├── Chapter01 └── example bash_profile.sh ├── Chapter02 ├── Building_text_classifier.py ├── bag_of_word.py ├── chunking.py ├── stemming.py └── tokenization.py ├── Chapter03 ├── encryptdecrypt.py ├── filehandler.py ├── graphicmenu.py ├── photohandler.py ├── photohandler_1stpart.py └── tkencryptdecrypt.py ├── Chapter04 ├── Building_Naive_Bayes_classifier.py ├── Splitting_dataset.py ├── cross_validation.py ├── cross_validation_multivar.txt ├── data_multivar.txt ├── data_topic_modeling.txt ├── logistic_regression.py ├── sentiment_analysis.py └── topic_modeling.py ├── Chapter05 ├── bg.gif ├── bouncingball.py ├── gold.gif ├── mark.gif ├── painting.py ├── playerD.gif ├── playerL.gif ├── playerR.gif ├── playerU.gif ├── scroller.py ├── wallH.gif └── wallV.gif ├── Chapter06 ├── Blurring_Sharpening.py ├── Erosion_Dilation.py ├── Flipping.py ├── Image_Segmentation.py ├── Load_Display_Save.py ├── Scaling.py ├── image_1.jpg ├── image_2.jpg ├── image_3.jpg ├── image_4.jpg ├── image_5.jpg └── image_6.jpg ├── Chapter07 ├── 3dMaze.py ├── 3dModel.py ├── 3dObject.py ├── 3dWorld.py └── source_files │ ├── fonts │ └── FreeMonoBoldOblique.ttf │ ├── models │ ├── monkey.mtl │ ├── monkey.obj │ ├── simplecube.mtl │ └── simplecube.obj │ └── textures │ ├── Map.png │ ├── dunes3_512.jpg │ ├── ecubes │ ├── sbox_back.jpg │ ├── sbox_bottom.jpg │ ├── sbox_front.jpg │ ├── sbox_left.jpg │ ├── sbox_right.jpg │ └── sbox_top.jpg │ ├── floor.png │ ├── floor_nm.jpg │ ├── grass.jpg │ ├── inside_map0.png │ ├── inside_map1.png │ ├── inside_map2.png │ ├── mudnormal.jpg │ ├── rock1.jpg │ ├── squareblocks4.png │ ├── squareblocksred.png │ ├── stars.jpg │ ├── stripwood.jpg │ └── water.jpg ├── Chapter08 ├── Haarcascade_face_detector.py ├── face_recognizer.py ├── faces_dataset │ ├── test │ │ ├── .DS_Store │ │ ├── image_0019.jpg │ │ ├── image_0020.jpg │ │ ├── image_0021.jpg │ │ ├── image_0039.jpg │ │ ├── image_0040.jpg │ │ ├── image_0041.jpg │ │ ├── image_0087.jpg │ │ ├── image_0088.jpg │ │ └── image_0089.jpg │ └── train │ │ ├── person1 │ │ ├── .DS_Store │ │ ├── image_0001.jpg │ │ ├── image_0002.jpg │ │ ├── image_0003.jpg │ │ ├── image_0004.jpg │ │ ├── image_0005.jpg │ │ ├── image_0006.jpg │ │ ├── image_0007.jpg │ │ ├── image_0008.jpg │ │ ├── image_0009.jpg │ │ ├── image_0010.jpg │ │ ├── image_0011.jpg │ │ ├── image_0012.jpg │ │ ├── image_0013.jpg │ │ ├── image_0014.jpg │ │ ├── image_0015.jpg │ │ ├── image_0016.jpg │ │ ├── image_0017.jpg │ │ └── image_0018.jpg │ │ ├── person2 │ │ ├── .DS_Store │ │ ├── image_0022.jpg │ │ ├── image_0023.jpg │ │ ├── image_0024.jpg │ │ ├── image_0025.jpg │ │ ├── image_0026.jpg │ │ ├── image_0027.jpg │ │ ├── image_0028.jpg │ │ ├── image_0029.jpg │ │ ├── image_0030.jpg │ │ ├── image_0031.jpg │ │ ├── image_0032.jpg │ │ ├── image_0033.jpg │ │ ├── image_0034.jpg │ │ ├── image_0035.jpg │ │ ├── image_0036.jpg │ │ ├── image_0037.jpg │ │ └── image_0038.jpg │ │ └── person3 │ │ ├── .DS_Store │ │ ├── image_0069.jpg │ │ ├── image_0070.jpg │ │ ├── image_0071.jpg │ │ ├── image_0072.jpg │ │ ├── image_0073.jpg │ │ ├── image_0074.jpg │ │ ├── image_0075.jpg │ │ ├── image_0076.jpg │ │ ├── image_0077.jpg │ │ ├── image_0078.jpg │ │ ├── image_0079.jpg │ │ ├── image_0080.jpg │ │ ├── image_0081.jpg │ │ ├── image_0082.jpg │ │ ├── image_0083.jpg │ │ ├── image_0084.jpg │ │ ├── image_0085.jpg │ │ └── image_0086.jpg ├── haarcascade_eye.xml └── haarcascade_frontalface_alt.xml ├── Chapter09 ├── btntest.py ├── gpiokeys-events.py ├── gpiokeys-mouse.py ├── gpiokeys.py ├── ledtest.py ├── rgbled-part1.py ├── rgbled-rand.py ├── rgbled.py ├── rgbledrainbow.py ├── shtdwn.py └── shtdwn_full.py ├── Chapter10 ├── data.log ├── data_adc.py ├── data_local.py ├── del_data_lite.php ├── lcd_i2c.py ├── live_graph.py ├── live_graph_light.py ├── log_adc.py ├── log_graph.py ├── log_local.py ├── mysqlite_adc.py ├── mysqlite_local.py ├── show_data_lite.php └── xivelylog.py ├── Chapter11 ├── optical_charecter_recognition.py ├── visualize_characters.py └── words.data ├── Chapter12 ├── XLoBorg3-part1.py ├── XLoBorg3.py ├── avoidance.py ├── bug_drive.py ├── compassDrive.py ├── rover_drive.py ├── rover_drive_hwpwm.py ├── rover_drive_i2c.py ├── rover_drive_swpwm.py ├── rover_drivefwd.py ├── servoAdafruit.py ├── servo_control.py └── sonic.py ├── Chapter13 ├── matrixControl.py ├── matrixMenu.py ├── missileControl.py ├── missileMenu.py ├── robotarmControl.py ├── serialControl.py ├── serialMenu.py ├── serialTest.py ├── socketControl.py ├── socketMenu.py └── spiTest.py ├── Chapter14 ├── Euclidean_distance.py ├── Pearson_correlation.py ├── movie_rating.json └── movie_recommendations.py ├── LICENSE └── README.md /Chapter01/example bash_profile.sh: -------------------------------------------------------------------------------- 1 | function proxyenable { 2 | # Define proxy settings 3 | PROXY_ADDR="proxy.address.com:port" 4 | # Login name (leave blank if not required): 5 | LOGIN_USER="login_name" 6 | # Login Password (leave blank to prompt): 7 | LOGIN_PWD= 8 | #If login specified - check for password 9 | if [[ -z $LOGIN_USER ]]; then 10 | #No login for proxy 11 | PROXY_FULL=$PROXY_ADDR 12 | else 13 | #Login needed for proxy Prompt for password -s option hides input 14 | if [[ -z $LOGIN_PWD ]]; then 15 | read -s -p "Provide proxy password (then Enter):" LOGIN_PWD 16 | echo 17 | fi 18 | PROXY_FULL=$LOGIN_USER:$LOGIN_PWD@$PROXY_ADDR 19 | fi 20 | #Web Proxy Enable: http_proxy or HTTP_PROXY environment variables 21 | export http_proxy="http://$PROXY_FULL/" 22 | export HTTP_PROXY=$http_proxy 23 | export https_proxy="https://$PROXY_FULL/" 24 | export HTTPS_PROXY=$https_proxy 25 | export ftp_proxy="ftp://$PROXY_FULL/" 26 | export FTP_PROXY=$ftp_proxy 27 | #Remove info no longer needed from environment 28 | unset LOGIN_USER LOGIN_PWD PROXY_ADDR PROXY_FULL 29 | echo Proxy Enabled 30 | } 31 | 32 | function proxydisable { 33 | #Disable proxy values, apt-get and get settings 34 | unset http_proxy HTTP_PROXY https_proxy HTTPS_PROXY ftp_proxy FPT_PROXY 35 | echo Proxy Disabled 36 | } 37 | -------------------------------------------------------------------------------- /Chapter02/Building_text_classifier.py: -------------------------------------------------------------------------------- 1 | from sklearn.datasets import fetch_20newsgroups 2 | 3 | category_mapping = {'misc.forsale': 'Sellings', 'rec.motorcycles': 'Motorbikes', 4 | 'rec.sport.baseball': 'Baseball', 'sci.crypt': 'Cryptography', 5 | 'sci.space': 'OuterSpace'} 6 | 7 | training_content = fetch_20newsgroups(subset='train', 8 | categories=category_mapping.keys(), shuffle=True, random_state=7) 9 | 10 | # Feature extraction 11 | from sklearn.feature_extraction.text import CountVectorizer 12 | 13 | vectorizing = CountVectorizer() 14 | train_counts = vectorizing.fit_transform(training_content.data) 15 | print "\nDimensions of training data:", train_counts.shape 16 | 17 | # Training a classifier 18 | from sklearn.naive_bayes import MultinomialNB 19 | from sklearn.feature_extraction.text import TfidfTransformer 20 | 21 | input_content = [ 22 | "The curveballs of right handed pitchers tend to curve to the left", 23 | "Caesar cipher is an ancient form of encryption", 24 | "This two-wheeler is really good on slippery roads" 25 | ] 26 | 27 | # tf-idf transformer 28 | tfidf_transformer = TfidfTransformer() 29 | train_tfidf = tfidf_transformer.fit_transform(train_counts) 30 | 31 | # Multinomial Naive Bayes classifier 32 | classifier = MultinomialNB().fit(train_tfidf, training_content.target) 33 | 34 | input_counts = vectorizing.transform(input_content) 35 | 36 | input_tfidf = tfidf_transformer.transform(input_counts) 37 | 38 | # Predict the output categories 39 | categories_prediction = classifier.predict(input_tfidf) 40 | 41 | # Print the outputs 42 | for sentence, category in zip(input_content, categories_prediction): 43 | print '\nInput:', sentence, '\nPredicted category:', \ 44 | category_mapping[training_content.target_names[category]] 45 | -------------------------------------------------------------------------------- /Chapter02/bag_of_word.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from nltk.corpus import brown 3 | from chunking import splitter 4 | 5 | if __name__=='__main__': 6 | # Read the data from the Brown corpus 7 | content = ' '.join(brown.words()[:10000]) 8 | 9 | # Number of words in each chunk 10 | num_of_words = 2000 11 | num_chunks = [] 12 | count = 0 13 | texts_chunk = splitter(content, num_of_words) 14 | 15 | for text in texts_chunk: 16 | num_chunk = {'index': count, 'text': text} 17 | num_chunks.append(num_chunk) 18 | count += 1 19 | 20 | # Extract document term matrix 21 | from sklearn.feature_extraction.text import CountVectorizer 22 | 23 | # Extract document term matrix 24 | from sklearn.feature_extraction.text import CountVectorizer 25 | 26 | vectorizer = CountVectorizer(min_df=5, max_df=.95) 27 | matrix = vectorizer.fit_transform([num_chunk['text'] for num_chunk in num_chunks]) 28 | 29 | vocabulary = np.array(vectorizer.get_feature_names()) 30 | print "\nVocabulary:" 31 | print vocabulary 32 | 33 | print "\nDocument term matrix:" 34 | chunks_name = ['Chunk-0', 'Chunk-1', 'Chunk-2', 'Chunk-3', 'Chunk-4'] 35 | 36 | formatted_row = '{:>12}' * (len(chunks_name) + 1) 37 | print '\n', formatted_row.format('Word', *chunks_name), '\n' 38 | 39 | for word, item in zip(vocabulary, matrix.T): 40 | # 'item' is a 'csr_matrix' data structure 41 | result = [str(x) for x in item.data] 42 | print formatted_row.format(word, *result) 43 | -------------------------------------------------------------------------------- /Chapter02/chunking.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from nltk.corpus import brown 3 | 4 | # Split a text into chunks 5 | def splitter(content, num_of_words): 6 | words = content.split(' ') 7 | result = [] 8 | 9 | current_count = 0 10 | current_words = [] 11 | 12 | for word in words: 13 | current_words.append(word) 14 | current_count += 1 15 | 16 | if current_count == num_of_words: 17 | result.append(' '.join(current_words)) 18 | current_words = [] 19 | current_count = 0 20 | 21 | result.append(' '.join(current_words)) 22 | return result 23 | 24 | 25 | if __name__=='__main__': 26 | # Read the data from the Brown corpus 27 | content = ' '.join(brown.words()[:10000]) 28 | 29 | # Number of words in each chunk 30 | num_of_words = 1600 31 | 32 | chunks = [] 33 | counter = 0 34 | 35 | num_text_chunks = splitter(content, num_of_words) 36 | print "Number of text chunks =", len(num_text_chunks) 37 | -------------------------------------------------------------------------------- /Chapter02/stemming.py: -------------------------------------------------------------------------------- 1 | from nltk.stem.porter import PorterStemmer 2 | from nltk.stem.lancaster import LancasterStemmer 3 | from nltk.stem.snowball import SnowballStemmer 4 | 5 | words = ['ability', 'baby', 'college', 'playing', 'is', 'dream', 'election', 'beaches', 'image', 'group', 'happy'] 6 | 7 | # Compare different stemmers 8 | stemmers = ['PORTER', 'LANCASTER', 'SNOWBALL'] 9 | 10 | stem_porter = PorterStemmer() 11 | stem_lancaster = LancasterStemmer() 12 | stem_snowball = SnowballStemmer('english') 13 | 14 | formatted_row = '{:>16}' * (len(stemmers) + 1) 15 | print '\n', formatted_row.format('WORD', *stemmers), '\n' 16 | 17 | for word in words: 18 | stem_words = [stem_porter.stem(word), 19 | stem_lancaster.stem(word), 20 | stem_snowball.stem(word)] 21 | print formatted_row.format(word, *stem_words) 22 | -------------------------------------------------------------------------------- /Chapter02/tokenization.py: -------------------------------------------------------------------------------- 1 | 2 | text = "Tokenization is the process of dividing text into a set of meaningful pieces. These pieces are called tokens." 3 | 4 | # Sentence tokenization 5 | from nltk.tokenize import sent_tokenize 6 | 7 | tokenize_list_sent = sent_tokenize(text) 8 | 9 | print "\nSentence tokenizer:" 10 | print tokenize_list_sent 11 | 12 | # Create a new word tokenizer 13 | from nltk.tokenize import word_tokenize 14 | print "\nWord tokenizer:" 15 | print word_tokenize(text) 16 | 17 | # Create a new WordPunctokenizer 18 | from nltk.tokenize import WordPunctTokenizer 19 | word_punct_tokenizer = WordPunctTokenizer() 20 | print "\nWord punct tokenizer:" 21 | print word_punct_tokenizer.tokenize(text) 22 | -------------------------------------------------------------------------------- /Chapter03/encryptdecrypt.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | #encryptdecrypt.py 3 | 4 | #Takes the input_text and encrypts it, returning the result 5 | def encryptText(input_text,key): 6 | input_text=input_text.upper() 7 | result = "" 8 | for letter in input_text: 9 | #Ascii Uppercase 65-90 Lowercase 97-122 (Full range 32-126) 10 | ascii_value=ord(letter) 11 | #Exclude non-characters from encryption 12 | if (ord("A") > ascii_value) or (ascii_value > ord("Z")): 13 | result+=letter 14 | else: 15 | #Apply encryption key 16 | key_value = ascii_value+key 17 | #Ensure we just use A-Z regardless of key 18 | if not((ord("A")) < key_value < ord("Z")): 19 | key_value=ord("A") + (key_value-ord("A"))% 20 | (ord("Z")-ord("A")+1) 21 | #Add the encoded letter to the result string 22 | result+=str(chr(key_value)) 23 | return result 24 | 25 | #Test function, only called if script executed directly 26 | def main(): 27 | print ("Please enter text to scramble:") 28 | #Get user input 29 | try: 30 | user_input = input() 31 | scrambled_result = encryptText(user_input,10) 32 | print ("Result: " + scrambled_result) 33 | print ("To un-scramble, press enter again") 34 | input() 35 | unscrambled_result = encryptText(scrambled_result,-10) 36 | print ("Result: " + unscrambled_result) 37 | except UnicodeDecodeError: 38 | print ("Sorry: Only ASCII Characters are supported") 39 | 40 | if __name__=="__main__": 41 | main() 42 | #End 43 | -------------------------------------------------------------------------------- /Chapter03/filehandler.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | #filehandler.py 3 | import os 4 | import shutil 5 | import photohandler as PH 6 | from operator import itemgetter 7 | 8 | FOLDERSONLY=True 9 | DEBUG=True 10 | defaultpath="" 11 | NAME=0 12 | DATE=1 13 | 14 | class FileList: 15 | def __init__(self,folder): 16 | """Class constructor""" 17 | self.folder=folder 18 | self.listFileDates() 19 | 20 | def getPhotoNamedates(self): 21 | """returns the list of filenames and dates""" 22 | return self.photo_namedates 23 | 24 | def listFileDates(self): 25 | """Generate list of filenames and dates""" 26 | self.photo_namedates = list() 27 | if os.path.isdir(self.folder): 28 | for filename in os.listdir(self.folder): 29 | if filename.lower().endswith(".jpg"): 30 | aPhoto = PH.Photo(os.path.join(self.folder,filename)) 31 | if aPhoto.filevalid: 32 | if (DEBUG):print("NameDate: %s %s"% 33 | (filename,aPhoto.getDate())) 34 | self.photo_namedates.append((filename, 35 | aPhoto.getDate())) 36 | self.photo_namedates = sorted(self.photo_namedates, 37 | key=lambda date: date[DATE]) 38 | 39 | def genFolders(self): 40 | """function to generate folders""" 41 | for i,namedate in enumerate(self.getPhotoNamedates()): 42 | #Remove the - from the date format 43 | new_folder=namedate[DATE].replace("-","") 44 | newpath = os.path.join(self.folder,new_folder) 45 | #If path does not exist create folder 46 | if not os.path.exists(newpath): 47 | if (DEBUG):print ("New Path: %s" % newpath) 48 | os.makedirs(newpath) 49 | if (DEBUG):print ("Found file: %s move to %s" % 50 | (namedate[NAME],newpath)) 51 | src_file = os.path.join(self.folder,namedate[NAME]) 52 | dst_file = os.path.join(newpath,namedate[NAME]) 53 | try: 54 | if (DEBUG):print ("File moved %s to %s" % 55 | (src_file, dst_file)) 56 | if (FOLDERSONLY==False):shutil.move(src_file, dst_file) 57 | except IOError: 58 | print ("Skipped: File not found") 59 | 60 | def main(): 61 | """called only when run directly, allowing module testing""" 62 | import tkinter as TK 63 | from tkinter import filedialog 64 | app = TK.Tk() 65 | app.withdraw() 66 | dirname = TK.filedialog.askdirectory(parent=app, 67 | initialdir=defaultpath, 68 | title='Select your pictures folder') 69 | if dirname != "": 70 | ourFileList=FileList(dirname) 71 | ourFileList.genFolders() 72 | 73 | if __name__=="__main__": 74 | main() 75 | #End 76 | -------------------------------------------------------------------------------- /Chapter03/graphicmenu.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # graphicmenu.py 3 | import tkinter as tk 4 | from subprocess import call 5 | import threading 6 | 7 | #Define applications ["Display name","command"] 8 | leafpad = ["Leafpad","leafpad"] 9 | scratch = ["Scratch","scratch"] 10 | pistore = ["Pi Store","pistore"] 11 | app_list = [leafpad,scratch,pistore] 12 | APP_NAME = 0 13 | APP_CMD = 1 14 | 15 | class runApplictionThread(threading.Thread): 16 | def __init__(self,app_cmd): 17 | threading.Thread.__init__(self) 18 | self.cmd = app_cmd 19 | def run(self): 20 | #Run the command, if valid 21 | try: 22 | call(self.cmd) 23 | except: 24 | print ("Unable to run: %s" % self.cmd) 25 | 26 | class appButtons: 27 | def __init__(self,gui,app_index): 28 | #Add the buttons to window 29 | btn = tk.Button(gui, text=app_list[app_index][APP_NAME], 30 | width=30, command=self.startApp) 31 | btn.pack() 32 | self.app_cmd=app_list[app_index][APP_CMD] 33 | def startApp(self): 34 | print ("APP_CMD: %s" % self.app_cmd) 35 | runApplictionThread(self.app_cmd).start() 36 | 37 | root = tk.Tk() 38 | root.title("App Menu") 39 | prompt = ' Select an application ' 40 | label1 = tk.Label(root, text=prompt, width=len(prompt), bg='green') 41 | label1.pack() 42 | #Create menu buttons from app_list 43 | for index, app in enumerate(app_list): 44 | appButtons(root,index) 45 | #Run the tk window 46 | root.mainloop() 47 | #End -------------------------------------------------------------------------------- /Chapter03/photohandler.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | #photohandler.py 3 | from PIL import Image 4 | from PIL import ExifTags 5 | import datetime 6 | import os 7 | 8 | #set module values 9 | previewsize=240,240 10 | defaultimagepreview="./preview.ppm" 11 | filedate_to_use="Exif DateTime" 12 | #Define expected inputs 13 | ARG_IMAGEFILE=1 14 | ARG_LENGTH=2 15 | 16 | class Photo: 17 | def __init__(self,filename): 18 | """Class constructor""" 19 | self.filename=filename 20 | self.filevalid=False 21 | self.exifvalid=False 22 | img=self.initImage() 23 | if self.filevalid==True: 24 | self.initExif(img) 25 | self.initDates() 26 | 27 | def initImage(self): 28 | """opens the image and confirms if valid, returns Image""" 29 | try: 30 | img=Image.open(self.filename) 31 | self.filevalid=True 32 | except IOError: 33 | print ("Target image not found/valid %s" % 34 | (self.filename)) 35 | img=None 36 | self.filevalid=False 37 | return img 38 | 39 | def initExif(self,image): 40 | """gets any Exif data from the photo""" 41 | try: 42 | self.exif_info={ 43 | ExifTags.TAGS[x]:y 44 | for x,y in image._getexif().items() 45 | if x in ExifTags.TAGS 46 | } 47 | self.exifvalid=True 48 | except AttributeError: 49 | print ("Image has no Exif Tags") 50 | self.exifvalid=False 51 | 52 | 53 | def initDates(self): 54 | """determines the date the photo was taken""" 55 | #Gather all the times available into YYYY-MM-DD format 56 | self.filedates={} 57 | if self.exifvalid: 58 | #Get the date info from Exif info 59 | exif_ids=["DateTime","DateTimeOriginal", 60 | "DateTimeDigitized"] 61 | for id in exif_ids: 62 | dateraw=self.exif_info[id] 63 | self.filedates["Exif "+id]=\ 64 | dateraw[:10].replace(":","-") 65 | modtimeraw = os.path.getmtime(self.filename) 66 | self.filedates["File ModTime"]="%s" %\ 67 | datetime.datetime.fromtimestamp(modtimeraw).date() 68 | createtimeraw = os.path.getctime(self.filename) 69 | self.filedates["File CreateTime"]="%s" %\ 70 | datetime.datetime.fromtimestamp(createtimeraw).date() 71 | 72 | def getDate(self): 73 | """returns the date the image was taken""" 74 | try: 75 | date = self.filedates[filedate_to_use] 76 | except KeyError: 77 | print ("Exif Date not found") 78 | date = self.filedates["File ModTime"] 79 | return date 80 | 81 | def previewPhoto(self): 82 | """creates a thumbnail image suitable for tk to display""" 83 | imageview=self.initImage() 84 | imageview=imageview.convert('RGB') 85 | imageview.thumbnail(previewsize,Image.ANTIALIAS) 86 | imageview.save(defaultimagepreview,format='ppm') 87 | return defaultimagepreview 88 | 89 | #Module test code 90 | def dispPreview(aPhoto): 91 | """Create a test GUI""" 92 | import tkinter as TK 93 | 94 | #Define the app window 95 | app = TK.Tk() 96 | app.title("Photo View Demo") 97 | 98 | #Define TK objects 99 | # create an empty canvas object the same size as the image 100 | canvas = TK.Canvas(app, width=previewsize[0], 101 | height=previewsize[1]) 102 | canvas.grid(row=0,rowspan=2) 103 | # Add list box to display the photo data 104 | #(including xyscroll bars) 105 | photoInfo=TK.Variable() 106 | lbPhotoInfo=TK.Listbox(app,listvariable=photoInfo, 107 | height=18,width=45, 108 | font=("monospace",10)) 109 | yscroll=TK.Scrollbar(command=lbPhotoInfo.yview, 110 | orient=TK.VERTICAL) 111 | xscroll=TK.Scrollbar(command=lbPhotoInfo.xview, 112 | orient=TK.HORIZONTAL) 113 | lbPhotoInfo.configure(xscrollcommand=xscroll.set, 114 | yscrollcommand=yscroll.set) 115 | lbPhotoInfo.grid(row=0,column=1,sticky=TK.N+TK.S) 116 | yscroll.grid(row=0,column=2,sticky=TK.N+TK.S) 117 | xscroll.grid(row=1,column=1,sticky=TK.N+TK.E+TK.W) 118 | 119 | # Generate the preview image 120 | preview_filename = aPhoto.previewPhoto() 121 | photoImg = TK.PhotoImage(file=preview_filename) 122 | # anchor image to NW corner 123 | canvas.create_image(0,0, anchor=TK.NW, image=photoImg) 124 | 125 | # Populate infoList with dates and exif data 126 | infoList=[] 127 | for key,value in aPhoto.filedates.items(): 128 | infoList.append(key.ljust(25) + value) 129 | if aPhoto.exifvalid: 130 | for key,value in aPhoto.exif_info.items(): 131 | infoList.append(key.ljust(25) + str(value)) 132 | # Set listvariable with the infoList 133 | photoInfo.set(tuple(infoList)) 134 | 135 | app.mainloop() 136 | 137 | def main(): 138 | """called only when run directly, allowing module testing""" 139 | import sys 140 | #Check the arguments 141 | if len(sys.argv) == ARG_LENGTH: 142 | print ("Command: %s" %(sys.argv)) 143 | #Create an instance of the Photo class 144 | viewPhoto = Photo(sys.argv[ARG_IMAGEFILE]) 145 | #Test the module by running a GUI 146 | if viewPhoto.filevalid==True: 147 | dispPreview(viewPhoto) 148 | else: 149 | print ("Usage: photohandler.py imagefile") 150 | 151 | if __name__=='__main__': 152 | main() 153 | #End 154 | 155 | -------------------------------------------------------------------------------- /Chapter03/photohandler_1stpart.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | #photohandler.py 3 | from PIL import Image 4 | from PIL import ExifTags 5 | import datetime 6 | import os 7 | 8 | #set module values 9 | previewsize=240,240 10 | defaultimagepreview="./preview.ppm" 11 | filedate_to_use="Exif DateTime" 12 | #Define expected inputs 13 | ARG_IMAGEFILE=1 14 | ARG_LENGTH=2 15 | 16 | class Photo: 17 | def __init__(self,filename): 18 | """Class constructor""" 19 | self.filename=filename 20 | self.filevalid=False 21 | self.exifvalid=False 22 | img=self.initImage() 23 | if self.filevalid==True: 24 | self.initExif(img) 25 | self.initDates() 26 | 27 | def initImage(self): 28 | """opens the image and confirms if valid, returns Image""" 29 | try: 30 | img=Image.open(self.filename) 31 | self.filevalid=True 32 | except IOError: 33 | print ("Target image not found/valid %s" % 34 | (self.filename)) 35 | img=None 36 | self.filevalid=False 37 | return img 38 | 39 | def initExif(self,image): 40 | """gets any Exif data from the photo""" 41 | try: 42 | self.exif_info={ 43 | ExifTags.TAGS[x]:y 44 | for x,y in image._getexif().items() 45 | if x in ExifTags.TAGS 46 | } 47 | self.exifvalid=True 48 | except AttributeError: 49 | print ("Image has no Exif Tags") 50 | self.exifvalid=False 51 | 52 | 53 | def initDates(self): 54 | """determines the date the photo was taken""" 55 | #Gather all the times available into YYYY-MM-DD format 56 | self.filedates={} 57 | if self.exifvalid: 58 | #Get the date info from Exif info 59 | exif_ids=["DateTime","DateTimeOriginal", 60 | "DateTimeDigitized"] 61 | for id in exif_ids: 62 | dateraw=self.exif_info[id] 63 | self.filedates["Exif "+id]=\ 64 | dateraw[:10].replace(":","-") 65 | modtimeraw = os.path.getmtime(self.filename) 66 | self.filedates["File ModTime"]="%s" %\ 67 | datetime.datetime.fromtimestamp(modtimeraw).date() 68 | createtimeraw = os.path.getctime(self.filename) 69 | self.filedates["File CreateTime"]="%s" %\ 70 | datetime.datetime.fromtimestamp(createtimeraw).date() 71 | 72 | def getDate(self): 73 | """returns the date the image was taken""" 74 | try: 75 | date = self.filedates[filedate_to_use] 76 | except KeyError: 77 | print ("Exif Date not found") 78 | date = self.filedates["File ModTime"] 79 | return date 80 | 81 | def previewPhoto(self): 82 | """creates a thumbnail image suitable for tk to display""" 83 | imageview=self.initImage() 84 | imageview=imageview.convert('RGB') 85 | imageview.thumbnail(previewsize,Image.ANTIALIAS) 86 | imageview.save(defaultimagepreview,format='ppm') 87 | return defaultimagepreview 88 | 89 | -------------------------------------------------------------------------------- /Chapter03/tkencryptdecrypt.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | #tkencryptdecrypt 3 | import encryptdecrypt as ENC 4 | import tkinter as TK 5 | 6 | def encryptButton(): 7 | encryptvalue.set(ENC.encryptText(encryptvalue.get(), 8 | keyvalue.get())) 9 | 10 | def decryptButton(): 11 | encryptvalue.set(ENC.encryptText(encryptvalue.get(), 12 | -keyvalue.get())) 13 | #Define Tkinter application 14 | root=TK.Tk() 15 | root.title("Encrypt/Decrypt GUI") 16 | #Set control & test value 17 | encryptvalue = TK.StringVar() 18 | encryptvalue.set("My Message") 19 | keyvalue = TK.IntVar() 20 | keyvalue.set(20) 21 | prompt="Enter message to encrypt:" 22 | key="Key:" 23 | 24 | label1=TK.Label(root,text=prompt,width=len(prompt),bg='green') 25 | textEnter=TK.Entry(root,textvariable=encryptvalue, 26 | width=len(prompt)) 27 | encryptButton=TK.Button(root,text="Encrypt",command=encryptButton) 28 | decryptButton=TK.Button(root,text="Decrypt",command=decryptButton) 29 | label2=TK.Label(root,text=key,width=len(key)) 30 | keyEnter=TK.Entry(root,textvariable=keyvalue,width=8) 31 | #Set layout 32 | label1.grid(row=0,columnspan=2,sticky=TK.E+TK.W) 33 | textEnter.grid(row=1,columnspan=2,sticky=TK.E+TK.W) 34 | encryptButton.grid(row=2,column=0,sticky=TK.E) 35 | decryptButton.grid(row=2,column=1,sticky=TK.W) 36 | label2.grid(row=3,column=0,sticky=TK.E) 37 | keyEnter.grid(row=3,column=1,sticky=TK.W) 38 | 39 | TK.mainloop() 40 | -------------------------------------------------------------------------------- /Chapter04/Building_Naive_Bayes_classifier.py: -------------------------------------------------------------------------------- 1 | from sklearn.naive_bayes import GaussianNB 2 | import numpy as np 3 | import matplotlib.pyplot as plt 4 | 5 | in_file = 'data_multivar.txt' 6 | a = [] 7 | b = [] 8 | with open(in_file, 'r') as f: 9 | for line in f.readlines(): 10 | data = [float(x) for x in line.split(',')] 11 | a.append(data[:-1]) 12 | b.append(data[-1]) 13 | a = np.array(a) 14 | b = np.array(b) 15 | 16 | classification_gaussiannb = GaussianNB() 17 | classification_gaussiannb.fit(a, b) 18 | b_pred = classification_gaussiannb.predict(a) 19 | 20 | correctness = 100.0 * (b == b_pred).sum() / a.shape[0] 21 | print "correctness of the classification =", round(correctness, 2), "%" 22 | 23 | 24 | 25 | def plot_classification(classification_gaussiannb, a , b): 26 | 27 | a_min, a_max = min(a[:, 0]) - 1.0, max(a[:, 0]) + 1.0 28 | b_min, b_max = min(a[:, 1]) - 1.0, max(a[:, 1]) + 1.0 29 | 30 | step_size = 0.01 31 | 32 | a_values, b_values = np.meshgrid(np.arange(a_min, a_max, step_size), np.arange(b_min, b_max, step_size)) 33 | 34 | mesh_output1 = classification_gaussiannb.predict(np.c_[a_values.ravel(), b_values.ravel()]) 35 | 36 | mesh_output2 = mesh_output1.reshape(a_values.shape) 37 | 38 | plt.figure() 39 | 40 | plt.pcolormesh(a_values, b_values, mesh_output2, cmap=plt.cm.gray) 41 | 42 | plt.scatter(a[:, 0], a[:, 1], c=b , s=80, edgecolors='black', linewidth=1,cmap=plt.cm.Paired) 43 | # specify the boundaries of the figure 44 | plt.xlim(a_values.min(), a_values.max()) 45 | plt.ylim(b_values.min(), b_values.max()) 46 | # specify the ticks on the X and Y axes 47 | plt.xticks((np.arange(int(min(a[:, 0])-1), int(max(a[:, 0])+1), 1.0))) 48 | plt.yticks((np.arange(int(min(a[:, 1])-1), int(max(a[:, 1])+1), 1.0))) 49 | plt.show() 50 | 51 | plot_classification(classification_gaussiannb, a, b) 52 | 53 | 54 | -------------------------------------------------------------------------------- /Chapter04/Splitting_dataset.py: -------------------------------------------------------------------------------- 1 | from sklearn import cross_validation 2 | from sklearn.naive_bayes import GaussianNB 3 | import numpy as np 4 | import matplotlib.pyplot as plt 5 | 6 | in_file = 'data_multivar.txt' 7 | a = [] 8 | b = [] 9 | with open(in_file, 'r') as f: 10 | for line in f.readlines(): 11 | data = [float(x) for x in line.split(',')] 12 | a.append(data[:-1]) 13 | b.append(data[-1]) 14 | a = np.array(a) 15 | b = np.array(b) 16 | 17 | a_training, a_testing, b_training, b_testing = cross_validation.train_test_split(a, b, 18 | test_size=0.25, random_state=5) 19 | classification_gaussiannb_new = GaussianNB() 20 | classification_gaussiannb_new.fit(a_training, b_training) 21 | 22 | 23 | b_test_pred = classification_gaussiannb_new.predict(a_testing) 24 | 25 | correctness = 100.0 * (b_testing == b_test_pred).sum() / a_testing.shape[0] 26 | print "correctness of the classification =", round(correctness, 2), "%" 27 | 28 | def plot_classification(classification_gaussiannb_new, a_testing , b_testing): 29 | 30 | a_min, a_max = min(a_testing[:, 0]) - 1.0, max(a_testing[:, 0]) + 1.0 31 | b_min, b_max = min(a_testing[:, 1]) - 1.0, max(a_testing[:, 1]) + 1.0 32 | 33 | step_size = 0.01 34 | 35 | a_values, b_values = np.meshgrid(np.arange(a_min, a_max, step_size), np.arange(b_min, b_max, step_size)) 36 | 37 | 38 | mesh_output = classification_gaussiannb_new.predict(np.c_[a_values.ravel(), b_values.ravel()]) 39 | 40 | mesh_output = mesh_output.reshape(a_values.shape) 41 | 42 | plt.figure() 43 | 44 | plt.pcolormesh(a_values, b_values, mesh_output, cmap=plt.cm.gray) 45 | 46 | plt.scatter(a_testing[:, 0], a_testing[:, 1], c=b_testing , s=80, edgecolors='black', linewidth=1,cmap=plt.cm.Paired) 47 | # specify the boundaries of the figure 48 | plt.xlim(a_values.min(), a_values.max()) 49 | plt.ylim(b_values.min(), b_values.max()) 50 | # specify the ticks on the X and Y axes 51 | plt.xticks((np.arange(int(min(a_testing[:, 0])-1), int(max(a_testing[:, 0])+1), 1.0))) 52 | plt.yticks((np.arange(int(min(a_testing[:, 1])-1), int(max(a_testing[:, 1])+1), 1.0))) 53 | plt.show() 54 | 55 | plot_classification(classification_gaussiannb_new, a_testing, b_testing) 56 | -------------------------------------------------------------------------------- /Chapter04/cross_validation.py: -------------------------------------------------------------------------------- 1 | from sklearn import cross_validation 2 | from sklearn.naive_bayes import GaussianNB 3 | import numpy as np 4 | 5 | in_file = 'cross_validation_multivar.txt' 6 | a = [] 7 | b = [] 8 | with open(in_file, 'r') as f: 9 | for line in f.readlines(): 10 | data = [float(x) for x in line.split(',')] 11 | a.append(data[:-1]) 12 | b.append(data[-1]) 13 | a = np.array(a) 14 | b = np.array(b) 15 | 16 | classification_gaussiannb = GaussianNB() 17 | 18 | num_of_validations = 5 19 | accuracy = cross_validation.cross_val_score(classification_gaussiannb, a, b, scoring='accuracy', cv=num_of_validations) 20 | print "Accuracy: " + str(round(100* accuracy.mean(), 2)) + "%" 21 | f1 = cross_validation.cross_val_score(classification_gaussiannb, a, b, scoring='f1_weighted', cv=num_of_validations) 22 | print "f1: " + str(round(100*f1.mean(), 2)) + "%" 23 | precision = cross_validation.cross_val_score(classification_gaussiannb,a, b, scoring='precision_weighted', cv=num_of_validations) 24 | print "Precision: " + str(round(100*precision.mean(), 2)) + "%" 25 | recall = cross_validation.cross_val_score(classification_gaussiannb, a, b, scoring='recall_weighted', cv=num_of_validations) 26 | print "Recall: " + str(round(100*recall.mean(), 2)) + "%" 27 | -------------------------------------------------------------------------------- /Chapter04/data_multivar.txt: -------------------------------------------------------------------------------- 1 | 5.35,4.48,0 2 | 6.72,5.37,0 3 | 3.57,5.25,0 4 | 4.77,7.65,1 5 | 2.25,4.07,1 6 | 6.08,3.01,1 7 | 4.91,5.52,0 8 | 5.79,4.09,0 9 | 5.03,5.92,0 10 | 5.51,7.32,1 11 | 3.49,4.08,1 12 | 7.32,2.71,1 13 | 4.5,4.76,0 14 | 5.35,4.94,0 15 | 5.18,4.91,0 16 | 4.77,9.15,1 17 | 2.5,4.35,1 18 | 7.94,2.91,1 19 | 5.5,4.64,0 20 | 5.62,3.42,0 21 | 4.15,5.95,0 22 | 5.04,8.56,1 23 | 2.22,4.78,1 24 | 7.77,4.21,1 25 | 5.36,4.24,0 26 | 4.82,5.52,0 27 | 4.23,5.83,0 28 | 3.74,8.74,1 29 | 1.7,4.53,1 30 | 7.0,2.86,1 31 | 4.73,4.12,0 32 | 6.4,4.21,0 33 | 4.4,6.27,0 34 | 5.72,8.75,1 35 | 3.0,3.56,1 36 | 6.48,3.14,1 37 | 4.33,4.09,0 38 | 5.16,4.34,0 39 | 5.67,5.67,0 40 | 3.88,7.5,1 41 | 3.41,4.62,1 42 | 6.76,3.71,1 43 | 4.02,5.46,0 44 | 6.18,5.67,0 45 | 4.9,5.3,0 46 | 5.82,9.13,1 47 | 2.43,2.87,1 48 | 6.12,3.68,1 49 | 5.61,3.98,0 50 | 5.76,5.96,0 51 | 4.82,5.41,0 52 | 4.59,7.28,1 53 | 2.51,2.99,1 54 | 6.92,2.62,1 55 | 4.47,5.88,0 56 | 6.01,5.51,0 57 | 3.65,6.05,0 58 | 5.13,7.98,1 59 | 2.43,4.81,1 60 | 6.68,2.32,1 61 | 5.6,4.7,0 62 | 6.01,5.51,0 63 | 4.97,5.89,0 64 | 5.15,7.59,1 65 | 3.1,3.83,1 66 | 6.83,3.8,1 67 | 4.87,5.65,0 68 | 6.63,5.24,0 69 | 3.93,5.2,0 70 | 4.88,8.49,1 71 | 1.0,4.36,1 72 | 6.82,2.77,1 73 | 4.45,4.57,0 74 | 4.36,4.85,0 75 | 5.45,5.62,0 76 | 5.0,8.02,1 77 | 2.16,4.23,1 78 | 8.02,3.3,1 79 | 5.31,5.46,0 80 | 6.03,5.47,0 81 | 4.57,4.2,0 82 | 4.22,8.34,1 83 | 1.8,3.69,1 84 | 7.49,2.87,1 85 | 5.99,5.15,0 86 | 5.86,4.67,0 87 | 5.71,5.63,0 88 | 5.05,7.84,1 89 | 3.1,3.02,1 90 | 6.46,2.71,1 91 | 4.9,4.71,0 92 | 5.95,4.45,0 93 | 4.17,5.91,0 94 | 5.33,7.41,1 95 | 3.26,3.86,1 96 | 7.59,3.27,1 97 | 5.39,6.14,0 98 | 4.86,4.99,0 99 | 5.01,6.54,0 100 | 4.12,8.27,1 101 | 1.74,6.65,1 102 | 6.61,2.62,1 103 | 5.08,4.85,0 104 | 6.08,4.47,0 105 | 4.31,6.89,0 106 | 5.12,6.69,1 107 | 2.64,4.62,1 108 | 6.71,3.43,1 109 | 5.31,6.93,0 110 | 5.89,5.53,0 111 | 4.25,6.34,0 112 | 5.32,8.82,1 113 | 3.36,4.69,1 114 | 7.04,2.77,1 115 | 6.08,5.5,0 116 | 5.71,4.76,0 117 | 4.93,4.77,0 118 | 4.91,6.46,1 119 | 3.3,3.92,1 120 | 5.89,2.2,1 121 | 4.6,6.67,0 122 | 5.81,4.58,0 123 | 5.52,6.0,0 124 | 5.34,6.91,1 125 | 2.68,3.65,1 126 | 6.93,4.01,1 127 | 4.97,5.46,0 128 | 4.68,4.49,0 129 | 5.27,5.23,0 130 | 4.36,7.91,1 131 | 3.32,3.68,1 132 | 6.61,3.35,1 133 | 4.2,5.43,0 134 | 4.94,5.94,0 135 | 5.19,5.85,0 136 | 5.43,9.2,1 137 | 1.37,4.77,1 138 | 5.99,4.41,1 139 | 5.13,5.88,0 140 | 7.53,3.77,0 141 | 4.78,6.04,0 142 | 4.54,9.24,1 143 | 3.59,4.94,1 144 | 5.5,3.24,1 145 | 3.88,5.42,0 146 | 4.95,5.04,0 147 | 5.52,5.43,0 148 | 5.29,8.61,1 149 | 2.75,4.86,1 150 | 6.74,3.77,1 151 | 3.85,5.23,0 152 | 6.29,4.87,0 153 | 4.65,5.22,0 154 | 5.14,8.14,1 155 | 3.1,3.89,1 156 | 7.2,2.93,1 157 | 5.44,4.57,0 158 | 5.41,4.79,0 159 | 3.76,5.03,0 160 | 5.14,8.09,1 161 | 1.69,4.37,1 162 | 7.94,3.33,1 163 | 5.62,3.92,0 164 | 5.45,4.29,0 165 | 5.86,4.73,0 166 | 5.31,7.79,1 167 | 3.47,4.09,1 168 | 7.24,2.83,1 169 | 4.34,4.89,0 170 | 5.67,5.54,0 171 | 4.67,6.11,0 172 | 4.26,8.28,1 173 | 3.91,2.55,1 174 | 6.6,3.94,1 175 | 5.22,4.52,0 176 | 5.19,4.75,0 177 | 4.57,5.29,0 178 | 4.34,7.11,1 179 | 1.6,4.96,1 180 | 6.53,2.48,1 181 | 5.13,4.84,0 182 | 5.74,4.98,0 183 | 5.65,4.36,0 184 | 4.87,8.14,1 185 | 1.85,1.94,1 186 | 7.14,2.15,1 187 | 5.23,4.19,0 188 | 4.67,3.44,0 189 | 5.21,5.97,0 190 | 5.85,8.11,1 191 | 2.28,4.06,1 192 | 8.13,3.0,1 193 | 4.42,4.59,0 194 | 6.8,6.22,0 195 | 4.51,4.75,0 196 | 6.07,9.27,1 197 | 1.61,4.72,1 198 | 7.57,3.6,1 199 | 4.1,4.22,0 200 | 5.06,5.06,0 201 | 4.79,4.44,0 202 | 4.55,7.86,1 203 | 4.23,4.02,1 204 | 6.78,3.97,1 205 | 5.36,5.5,0 206 | 4.26,5.45,0 207 | 5.42,5.91,0 208 | 5.04,6.63,1 209 | 1.9,3.9,1 210 | 6.49,3.44,1 211 | 4.82,5.5,0 212 | 4.63,5.81,0 213 | 4.61,5.83,0 214 | 3.48,8.51,1 215 | 2.5,3.4,1 216 | 9.08,3.6,1 217 | 3.66,4.79,0 218 | 5.75,5.18,0 219 | 4.98,5.88,0 220 | 4.97,8.14,1 221 | 3.43,3.76,1 222 | 7.68,1.68,1 223 | 4.36,4.51,0 224 | 5.75,3.53,0 225 | 4.19,7.12,0 226 | 4.63,7.92,1 227 | 3.05,3.18,1 228 | 7.15,3.57,1 229 | 5.09,5.33,0 230 | 6.38,5.72,0 231 | 5.33,4.11,0 232 | 4.04,7.74,1 233 | 2.94,4.11,1 234 | 7.85,3.28,1 235 | 4.86,5.34,0 236 | 5.62,5.49,0 237 | 4.36,5.98,0 238 | 5.55,7.76,1 239 | 1.78,4.1,1 240 | 6.46,3.08,1 241 | 3.69,4.58,0 242 | 4.69,4.47,0 243 | 5.99,5.42,0 244 | 4.16,6.91,1 245 | 2.66,4.41,1 246 | 7.33,2.29,1 247 | 4.82,5.4,0 248 | 5.79,4.5,0 249 | 4.74,5.34,0 250 | 5.44,7.57,1 251 | 1.75,4.89,1 252 | 6.36,3.08,1 253 | 4.65,4.63,0 254 | 5.62,5.0,0 255 | 4.63,5.71,0 256 | 5.1,7.09,1 257 | 0.74,3.85,1 258 | 7.56,3.07,1 259 | 5.16,5.58,0 260 | 4.62,4.56,0 261 | 4.58,5.61,0 262 | 5.02,7.74,1 263 | 2.5,4.2,1 264 | 6.52,2.86,1 265 | 5.04,4.87,0 266 | 5.86,5.25,0 267 | 5.57,5.08,0 268 | 4.35,8.51,1 269 | 2.64,3.11,1 270 | 6.92,2.87,1 271 | 5.04,5.73,0 272 | 5.91,5.52,0 273 | 4.59,5.66,0 274 | 4.51,8.37,1 275 | 1.51,3.92,1 276 | 6.99,2.29,1 277 | 6.33,4.35,0 278 | 5.69,5.07,0 279 | 4.57,4.85,0 280 | 5.09,7.95,1 281 | 1.59,4.34,1 282 | 6.7,1.66,1 283 | 5.26,5.59,0 284 | 4.98,6.17,0 285 | 4.36,7.11,0 286 | 5.05,7.91,1 287 | 3.31,3.92,1 288 | 7.63,1.86,1 289 | 5.46,5.2,0 290 | 5.32,5.76,0 291 | 5.12,5.43,0 292 | 4.45,7.6,1 293 | 2.67,3.39,1 294 | 9.66,2.51,1 295 | 6.36,3.76,0 296 | 5.24,4.92,0 297 | 5.14,5.14,0 298 | 5.28,8.66,1 299 | 2.68,2.49,1 300 | 7.28,2.63,1 301 | -------------------------------------------------------------------------------- /Chapter04/data_topic_modeling.txt: -------------------------------------------------------------------------------- 1 | "Sugar is bad to consume. My sister likes to have sugar, but not my father." 2 | "My father spends a lot of time driving my sister around to dance practice." 3 | "Doctors suggest that driving may cause increased stress and blood pressure." 4 | "Sometimes I feel pressure to perform well at school, but my father never seems to drive my sister to do better." 5 | "Health experts say that Sugar is not good for your lifestyle." 6 | -------------------------------------------------------------------------------- /Chapter04/logistic_regression.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from sklearn import linear_model 3 | import matplotlib.pyplot as plt 4 | 5 | a = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]]) 6 | b = np.array([1, 1, 1, 2, 2, 2]) 7 | 8 | 9 | classification = linear_model.LogisticRegression(solver='liblinear', C=100) 10 | 11 | classification.fit(a, b) 12 | 13 | 14 | def plot_classification(classification, a , b): 15 | 16 | a_min, a_max = min(a[:, 0]) - 1.0, max(a[:, 0]) + 1.0 17 | b_min, b_max = min(a[:, 1]) - 1.0, max(a[:, 1]) + 1.0 18 | 19 | step_size = 0.01 20 | 21 | a_values, b_values = np.meshgrid(np.arange(a_min, a_max, step_size), np.arange(b_min, b_max, step_size)) 22 | 23 | mesh_output1 = classification.predict(np.c_[a_values.ravel(), b_values.ravel()]) 24 | 25 | mesh_output2 = mesh_output1.reshape(a_values.shape) 26 | 27 | plt.figure() 28 | 29 | plt.pcolormesh(a_values, b_values, mesh_output2, cmap=plt.cm.gray) 30 | 31 | plt.scatter(a[:, 0], a[:, 1], c=b , s=80, edgecolors='black', linewidth=1,cmap=plt.cm.Paired) 32 | # specify the boundaries of the figure 33 | plt.xlim(a_values.min(), a_values.max()) 34 | plt.ylim(b_values.min(), b_values.max()) 35 | # specify the ticks on the X and Y axes 36 | plt.xticks((np.arange(int(min(a[:, 0])-1), int(max(a[:, 0])+1), 1.0))) 37 | plt.yticks((np.arange(int(min(a[:, 1])-1), int(max(a[:, 1])+1), 1.0))) 38 | plt.show() 39 | 40 | 41 | plot_classification(classification, a, b) 42 | -------------------------------------------------------------------------------- /Chapter04/sentiment_analysis.py: -------------------------------------------------------------------------------- 1 | import nltk.classify.util 2 | from nltk.classify import NaiveBayesClassifier 3 | from nltk.corpus import movie_reviews 4 | 5 | def collect_features(word_list): 6 | word = [] 7 | return dict ([(word, True) for word in word_list]) 8 | 9 | 10 | if __name__=='__main__': 11 | plus_filenum = movie_reviews.fileids('pos') 12 | minus_filenum = movie_reviews.fileids('neg') 13 | 14 | feature_pluspts = [(collect_features(movie_reviews.words(fileids=[f])), 15 | 'Positive') for f in plus_filenum] 16 | feature_minuspts = [(collect_features(movie_reviews.words(fileids=[f])), 17 | 'Negative') for f in minus_filenum] 18 | 19 | threshold_fact = 0.8 20 | threshold_pluspts = int(threshold_fact * len(feature_pluspts)) 21 | threshold_minuspts = int(threshold_fact * len(feature_minuspts)) 22 | 23 | feature_training = feature_pluspts[:threshold_pluspts] + feature_minuspts[:threshold_minuspts] 24 | feature_testing = feature_pluspts[threshold_pluspts:] + feature_minuspts[threshold_minuspts:] 25 | print "\nNumber of training datapoints:", len(feature_training) 26 | print "Number of test datapoints:", len(feature_testing) 27 | 28 | # Train a Naive Bayes classifiers 29 | classifiers = NaiveBayesClassifier.train(feature_training) 30 | print "\nAccuracy of the classifiers:", nltk.classify.util.accuracy(classifiers,feature_testing) 31 | 32 | print "\nTop 10 most informative words:" 33 | for item in classifiers.most_informative_features()[:10]:print item[0] 34 | 35 | # Sample input reviews 36 | in_reviews = [ 37 | "The Movie was amazing", 38 | "the movie was dull. I would never recommend it to anyone.", 39 | "The cinematography is pretty great in the movie", 40 | "The direction was horrible and the story was all over the place" 41 | ] 42 | 43 | print "\nPredictions:" 44 | for review in in_reviews: 45 | print "\nReview:", review 46 | probdist = classifiers.prob_classify(collect_features(review.split())) 47 | predict_sentiment = probdist.max() 48 | 49 | print "Predicted sentiment:", predict_sentiment 50 | print "Probability:", round(probdist.prob(predict_sentiment), 2) 51 | -------------------------------------------------------------------------------- /Chapter04/topic_modeling.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | from nltk.tokenize import RegexpTokenizer 4 | from nltk.stem.snowball import SnowballStemmer 5 | from gensim import models, corpora 6 | from nltk.corpus import stopwords 7 | 8 | # Load input words 9 | def load_words(in_file): 10 | element = [] 11 | with open(in_file, 'r') as f: 12 | for line in f.readlines(): 13 | element.append(line[:-1]) 14 | return element 15 | 16 | # Class to preprocedure of text 17 | class Preprocedure(object): 18 | # Initialize various operators 19 | def __init__(self): 20 | # Create a regular expression tokenizer 21 | self.tokenizer = RegexpTokenizer(r'\w+') 22 | 23 | # get the list of stop words 24 | self.english_stop_words= stopwords.words('english') 25 | 26 | # Create a Snowball stemmer 27 | self.snowball_stemmer = SnowballStemmer('english') 28 | 29 | # Tokenizing, stop word removal, and stemming 30 | def procedure(self, in_data): 31 | # Tokenize the string 32 | 33 | token = self.tokenizer.tokenize(in_data.lower()) 34 | 35 | # Remove the stop words 36 | tokenized_stopwords = [x for x in token if not x in self.english_stop_words] 37 | 38 | # Perform stemming on the tokens 39 | token_stemming = [self.snowball_stemmer.stem(x) for x in tokenized_stopwords] 40 | 41 | return token_stemming 42 | 43 | if __name__=='__main__': 44 | # File containing linewise input data 45 | in_file = 'data_topic_modeling.txt' 46 | # Load words 47 | element = load_words(in_file) 48 | 49 | # Create a preprocedure object 50 | preprocedure = Preprocedure() 51 | 52 | # Create a list for processed documents 53 | processed_tokens = [preprocedure.procedure(x) for x in element] 54 | 55 | # Create a dictionary based on the tokenized documents 56 | dict_tokens = corpora.Dictionary(processed_tokens) 57 | 58 | corpus = [dict_tokens.doc2bow(text) for text in processed_tokens] 59 | 60 | # Generate the LDA model based on the corpus we just created 61 | num_of_topics = 2 62 | num_of_words = 4 63 | ldamodel = models.ldamodel.LdaModel(corpus, 64 | num_topics=num_of_topics, id2word=dict_tokens, passes=25) 65 | 66 | print "Most contributing words to the topics:" 67 | for item in ldamodel.print_topics(num_topics=num_of_topics, num_words=num_of_words): 68 | print "\nTopic", item[0], "==>", item[1] 69 | -------------------------------------------------------------------------------- /Chapter05/bg.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter05/bg.gif -------------------------------------------------------------------------------- /Chapter05/bouncingball.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # bouncingball.py 3 | import tkinter as TK 4 | import time 5 | 6 | VERT,HOREZ=0,1 7 | xTOP,yTOP = 0,1 8 | xBTM,yBTM = 2,3 9 | MAX_WIDTH,MAX_HEIGHT = 640,480 10 | xSTART,ySTART = 100,200 11 | BALL_SIZE=20 12 | RUNNING=True 13 | 14 | def close(): 15 | global RUNNING 16 | RUNNING=False 17 | root.destroy() 18 | 19 | def move_right(event): 20 | if canv.coords(paddle)[xBTM]<(MAX_WIDTH-7): 21 | canv.move(paddle, 7, 0) 22 | 23 | def move_left(event): 24 | if canv.coords(paddle)[xTOP]>7: 25 | canv.move(paddle, -7, 0) 26 | 27 | def determineDir(ball,obj): 28 | global delta_x,delta_y 29 | if (ball[xTOP] == obj[xBTM]) or (ball[xBTM] == obj[xTOP]): 30 | delta_x = -delta_x 31 | elif (ball[yTOP] == obj[yBTM]) or (ball[yBTM] == obj[yTOP]): 32 | delta_y = -delta_y 33 | 34 | root = TK.Tk() 35 | root.title("Bouncing Ball") 36 | root.geometry('%sx%s+%s+%s' %(MAX_WIDTH, MAX_HEIGHT, 100, 100)) 37 | root.bind('', move_right) 38 | root.bind('', move_left) 39 | root.protocol('WM_DELETE_WINDOW', close) 40 | 41 | canv = TK.Canvas(root, highlightthickness=0) 42 | canv.pack(fill='both', expand=True) 43 | 44 | top = canv.create_line(0, 0, MAX_WIDTH, 0, fill='blue', 45 | tags=('top')) 46 | left = canv.create_line(0, 0, 0, MAX_HEIGHT, fill='blue', 47 | tags=('left')) 48 | right = canv.create_line(MAX_WIDTH, 0, MAX_WIDTH, MAX_HEIGHT, 49 | fill='blue', tags=('right')) 50 | bottom = canv.create_line(0, MAX_HEIGHT, MAX_WIDTH, MAX_HEIGHT, 51 | fill='blue', tags=('bottom')) 52 | 53 | ball = canv.create_rectangle(0, 0, BALL_SIZE, BALL_SIZE, 54 | outline='black', fill='black', tags=('ball')) 55 | paddle = canv.create_rectangle(100, MAX_HEIGHT - 30, 150, 470, 56 | outline='black', fill='green', tags=('rect')) 57 | 58 | brick=list() 59 | for i in range(0,16): 60 | for row in range(0,4): 61 | brick.append(canv.create_rectangle(i*40, row*20, 62 | ((i+1)*40)-2, ((row+1)*20)-2, 63 | outline='black', fill='red', 64 | tags=('rect'))) 65 | 66 | delta_x = delta_y = 1 67 | xold,yold = xSTART,ySTART 68 | canv.move(ball, xold, yold) 69 | 70 | while RUNNING: 71 | objects = canv.find_overlapping(canv.coords(ball)[0], 72 | canv.coords(ball)[1], 73 | canv.coords(ball)[2], 74 | canv.coords(ball)[3]) 75 | #Only change the direction once (so will bounce off 1st 76 | # block even if 2 are hit) 77 | dir_changed=False 78 | for obj in objects: 79 | if (obj != ball): 80 | if dir_changed==False: 81 | determineDir(canv.coords(ball),canv.coords(obj)) 82 | dir_changed=True 83 | if (obj >= brick[0]) and (obj <= brick[len(brick)-1]): 84 | canv.delete(obj) 85 | if (obj == bottom): 86 | text = canv.create_text(300,100,text="YOU HAVE MISSED!") 87 | canv.coords(ball, (xSTART,ySTART, 88 | xSTART+BALL_SIZE,ySTART+BALL_SIZE)) 89 | delta_x = delta_y = 1 90 | canv.update() 91 | time.sleep(3) 92 | canv.delete(text) 93 | new_x, new_y = delta_x, delta_y 94 | canv.move(ball, new_x, new_y) 95 | 96 | canv.update() 97 | time.sleep(0.005) 98 | #End 99 | -------------------------------------------------------------------------------- /Chapter05/gold.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter05/gold.gif -------------------------------------------------------------------------------- /Chapter05/mark.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter05/mark.gif -------------------------------------------------------------------------------- /Chapter05/painting.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | #painting.py 3 | import tkinter as TK 4 | 5 | #Set defaults 6 | btn1pressed = False 7 | newline = True 8 | 9 | def main(): 10 | root = TK.Tk() 11 | the_canvas = TK.Canvas(root) 12 | the_canvas.pack() 13 | the_canvas.bind("", mousemove) 14 | the_canvas.bind("", mouse1press) 15 | the_canvas.bind("", mouse1release) 16 | root.mainloop() 17 | 18 | def mouse1press(event): 19 | global btn1pressed 20 | btn1pressed = True 21 | 22 | def mouse1release(event): 23 | global btn1pressed, newline 24 | btn1pressed = False 25 | newline = True 26 | 27 | def mousemove(event): 28 | if btn1pressed == True: 29 | global xorig, yorig, newline 30 | if newline == False: 31 | event.widget.create_line(xorig,yorig,event.x,event.y, 32 | smooth=TK.TRUE) 33 | newline = False 34 | xorig = event.x 35 | yorig = event.y 36 | 37 | if __name__ == "__main__": 38 | main() 39 | #End 40 | -------------------------------------------------------------------------------- /Chapter05/playerD.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter05/playerD.gif -------------------------------------------------------------------------------- /Chapter05/playerL.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter05/playerL.gif -------------------------------------------------------------------------------- /Chapter05/playerR.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter05/playerR.gif -------------------------------------------------------------------------------- /Chapter05/playerU.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter05/playerU.gif -------------------------------------------------------------------------------- /Chapter05/wallH.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter05/wallH.gif -------------------------------------------------------------------------------- /Chapter05/wallV.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter05/wallV.gif -------------------------------------------------------------------------------- /Chapter06/Blurring_Sharpening.py: -------------------------------------------------------------------------------- 1 | # Blurring and Sharpening Images 2 | 3 | # Import Computer Vision package - cv2 4 | import cv2 5 | 6 | # Import Numerical Python package - numpy as np 7 | import numpy as np 8 | 9 | # Read the image using imread built-in function 10 | image = cv2.imread('image_6.jpg') 11 | 12 | # Display original image using imshow built-in function 13 | cv2.imshow("Original", image) 14 | 15 | # Wait until any key is pressed 16 | cv2.waitKey(0) 17 | 18 | # Blurring images: Averaging, cv2.blur built-in function 19 | # Averaging: Convolving image with normalized box filter 20 | # Convolution: Mathematical operation on 2 functions which produces third function. 21 | # Normalized box filter having size 3 x 3 would be: 22 | # (1/9) [[1, 1, 1], 23 | # [1, 1, 1], 24 | # [1, 1, 1]] 25 | blur = cv2.blur(image,(9,9)) # (9 x 9) filter is used 26 | 27 | # Display blurred image 28 | cv2.imshow('Blurred', blur) 29 | 30 | # Wait until any key is pressed 31 | cv2.waitKey(0) 32 | 33 | # Sharpening images: Emphasizes edges in an image 34 | 35 | kernel = np.array([[-1,-1,-1], 36 | [-1,9,-1], 37 | [-1,-1,-1]]) 38 | # If we don't normalize to 1, image would be brighter or darker respectively 39 | 40 | # cv2.filter2D is the built-in function used for sharpening images 41 | # cv2.filter2D(image, ddepth, kernel) 42 | sharpened = cv2.filter2D(image, -1, kernel) 43 | # ddepth = -1, sharpened images will have same depth as original image 44 | 45 | # Display sharpenend image 46 | cv2.imshow('Sharpened', sharpened) 47 | 48 | # Wait untill any key is pressed 49 | cv2.waitKey(0) 50 | 51 | # Close all windows 52 | cv2.destroyAllWindows() 53 | -------------------------------------------------------------------------------- /Chapter06/Erosion_Dilation.py: -------------------------------------------------------------------------------- 1 | # Erosion and Dilation are Morphological Operations 2 | # Erosion: Removes pixels at the boundaries of objects in an image 3 | # Dilation: Adds pixels to the boundaries of objects in an image 4 | 5 | # Import Computer Vision package - cv2 6 | import cv2 7 | 8 | # Import Numerical Python package - numpy as np 9 | import numpy as np 10 | 11 | # Read the image using imread built-in function 12 | image = cv2.imread('image_4.jpg') 13 | 14 | # Display original image using imshow built-in function 15 | cv2.imshow("Original", image) 16 | 17 | # Wait until any key is pressed 18 | cv2.waitKey(0) 19 | 20 | # np.ones returns an array, given shape and type, filled with ones 21 | # np.ones(shape, dtype) 22 | kernel = np.ones((5,5), dtype = "uint8") 23 | # 5 x 5 is the dimension of the kernal 24 | # uint8: is an unsigned integer (0 to 255) 25 | 26 | # cv2.erode is the built-in function used for erosion 27 | # cv2.erode(image, kernel, iterations) 28 | erosion = cv2.erode(image, kernel, iterations = 1) 29 | 30 | # Display image after erosion using imshow built-in function 31 | cv2.imshow("Erosion", erosion) 32 | 33 | # Wait until any key is pressed 34 | cv2.waitKey(0) 35 | 36 | # cv2.dilate is the built-in function used for dilation 37 | # cv2.dilate(image, kernel, iterations) 38 | dilation = cv2.dilate(image, kernel, iterations = 1) 39 | 40 | # Display image after dilation using imshow built-in function 41 | cv2.imshow("Dilation", dilation) 42 | 43 | # Wait until any key is pressed 44 | cv2.waitKey(0) 45 | 46 | # Close all windows 47 | cv2.destroyAllWindows() 48 | -------------------------------------------------------------------------------- /Chapter06/Flipping.py: -------------------------------------------------------------------------------- 1 | # Flipping Images - Horizontally, Vertically, Horizontally & Vertically 2 | 3 | # Import Computer Vision package - cv2 4 | import cv2 5 | 6 | # Read the image using imread built in function 7 | image = cv2.imread('image_2.jpg') 8 | 9 | # Display original image using imshow built in function 10 | cv2.imshow("Original", image) 11 | 12 | # Wait until any key is pressed 13 | cv2.waitKey(0) 14 | 15 | # cv2.flip is used to flip images 16 | # Horizontal flipping of images using value '1' 17 | flipping = cv2.flip(image, 1) 18 | 19 | # Display horizontally flipped image 20 | cv2.imshow("Horizontal Flipping", flipping) 21 | 22 | # Wait until any key is pressed 23 | cv2.waitKey(0) 24 | 25 | # Vertical flipping of images using value '0' 26 | flipping = cv2.flip(image, 0) 27 | 28 | # Display vertically flipped image 29 | cv2.imshow("Vertical Flipping", flipping) 30 | 31 | # Wait until any key is pressed 32 | cv2.waitKey(0) 33 | 34 | # Horizontal & Vertical flipping of images using value '-1' 35 | flipping = cv2.flip(image, -1) 36 | 37 | # Display horizontally & vertically flipped image 38 | cv2.imshow("Horizontal & Vertical Flipping", flipping) 39 | 40 | # Wait until any key is pressed 41 | cv2.waitKey(0) 42 | 43 | # Close all windows 44 | cv2.destroyAllWindows() 45 | 46 | -------------------------------------------------------------------------------- /Chapter06/Image_Segmentation.py: -------------------------------------------------------------------------------- 1 | # Image Segmatation using Contours 2 | # Segmentation: Partitioning images into different regions 3 | # Contours: Lines or curves around the boundary of an object 4 | 5 | # Import Computer Vision package - cv2 6 | import cv2 7 | 8 | # Import Numerical Python package - numpy as np 9 | import numpy as np 10 | 11 | # Read the image using imread built-in function 12 | image = cv2.imread('image_5.jpg') 13 | 14 | # Display original image using imshow built-in function 15 | cv2.imshow("Original", image) 16 | 17 | # Wait until any key is pressed 18 | cv2.waitKey(0) 19 | 20 | # cv2.Canny is the built-in function used to detect edges 21 | # cv2.Canny(image, threshold_1, threshold_2) 22 | canny = cv2.Canny(image, 50, 200) 23 | 24 | # Display edge detected output image using imshow built-in function 25 | cv2.imshow("Canny Edge Detection", canny) 26 | 27 | # Wait until any key is pressed 28 | cv2.waitKey(0) 29 | 30 | # cv2.findContours is the built-in function to find contours 31 | # cv2.findContours(canny, contour retrieval mode, contour approximation mode) 32 | # contour retrieval mode: cv2.RETR_LIST (retrieves all contours) 33 | # contour approximation mode: cv2.CHAIN_APPROX_NONE (stores all boundary points) 34 | contours, hierarchy = cv2.findContours(canny, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE) 35 | 36 | # cv2.drawContours is the the built-in function to draw contours 37 | # cv2.drawContours(image, contours, index of contours, color, thickness) 38 | cv2.drawContours(image, contours, -1, (255,0,0), 10) 39 | # index of contours = -1 will draw all the contours 40 | 41 | # Display contours using imshow built-in function 42 | cv2.imshow("Contours", image) 43 | 44 | # Wait until any key is pressed 45 | cv2.waitKey() 46 | 47 | # Close all windows 48 | cv2.destroyAllWindows() 49 | -------------------------------------------------------------------------------- /Chapter06/Load_Display_Save.py: -------------------------------------------------------------------------------- 1 | # Load, Display and Save Images 2 | 3 | # Import Computer Vision package - cv2 4 | import cv2 5 | 6 | # Read the image using imread built-in function 7 | image = cv2.imread('image_1.jpg') 8 | 9 | # Display original image using imshow built-in function 10 | cv2.imshow("Original", image) 11 | 12 | # Wait until any key is pressed 13 | cv2.waitKey(0) 14 | 15 | # Save the image using imwrite built-in function 16 | cv2.imwrite("Saved Image.jpg", image) 17 | -------------------------------------------------------------------------------- /Chapter06/Scaling.py: -------------------------------------------------------------------------------- 1 | # Scaling (Resizing) Images - Cubic, Area, Linear Interpolations 2 | # Interpolation is a method of estimating values between known data points 3 | 4 | # Import Computer Vision package - cv2 5 | import cv2 6 | 7 | # Import Numerical Python package - numpy as np 8 | import numpy as np 9 | 10 | # Read the image using imread built-in function 11 | image = cv2.imread('image_3.jpg') 12 | 13 | # Display original image using imshow built-in function 14 | cv2.imshow("Original", image) 15 | 16 | # Wait until any key is pressed 17 | cv2.waitKey() 18 | 19 | # cv2.resize(image, output image size, x scale, y scale, interpolation) 20 | 21 | # Scaling using cubic interpolation 22 | scaling_cubic = cv2.resize(image, None, fx=.75, fy=.75, interpolation = cv2.INTER_CUBIC) 23 | 24 | # Display cubic interpolated image 25 | cv2.imshow('Cubic Interpolated', scaling_cubic) 26 | 27 | # Wait until any key is pressed 28 | cv2.waitKey() 29 | 30 | # Scaling using area interpolation 31 | scaling_skewed = cv2.resize(image, (600, 300), interpolation = cv2.INTER_AREA) 32 | 33 | # Display area interpolated image 34 | cv2.imshow('Area Interpolated', scaling_skewed) 35 | 36 | # Wait until any key is pressed 37 | cv2.waitKey() 38 | 39 | # Scaling using linear interpolation 40 | scaling_linear = cv2.resize(image, None, fx=0.5, fy=0.5, interpolation = cv2.INTER_LINEAR) 41 | 42 | # Display linear interpolated image 43 | cv2.imshow('Linear Interpolated', scaling_linear) 44 | 45 | # Wait until any key is pressed 46 | cv2.waitKey() 47 | 48 | # Close all windows 49 | cv2.destroyAllWindows() 50 | -------------------------------------------------------------------------------- /Chapter06/image_1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter06/image_1.jpg -------------------------------------------------------------------------------- /Chapter06/image_2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter06/image_2.jpg -------------------------------------------------------------------------------- /Chapter06/image_3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter06/image_3.jpg -------------------------------------------------------------------------------- /Chapter06/image_4.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter06/image_4.jpg -------------------------------------------------------------------------------- /Chapter06/image_5.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter06/image_5.jpg -------------------------------------------------------------------------------- /Chapter06/image_6.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter06/image_6.jpg -------------------------------------------------------------------------------- /Chapter07/3dModel.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ Wavefront obj model loading. Material properties set in 3 | mtl file. Uses the import pi3d method to load *everything* 4 | """ 5 | import demo 6 | import pi3d 7 | from math import sin, cos, radians 8 | 9 | # Setup display and initialise pi3d 10 | DISPLAY = pi3d.Display.create() 11 | # Fetch key presses 12 | inputs=pi3d.InputEvents() 13 | 14 | def main(): 15 | #Model textures and shaders 16 | shader = pi3d.Shader("uv_reflect") 17 | bumptex = pi3d.Texture("textures/floor_nm.jpg") 18 | shinetex = pi3d.Texture("textures/stars.jpg") 19 | # load model 20 | mymodel = pi3d.Model(file_string='models/teapot.obj', z=10) 21 | mymodel.set_shader(shader) 22 | mymodel.set_normal_shine(bumptex, 4.0, shinetex, 0.5) 23 | 24 | #Create environment box 25 | flatsh = pi3d.Shader("uv_flat") 26 | ectex=pi3d.loadECfiles("textures/ecubes","sbox") 27 | myecube = pi3d.EnvironmentCube(size=900.0, maptype="FACES", 28 | name="cube") 29 | myecube.set_draw_details(flatsh, ectex) 30 | 31 | CAMERA = pi3d.Camera.instance() 32 | rot = 0.0 # rotation of camera 33 | tilt = 0.0 # tilt of camera 34 | 35 | while DISPLAY.loop_running() and not \ 36 | inputs.key_state("KEY_ESC"): 37 | #Rotate camera 38 | inputs.do_input_events() 39 | # camera steered by mouse 40 | #Note:Some mice devices will be located on 41 | #get_mouse_movement(1) instead of get_mouse_movement() 42 | mx,my,mv,mh,md=inputs.get_mouse_movement() 43 | #mx,my,mv,mh,md=inputs.get_mouse_movement(1) 44 | rot -= (mx)*0.2 45 | tilt -= (my)*0.2 46 | CAMERA.reset() 47 | CAMERA.rotate(tilt, rot, 0) 48 | #Rotate object 49 | mymodel.rotateIncY(2.0) 50 | mymodel.rotateIncZ(0.1) 51 | mymodel.rotateIncX(0.3) 52 | #Draw objects 53 | mymodel.draw() 54 | myecube.draw() 55 | 56 | try: 57 | main() 58 | finally: 59 | inputs.release() 60 | DISPLAY.destroy() 61 | print("Closed Everything. END") 62 | #End 63 | -------------------------------------------------------------------------------- /Chapter07/3dObject.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ Create a 3D space with a Tetrahedron inside and rotate the 3 | view around using the mouse. 4 | """ 5 | from math import sin, cos, radians 6 | 7 | import demo 8 | import pi3d 9 | 10 | DISPLAY = pi3d.Display.create(x=50, y=50) 11 | #capture mouse and key presses 12 | inputs=pi3d.InputEvents() 13 | 14 | def main(): 15 | CAMERA = pi3d.Camera.instance() 16 | tex = pi3d.Texture("textures/stripwood.jpg") 17 | flatsh = pi3d.Shader("uv_flat") 18 | 19 | #Define the coordinates for our shape (x,y,z) 20 | A=(-1.0,-1.0,-1.0) 21 | B=(1.0,-1.0,1.0) 22 | C=(-1.0,-1.0,1.0) 23 | D=(-1.0,1.0,1.0) 24 | ids=["A","B","C","D"] 25 | coords=[A,B,C,D] 26 | myTetra = pi3d.Tetrahedron(x=0.0, y=0.0, z=0.0, 27 | corners=(A,B,C,D)) 28 | myTetra.set_draw_details(flatsh,[tex]) 29 | # Load ttf font and set the font to black 30 | arialFont = pi3d.Font("fonts/FreeMonoBoldOblique.ttf", 31 | "#000000") 32 | mystring=[] 33 | #Create string objects to show the coordinates 34 | for i,pos in enumerate(coords): 35 | mystring.append(pi3d.String(font=arialFont, 36 | string=ids[i]+str(pos), 37 | x=pos[0], y=pos[1],z=pos[2])) 38 | mystring.append(pi3d.String(font=arialFont, 39 | string=ids[i]+str(pos), 40 | x=pos[0], y=pos[1],z=pos[2], ry=180)) 41 | for string in mystring: 42 | string.set_shader(flatsh) 43 | 44 | camRad = 4.0 # radius of camera position 45 | rot = 0.0 # rotation of camera 46 | tilt = 0.0 # tilt of camera 47 | 48 | # main display loop 49 | while DISPLAY.loop_running() and not \ 50 | inputs.key_state("KEY_ESC"): 51 | inputs.do_input_events() 52 | #Note:Some mice devices will be located on 53 | #get_mouse_movement(1) instead of get_mouse_movement() 54 | mx,my,mv,mh,md=inputs.get_mouse_movement(1) 55 | #mx,my,mv,mh,md=inputs.get_mouse_movement(1) 56 | rot -= (mx)*0.2 57 | tilt -= (my)*0.2 58 | CAMERA.reset() 59 | CAMERA.rotate(-tilt, rot, 0) 60 | CAMERA.position((camRad * sin(radians(rot)) * 61 | cos(radians(tilt)), 62 | camRad * sin(radians(tilt)), 63 | -camRad * cos(radians(rot)) * 64 | cos(radians(tilt)))) 65 | #Draw the Tetrahedron 66 | myTetra.draw() 67 | for string in mystring: 68 | string.draw() 69 | 70 | try: 71 | main() 72 | finally: 73 | inputs.release() 74 | DISPLAY.destroy() 75 | print("Closed Everything. END") 76 | #End 77 | -------------------------------------------------------------------------------- /Chapter07/3dWorld.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | from __future__ import absolute_import, division 3 | from __future__ import print_function, unicode_literals 4 | """ An example of generating a 3D environment using a elevation map 5 | """ 6 | from math import sin, cos, radians 7 | import demo 8 | import pi3d 9 | 10 | DISPLAY = pi3d.Display.create(x=50, y=50) 11 | #capture mouse and key presses 12 | inputs=pi3d.InputEvents() 13 | 14 | def limit(value,min,max): 15 | if (value < min): 16 | value = min 17 | elif (value > max): 18 | value = max 19 | return value 20 | 21 | def main(): 22 | CAMERA = pi3d.Camera.instance() 23 | tex = pi3d.Texture("textures/grass.jpg") 24 | flatsh = pi3d.Shader("uv_flat") 25 | # Create elevation map 26 | mapwidth,mapdepth,mapheight=200.0,200.0,50.0 27 | mymap = pi3d.ElevationMap("textures/Map.png", 28 | width=mapwidth, depth=mapdepth, height=mapheight, 29 | divx=128, divy=128, ntiles=20) 30 | mymap.set_draw_details(flatsh, [tex], 1.0, 1.0) 31 | 32 | rot = 0.0 # rotation of camera 33 | tilt = 0.0 # tilt of camera 34 | height = 20 35 | viewhight = 4 36 | sky = 200 37 | xm,ym,zm = 0.0,height,0.0 38 | onGround = False 39 | # main display loop 40 | while DISPLAY.loop_running() and not inputs.key_state("KEY_ESC"): 41 | inputs.do_input_events() 42 | # camera steered by mouse 43 | #mx,my,mv,mh,md=inputs.get_mouse_movement() 44 | mx,my,mv,mh,md=inputs.get_mouse_movement(1) 45 | rot -= (mx)*0.2 46 | tilt -= (my)*0.2 47 | CAMERA.reset() 48 | CAMERA.rotate(-tilt, rot, 0) 49 | CAMERA.position((xm,ym,zm)) 50 | mymap.draw() 51 | if inputs.key_state("KEY_W"): 52 | xm -= sin(radians(rot)) 53 | zm += cos(radians(rot)) 54 | elif inputs.key_state("KEY_S"): 55 | xm += sin(radians(rot)) 56 | zm -= cos(radians(rot)) 57 | elif inputs.key_state("KEY_R"): 58 | ym += 2 59 | onGround = False 60 | elif inputs.key_state("KEY_T"): 61 | ym -= 2 62 | ym-=0.1 #Float down! 63 | #Limit the movement 64 | xm=limit(xm,-(mapwidth/2),mapwidth/2) 65 | zm=limit(zm,-(mapdepth/2),mapdepth/2) 66 | if ym >= sky: 67 | ym = sky 68 | #Check onGround 69 | ground = mymap.calcHeight(xm, zm) + viewhight 70 | if (onGround == True) or (ym <= ground): 71 | ym = mymap.calcHeight(xm, zm) + viewhight 72 | onGround = True 73 | 74 | try: 75 | main() 76 | finally: 77 | inputs.release() 78 | DISPLAY.destroy() 79 | print("Closed Everything. END") 80 | #End 81 | 82 | -------------------------------------------------------------------------------- /Chapter07/source_files/fonts/FreeMonoBoldOblique.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter07/source_files/fonts/FreeMonoBoldOblique.ttf -------------------------------------------------------------------------------- /Chapter07/source_files/models/monkey.mtl: -------------------------------------------------------------------------------- 1 | # Blender MTL File: 'None' 2 | # Material Count: 1 3 | 4 | newmtl None 5 | Ns 0 6 | Ka 0.000000 0.000000 0.000000 7 | Kd 0.8 0.8 0.8 8 | Ks 0.8 0.8 0.8 9 | d 1 10 | illum 2 11 | map_Kd ../textures/water.jpg 12 | -------------------------------------------------------------------------------- /Chapter07/source_files/models/simplecube.mtl: -------------------------------------------------------------------------------- 1 | # Blender MTL File: 'None' 2 | # Material Count: 1 3 | 4 | newmtl Material 5 | Ns 96.078431 6 | Ka 0.000000 0.000000 0.000000 7 | Kd 0.640000 0.640000 0.640000 8 | Ks 0.500000 0.500000 0.500000 9 | Ni 1.000000 10 | d 1.000000 11 | illum 2 12 | map_Kd ../textures/water.jpg 13 | -------------------------------------------------------------------------------- /Chapter07/source_files/models/simplecube.obj: -------------------------------------------------------------------------------- 1 | # Blender v2.67 (sub 0) OBJ File: '' 2 | # www.blender.org 3 | mtllib simplecube.mtl 4 | o Cube 5 | v 1.000000 -1.000000 -1.000000 6 | v 1.000000 -1.000000 1.000000 7 | v -1.000000 -1.000000 1.000000 8 | v -1.000000 -1.000000 -1.000000 9 | v 1.000000 1.000000 -0.999999 10 | v 0.999999 1.000000 1.000001 11 | v -1.000000 1.000000 1.000000 12 | v -1.000000 1.000000 -1.000000 13 | vt 0.000000 0.000000 14 | vt 1.000000 0.000000 15 | vt 1.000000 1.000000 16 | vt 0.000000 1.000000 17 | vn 0.000000 -1.000000 0.000000 18 | vn 0.000000 1.000000 0.000000 19 | vn 1.000000 0.000000 0.000000 20 | vn -0.000000 -0.000000 1.000000 21 | vn -1.000000 -0.000000 -0.000000 22 | vn 0.000000 0.000000 -1.000000 23 | usemtl Material 24 | s off 25 | f 1/1/1 2/2/1 3/3/1 4/4/1 26 | f 5/1/2 8/2/2 7/3/2 6/4/2 27 | f 1/1/3 5/2/3 6/3/3 2/4/3 28 | f 2/1/4 6/2/4 7/3/4 3/4/4 29 | f 3/1/5 7/2/5 8/3/5 4/4/5 30 | f 5/1/6 1/2/6 4/3/6 8/4/6 31 | -------------------------------------------------------------------------------- /Chapter07/source_files/textures/Map.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter07/source_files/textures/Map.png -------------------------------------------------------------------------------- /Chapter07/source_files/textures/dunes3_512.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter07/source_files/textures/dunes3_512.jpg -------------------------------------------------------------------------------- /Chapter07/source_files/textures/ecubes/sbox_back.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter07/source_files/textures/ecubes/sbox_back.jpg -------------------------------------------------------------------------------- /Chapter07/source_files/textures/ecubes/sbox_bottom.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter07/source_files/textures/ecubes/sbox_bottom.jpg -------------------------------------------------------------------------------- /Chapter07/source_files/textures/ecubes/sbox_front.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter07/source_files/textures/ecubes/sbox_front.jpg -------------------------------------------------------------------------------- /Chapter07/source_files/textures/ecubes/sbox_left.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter07/source_files/textures/ecubes/sbox_left.jpg -------------------------------------------------------------------------------- /Chapter07/source_files/textures/ecubes/sbox_right.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter07/source_files/textures/ecubes/sbox_right.jpg -------------------------------------------------------------------------------- /Chapter07/source_files/textures/ecubes/sbox_top.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter07/source_files/textures/ecubes/sbox_top.jpg -------------------------------------------------------------------------------- /Chapter07/source_files/textures/floor.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter07/source_files/textures/floor.png -------------------------------------------------------------------------------- /Chapter07/source_files/textures/floor_nm.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter07/source_files/textures/floor_nm.jpg -------------------------------------------------------------------------------- /Chapter07/source_files/textures/grass.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter07/source_files/textures/grass.jpg -------------------------------------------------------------------------------- /Chapter07/source_files/textures/inside_map0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter07/source_files/textures/inside_map0.png -------------------------------------------------------------------------------- /Chapter07/source_files/textures/inside_map1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter07/source_files/textures/inside_map1.png -------------------------------------------------------------------------------- /Chapter07/source_files/textures/inside_map2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter07/source_files/textures/inside_map2.png -------------------------------------------------------------------------------- /Chapter07/source_files/textures/mudnormal.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter07/source_files/textures/mudnormal.jpg -------------------------------------------------------------------------------- /Chapter07/source_files/textures/rock1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter07/source_files/textures/rock1.jpg -------------------------------------------------------------------------------- /Chapter07/source_files/textures/squareblocks4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter07/source_files/textures/squareblocks4.png -------------------------------------------------------------------------------- /Chapter07/source_files/textures/squareblocksred.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter07/source_files/textures/squareblocksred.png -------------------------------------------------------------------------------- /Chapter07/source_files/textures/stars.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter07/source_files/textures/stars.jpg -------------------------------------------------------------------------------- /Chapter07/source_files/textures/stripwood.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter07/source_files/textures/stripwood.jpg -------------------------------------------------------------------------------- /Chapter07/source_files/textures/water.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter07/source_files/textures/water.jpg -------------------------------------------------------------------------------- /Chapter08/Haarcascade_face_detector.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | 4 | # Load face cascade file 5 | frontalface_cascade= cv2.CascadeClassifier('haarcascade_frontalface_alt.xml') 6 | 7 | # Check if face cascade file has been loaded 8 | if frontalface_cascade.empty(): 9 | raise IOError('Unable to load the face cascade classifier xml file') 10 | 11 | # Initialize video capture object 12 | capture = cv2.VideoCapture(0) 13 | 14 | # Define the scaling factor 15 | scale_factor = 0.5 16 | 17 | # Loop until you hit the Esc key 18 | while True: 19 | # Capture current frame and resize it 20 | ret, frame = capture.read() 21 | frame = cv2.resize(frame, None, fx=scale_factor, fy=scale_factor, 22 | interpolation=cv2.INTER_AREA) 23 | 24 | # Convert to grayscale 25 | gray_image = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) 26 | 27 | # Run the face detector on the grayscale image 28 | face_rectangle = frontalface_cascade.detectMultiScale(gray_image, 1.3, 5) 29 | 30 | # Draw rectangles on the image 31 | for (x,y,w,h) in face_rectangle: 32 | cv2.rectangle(frame, (x,y), (x+w,y+h), (0,255,0), 3) 33 | 34 | # Display the image 35 | cv2.imshow('Face Detector', frame) 36 | 37 | # Check if Esc key has been pressed 38 | a = cv2.waitKey(1) 39 | if a == 10: 40 | break 41 | 42 | # Release the video capture object and close all windows 43 | capture.release() 44 | cv2.destroyAllWindows() 45 | -------------------------------------------------------------------------------- /Chapter08/face_recognizer.py: -------------------------------------------------------------------------------- 1 | import os 2 | import cv2 3 | import numpy as np 4 | from sklearn import preprocessing 5 | 6 | # Class to handle tasks related to label encoding 7 | class LabelEncoding(object): 8 | # Method to encode labels from words to numbers 9 | def encoding_labels(self, label_wordings): 10 | self.le = preprocessing.LabelEncoder() 11 | self.le.fit(label_wordings) 12 | 13 | # Convert input label from word to number 14 | def word_to_number(self, label_wordings): 15 | return int(self.le.transform([label_wordings])[0]) 16 | 17 | # Convert input label from number to word 18 | def number_to_word(self, label_number): 19 | return self.le.inverse_transform([label_number])[0] 20 | 21 | # Extract images and labels from input path 22 | def getting_images_and_labels(path_input): 23 | label_wordings = [] 24 | 25 | # Iterate through the input path and append files 26 | for roots, dirs, files in os.walk(path_input): 27 | for fname in (x for x in files if x.endswith('.jpg')): 28 | fpath = os.path.join(roots, fname) 29 | label_wordings.append(fpath.split('/')[-2]) 30 | 31 | # Initialize variables 32 | images = [] 33 | le = LabelEncoding() 34 | le.encoding_labels(label_wordings) 35 | labels = [] 36 | 37 | # Parse the input directory 38 | for roots, dirs, files in os.walk(path_input): 39 | for fname in (x for x in files if x.endswith('.jpg')): 40 | fpath = os.path.join(roots, fname) 41 | 42 | # Read the image in grayscale format 43 | img = cv2.imread(fpath, 0) 44 | 45 | # Extract the label 46 | names = fpath.split('/')[-2] 47 | 48 | # Perform face detection 49 | face = faceCascade.detectMultiScale(img, 1.1, 2, minSize=(100,100)) 50 | 51 | # Iterate through face rectangles 52 | for (x, y, w, h) in face: 53 | images.append(img[y:y+h, x:x+w]) 54 | labels.append(le.word_to_number(names)) 55 | 56 | return images, labels, le 57 | 58 | if __name__=='__main__': 59 | path_cascade = "haarcascade_frontalface_alt.xml" 60 | train_img_path = 'faces_dataset/train' 61 | path_img_test = 'faces_dataset/test' 62 | 63 | # Load face cascade file 64 | faceCascade = cv2.CascadeClassifier(path_cascade) 65 | 66 | # Initialize Local Binary Patterns Histogram face recognizer 67 | face_recognizer = cv2.createLBPHFaceRecognizer() 68 | 69 | # Extract images, labels, and label encoder from training dataset 70 | imgs, labels, le = getting_images_and_labels(train_img_path) 71 | 72 | # Train the face recognizer 73 | print "\nTraining..." 74 | face_recognizer.train(imgs, np.array(labels)) 75 | 76 | # Test the recognizer on unknown images 77 | print '\nPerforming prediction on test images...' 78 | flag_stop = False 79 | for roots, dirs, files in os.walk(path_img_test): 80 | for fname in (x for x in files if x.endswith('.jpg')): 81 | fpath = os.path.join(roots, fname) 82 | 83 | # Read the image 84 | predicting_img = cv2.imread(fpath, 0) 85 | 86 | # Detect faces 87 | face = faceCascade.detectMultiScale(predicting_img, 1.1, 88 | 2, minSize=(100,100)) 89 | 90 | # Iterate through face rectangles 91 | for (x, y, w, h) in face: 92 | # Predict the output 93 | index_predicted, config = face_recognizer.predict( 94 | predicting_img[y:y+h, x:x+w]) 95 | 96 | # Convert to word label 97 | person_predicted = le.number_to_word(index_predicted) 98 | 99 | # Overlay text on the output image and display it 100 | cv2.putText(predicting_img, 'Prediction: ' + person_predicted, 101 | (10,60), cv2.FONT_HERSHEY_SIMPLEX, 2, (255,255,255), 6) 102 | cv2.imshow("Recognizing face", predicting_img) 103 | 104 | a = cv2.waitKey(0) 105 | if a == 27: 106 | flag = True 107 | break 108 | 109 | if flag_stop: 110 | break 111 | 112 | -------------------------------------------------------------------------------- /Chapter08/faces_dataset/test/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/test/.DS_Store -------------------------------------------------------------------------------- /Chapter08/faces_dataset/test/image_0019.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/test/image_0019.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/test/image_0020.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/test/image_0020.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/test/image_0021.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/test/image_0021.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/test/image_0039.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/test/image_0039.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/test/image_0040.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/test/image_0040.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/test/image_0041.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/test/image_0041.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/test/image_0087.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/test/image_0087.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/test/image_0088.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/test/image_0088.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/test/image_0089.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/test/image_0089.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person1/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person1/.DS_Store -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person1/image_0001.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person1/image_0001.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person1/image_0002.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person1/image_0002.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person1/image_0003.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person1/image_0003.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person1/image_0004.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person1/image_0004.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person1/image_0005.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person1/image_0005.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person1/image_0006.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person1/image_0006.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person1/image_0007.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person1/image_0007.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person1/image_0008.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person1/image_0008.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person1/image_0009.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person1/image_0009.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person1/image_0010.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person1/image_0010.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person1/image_0011.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person1/image_0011.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person1/image_0012.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person1/image_0012.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person1/image_0013.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person1/image_0013.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person1/image_0014.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person1/image_0014.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person1/image_0015.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person1/image_0015.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person1/image_0016.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person1/image_0016.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person1/image_0017.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person1/image_0017.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person1/image_0018.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person1/image_0018.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person2/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person2/.DS_Store -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person2/image_0022.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person2/image_0022.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person2/image_0023.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person2/image_0023.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person2/image_0024.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person2/image_0024.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person2/image_0025.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person2/image_0025.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person2/image_0026.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person2/image_0026.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person2/image_0027.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person2/image_0027.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person2/image_0028.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person2/image_0028.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person2/image_0029.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person2/image_0029.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person2/image_0030.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person2/image_0030.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person2/image_0031.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person2/image_0031.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person2/image_0032.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person2/image_0032.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person2/image_0033.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person2/image_0033.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person2/image_0034.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person2/image_0034.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person2/image_0035.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person2/image_0035.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person2/image_0036.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person2/image_0036.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person2/image_0037.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person2/image_0037.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person2/image_0038.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person2/image_0038.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person3/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person3/.DS_Store -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person3/image_0069.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person3/image_0069.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person3/image_0070.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person3/image_0070.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person3/image_0071.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person3/image_0071.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person3/image_0072.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person3/image_0072.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person3/image_0073.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person3/image_0073.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person3/image_0074.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person3/image_0074.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person3/image_0075.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person3/image_0075.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person3/image_0076.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person3/image_0076.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person3/image_0077.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person3/image_0077.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person3/image_0078.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person3/image_0078.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person3/image_0079.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person3/image_0079.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person3/image_0080.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person3/image_0080.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person3/image_0081.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person3/image_0081.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person3/image_0082.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person3/image_0082.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person3/image_0083.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person3/image_0083.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person3/image_0084.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person3/image_0084.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person3/image_0085.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person3/image_0085.jpg -------------------------------------------------------------------------------- /Chapter08/faces_dataset/train/person3/image_0086.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Raspberry-Pi-3-Cookbook-for-Python-Programmers-Third-Edition/ffaa7e324bda7ad8f7c752092609f48c8335ea39/Chapter08/faces_dataset/train/person3/image_0086.jpg -------------------------------------------------------------------------------- /Chapter09/btntest.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | #btntest.py 3 | import time 4 | import os 5 | import RPi.GPIO as GPIO 6 | #HARDWARE SETUP 7 | # P1 8 | # 2[==X==1=======]26 9 | # 1[=============]25 10 | #Button Config 11 | BTN = 12 12 | 13 | def gpio_setup(): 14 | #Setup the wiring 15 | GPIO.setmode(GPIO.BOARD) 16 | #Setup Ports 17 | GPIO.setup(BTN,GPIO.IN,pull_up_down=GPIO.PUD_UP) 18 | 19 | 20 | def main(): 21 | gpio_setup() 22 | count=0 23 | btn_closed = True 24 | while True: 25 | btn_val = GPIO.input(BTN) 26 | if btn_val and btn_closed: 27 | print("OPEN") 28 | btn_closed=False 29 | elif btn_val==False and btn_closed==False: 30 | count+=1 31 | print("CLOSE %s" % count) 32 | os.system("flite -t '%s'" % count) 33 | btn_closed=True 34 | time.sleep(0.1) 35 | 36 | try: 37 | main() 38 | finally: 39 | GPIO.cleanup() 40 | print("Closed Everything. END") 41 | #End 42 | -------------------------------------------------------------------------------- /Chapter09/gpiokeys-events.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | #gpiokeys-events.py 3 | import time 4 | import RPi.GPIO as GPIO 5 | import uinput 6 | 7 | #HARDWARE SETUP 8 | # P1 9 | # 2[==G=====<=V==]26 10 | # 1[===2=1>^=====]25 11 | B_DOWN = 22 #V 12 | B_LEFT = 18 #< 13 | B_UP = 15 #^ 14 | B_RIGHT = 13 #> 15 | B_1 = 11 #1 16 | B_2 = 7 #2 17 | 18 | DEBUG=False 19 | 20 | BTN = [B_UP,B_DOWN,B_LEFT,B_RIGHT,B_1,B_2] 21 | MSG = ["UP","DOWN","LEFT","RIGHT","1","2"] 22 | 23 | #Setup the DPad module pins and pull-ups 24 | def dpad_setup(): 25 | #Set up the wiring 26 | GPIO.setmode(GPIO.BOARD) 27 | # Setup BTN Ports as INPUTS 28 | for val in BTN: 29 | # set up GPIO input with pull-up control 30 | #(pull_up_down can be: 31 | # PUD_OFF, PUD_UP or PUD_DOWN, default PUD_OFF) 32 | GPIO.setup(val, GPIO.IN, pull_up_down=GPIO.PUD_UP) 33 | 34 | def main(): 35 | #Setup uinput 36 | events_dpad = (uinput.KEY_UP,uinput.KEY_DOWN,uinput.KEY_LEFT, 37 | uinput.KEY_RIGHT,uinput.KEY_ENTER,uinput.KEY_ENTER) 38 | events_z80 = (uinput.KEY_Q,uinput.KEY_A,uinput.KEY_O, 39 | uinput.KEY_P,uinput.KEY_M,uinput.KEY_ENTER) 40 | events=events_z80 41 | 42 | device = uinput.Device(events) 43 | time.sleep(2) # seconds 44 | dpad_setup() 45 | print("DPad Ready!") 46 | 47 | btn_state=[False,False,False,False,False,False] 48 | key_state=[False,False,False,False,False,False] 49 | while True: 50 | #Catch all the buttons pressed before pressing the related keys 51 | for idx, val in enumerate(BTN): 52 | if GPIO.input(val) == False: 53 | btn_state[idx]=True 54 | else: 55 | btn_state[idx]=False 56 | 57 | #Perform the button presses/releases 58 | #(but only change state once) 59 | for idx, val in enumerate(btn_state): 60 | if val == True and key_state[idx] == False: 61 | if DEBUG:print (str(val) + ":" + MSG[idx]) 62 | device.emit(events[idx], 1) # Press. 63 | key_state[idx]=True 64 | elif val == False and key_state[idx] == True: 65 | if DEBUG:print (str(val) + ":!" + MSG[idx]) 66 | device.emit(events[idx], 0) # Release. 67 | key_state[idx]=False 68 | 69 | time.sleep(.1) 70 | 71 | try: 72 | main() 73 | finally: 74 | GPIO.cleanup() 75 | #End 76 | -------------------------------------------------------------------------------- /Chapter09/gpiokeys-mouse.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | #gpiokeys-mouse.py 3 | import time 4 | import RPi.GPIO as GPIO 5 | import uinput 6 | 7 | #HARDWARE SETUP 8 | # P1 9 | # 2[==G=====<=V==]26 10 | # 1[===2=1>^=====]25 11 | B_DOWN = 22 #V 12 | B_LEFT = 18 #< 13 | B_UP = 15 #^ 14 | B_RIGHT = 13 #> 15 | B_1 = 11 #1 16 | B_2 = 7 #2 17 | 18 | DEBUG=False 19 | 20 | BTN = [B_UP,B_DOWN,B_LEFT,B_RIGHT,B_1,B_2] 21 | #MSG = ["UP","DOWN","LEFT","RIGHT","1","2"] 22 | MSG = ["M_UP","M_DOWN","M_LEFT","M_RIGHT","1","Enter"] 23 | 24 | #Setup the DPad module pins and pull-ups 25 | def dpad_setup(): 26 | #Set up the wiring 27 | GPIO.setmode(GPIO.BOARD) 28 | # Setup BTN Ports as INPUTS 29 | for val in BTN: 30 | # set up GPIO input with pull-up control 31 | #(pull_up_down can be: 32 | # PUD_OFF, PUD_UP or PUD_DOWN, default PUD_OFF) 33 | GPIO.setup(val, GPIO.IN, pull_up_down=GPIO.PUD_UP) 34 | 35 | def main(): 36 | #Setup uinput 37 | events_mouse=(uinput.REL_Y,uinput.REL_Y, uinput.REL_X, 38 | uinput.REL_X,uinput.BTN_LEFT,uinput.BTN_RIGHT) 39 | events = events_mouse 40 | device = uinput.Device(events) 41 | time.sleep(2) # seconds 42 | dpad_setup() 43 | print("DPad Ready!") 44 | 45 | btn_state=[False,False,False,False,False,False] 46 | key_state=[False,False,False,False,False,False] 47 | while True: 48 | #Catch all the buttons pressed before pressing the related keys 49 | for idx, val in enumerate(BTN): 50 | if GPIO.input(val) == False: 51 | btn_state[idx]=True 52 | else: 53 | btn_state[idx]=False 54 | 55 | #Perform the button presses/releases 56 | #(but only change state once) 57 | for idx, val in enumerate(btn_state): 58 | if MSG[idx] == "M_UP" or MSG[idx] == "M_LEFT": 59 | state = -1 60 | else: 61 | state = 1 62 | if val == True: 63 | device.emit(events[idx], state) # Press. 64 | elif val == False: 65 | device.emit(events[idx], 0) # Release. 66 | 67 | time.sleep(0.01) 68 | 69 | try: 70 | main() 71 | finally: 72 | GPIO.cleanup() 73 | #End 74 | -------------------------------------------------------------------------------- /Chapter09/gpiokeys.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | #gpiokeys.py 3 | import time 4 | import RPi.GPIO as GPIO 5 | import uinput 6 | 7 | #HARDWARE SETUP 8 | # P1 9 | # 2[==G=====<=V==]26 10 | # 1[===2=1>^=====]25 11 | B_DOWN = 22 #V 12 | B_LEFT = 18 #< 13 | B_UP = 15 #^ 14 | B_RIGHT = 13 #> 15 | B_1 = 11 #1 16 | B_2 = 7 #2 17 | 18 | DEBUG=True 19 | BTN = [B_UP,B_DOWN,B_LEFT,B_RIGHT,B_1,B_2] 20 | MSG = ["UP","DOWN","LEFT","RIGHT","1","2"] 21 | 22 | #Setup the DPad module pins and pull-ups 23 | def dpad_setup(): 24 | #Set up the wiring 25 | GPIO.setmode(GPIO.BOARD) 26 | # Setup BTN Ports as INPUTS 27 | for val in BTN: 28 | # set up GPIO input with pull-up control 29 | #(pull_up_down can be: 30 | # PUD_OFF, PUD_UP or PUD_DOWN, default PUD_OFF) 31 | GPIO.setup(val, GPIO.IN, pull_up_down=GPIO.PUD_UP) 32 | 33 | def main(): 34 | #Setup uinput 35 | events = (uinput.KEY_UP,uinput.KEY_DOWN,uinput.KEY_LEFT, 36 | uinput.KEY_RIGHT,uinput.KEY_ENTER,uinput.KEY_ENTER) 37 | device = uinput.Device(events) 38 | time.sleep(2) # seconds 39 | dpad_setup() 40 | print("DPad Ready!") 41 | 42 | btn_state=[False,False,False,False,False,False] 43 | key_state=[False,False,False,False,False,False] 44 | while True: 45 | #Catch all the buttons pressed before pressing the related keys 46 | for idx, val in enumerate(BTN): 47 | if GPIO.input(val) == False: 48 | btn_state[idx]=True 49 | else: 50 | btn_state[idx]=False 51 | 52 | #Perform the button presses/releases 53 | #(but only change state once) 54 | for idx, val in enumerate(btn_state): 55 | if val == True and key_state[idx] == False: 56 | if DEBUG:print (str(val) + ":" + MSG[idx]) 57 | device.emit(events[idx], 1) # Press. 58 | key_state[idx]=True 59 | elif val == False and key_state[idx] == True: 60 | if DEBUG:print (str(val) + ":!" + MSG[idx]) 61 | device.emit(events[idx], 0) # Release. 62 | key_state[idx]=False 63 | 64 | time.sleep(.1) 65 | 66 | try: 67 | main() 68 | finally: 69 | GPIO.cleanup() 70 | #End 71 | -------------------------------------------------------------------------------- /Chapter09/ledtest.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | #ledtest.py 3 | import time 4 | import RPi.GPIO as GPIO 5 | # RGB LED module 6 | #HARDWARE SETUP 7 | # P1 8 | # 2[======XRG=B==]26 9 | # 1[=============]25 10 | # X=GND R=Red G=Green B=Blue 11 | 12 | #Setup Active States 13 | #Common Cathode RGB-LED (Cathode=Active Low) 14 | RGB_ENABLE = 1; RGB_DISABLE = 0 15 | 16 | #LED CONFIG - Set GPIO Ports 17 | RGB_RED = 16; RGB_GREEN = 18; RGB_BLUE = 22 18 | RGB = [RGB_RED,RGB_GREEN,RGB_BLUE] 19 | 20 | def led_setup(): 21 | #Setup the wiring 22 | GPIO.setmode(GPIO.BOARD) 23 | #Setup Ports 24 | for val in RGB: 25 | GPIO.setup(val,GPIO.OUT) 26 | 27 | def main(): 28 | led_setup() 29 | for val in RGB: 30 | GPIO.output(val,RGB_ENABLE) 31 | print("LED ON") 32 | time.sleep(5) 33 | GPIO.output(val,RGB_DISABLE) 34 | print("LED OFF") 35 | 36 | try: 37 | main() 38 | finally: 39 | GPIO.cleanup() 40 | print("Closed Everything. END") 41 | #End 42 | -------------------------------------------------------------------------------- /Chapter09/rgbled-part1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | #rgbled-part1.py 3 | import time 4 | import RPi.GPIO as GPIO 5 | 6 | #Setup Active states 7 | #Common Cathode RGB-LEDs (Cathode=Active Low) 8 | LED_ENABLE = 0; LED_DISABLE = 1 9 | RGB_ENABLE = 1; RGB_DISABLE = 0 10 | #HARDWARE SETUP 11 | # P1 12 | # 2[=====1=23=4==]26 13 | # 1[===5=RGB=====]25 14 | #LED CONFIG - Set GPIO Ports 15 | LED1 = 12; LED2 = 16; LED3 = 18; LED4 = 22; LED5 = 7 16 | LED = [LED1,LED2,LED3,LED4,LED5] 17 | RGB_RED = 11; RGB_GREEN = 13; RGB_BLUE = 15 18 | RGB = [RGB_RED,RGB_GREEN,RGB_BLUE] 19 | #Mixed Colors 20 | RGB_CYAN = [RGB_GREEN,RGB_BLUE] 21 | RGB_MAGENTA = [RGB_RED,RGB_BLUE] 22 | RGB_YELLOW = [RGB_RED,RGB_GREEN] 23 | RGB_WHITE = [RGB_RED,RGB_GREEN,RGB_BLUE] 24 | RGB_LIST = [RGB_RED,RGB_GREEN,RGB_BLUE,RGB_CYAN, 25 | RGB_MAGENTA,RGB_YELLOW,RGB_WHITE] 26 | 27 | def led_setup(): 28 | '''Setup the RGB-LED module pins and state.''' 29 | #Set up the wiring 30 | GPIO.setmode(GPIO.BOARD) 31 | # Setup Ports 32 | for val in LED: 33 | GPIO.setup(val, GPIO.OUT) 34 | for val in RGB: 35 | GPIO.setup(val, GPIO.OUT) 36 | led_clear() 37 | 38 | def led_gpiocontrol(pins,state): 39 | '''This function will control the state of 40 | a single or multiple pins in a list.''' 41 | #determine if "pins" is a single integer or not 42 | if isinstance(pins,int): 43 | #Single integer - reference directly 44 | GPIO.output(pins,state) 45 | else: 46 | #if not, then cycle through the "pins" list 47 | for i in pins: 48 | GPIO.output(i,state) 49 | 50 | def led_activate(led,color): 51 | '''Enable the selected led(s) and set the required color(s) 52 | Will accept single or multiple values''' 53 | #Enable led 54 | led_gpiocontrol(led,LED_ENABLE) 55 | #Enable color 56 | led_gpiocontrol(color,RGB_ENABLE) 57 | 58 | def led_deactivate(led,color): 59 | '''Deactivate the selected led(s) and set the required 60 | color(s) will accept single or multiple values''' 61 | #Disable led 62 | led_gpiocontrol(led,LED_DISABLE) 63 | #Disable color 64 | led_gpiocontrol(color,RGB_DISABLE) 65 | 66 | def led_time(led, color, timeon): 67 | '''Switch on the led and color for the timeon period''' 68 | led_activate(led,color) 69 | time.sleep(timeon) 70 | led_deactivate(led,color) 71 | 72 | def led_clear(): 73 | '''Set the pins to default state.''' 74 | for val in LED: 75 | GPIO.output(val, LED_DISABLE) 76 | for val in RGB: 77 | GPIO.output(val, RGB_DISABLE) 78 | 79 | def led_cleanup(): 80 | '''Reset pins to default state and release GPIO''' 81 | led_clear() 82 | GPIO.cleanup() 83 | 84 | def main(): 85 | '''Directly run test function. 86 | This function will run if the file is executed directly''' 87 | led_setup() 88 | led_time(LED1,RGB_RED,5) 89 | led_time(LED2,RGB_GREEN,5) 90 | led_time(LED3,RGB_BLUE,5) 91 | led_time(LED,RGB_MAGENTA,2) 92 | led_time(LED,RGB_YELLOW,2) 93 | led_time(LED,RGB_CYAN,2) 94 | 95 | if __name__=='__main__': 96 | try: 97 | main() 98 | finally: 99 | led_cleanup() 100 | #End 101 | -------------------------------------------------------------------------------- /Chapter09/rgbled-rand.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | #rgbled-rand.py 3 | import time 4 | from random import randint 5 | import RPi.GPIO as GPIO 6 | 7 | #Setup Active states 8 | #Common Cathode RGB-LEDs (Cathode=Active Low) 9 | LED_ENABLE = 0; LED_DISABLE = 1 10 | RGB_ENABLE = 1; RGB_DISABLE = 0 11 | #HARDWARE SETUP 12 | # P1 13 | # 2[=====1=23=4==]26 14 | # 1[===5=RGB=====]25 15 | #LED CONFIG - Set GPIO Ports 16 | LED1 = 12; LED2 = 16; LED3 = 18; LED4 = 22; LED5 = 7 17 | LED = [LED1,LED2,LED3,LED4,LED5] 18 | RGB_RED = 11; RGB_GREEN = 13; RGB_BLUE = 15 19 | RGB = [RGB_RED,RGB_GREEN,RGB_BLUE] 20 | #Mixed Colors 21 | RGB_CYAN = [RGB_GREEN,RGB_BLUE] 22 | RGB_MAGENTA = [RGB_RED,RGB_BLUE] 23 | RGB_YELLOW = [RGB_RED,RGB_GREEN] 24 | RGB_WHITE = [RGB_RED,RGB_GREEN,RGB_BLUE] 25 | RGB_LIST = [RGB_RED,RGB_GREEN,RGB_BLUE,RGB_CYAN, 26 | RGB_MAGENTA,RGB_YELLOW,RGB_WHITE] 27 | 28 | def led_setup(): 29 | '''Setup the RGB-LED module pins and state.''' 30 | #Set up the wiring 31 | GPIO.setmode(GPIO.BOARD) 32 | # Setup Ports 33 | for val in LED: 34 | GPIO.setup(val, GPIO.OUT) 35 | for val in RGB: 36 | GPIO.setup(val, GPIO.OUT) 37 | led_clear() 38 | 39 | def led_gpiocontrol(pins,state): 40 | '''This function will control the state of 41 | a single or multiple pins in a list.''' 42 | #determine if "pins" is a single integer or not 43 | if isinstance(pins,int): 44 | #Single integer - reference directly 45 | GPIO.output(pins,state) 46 | else: 47 | #if not, then cycle through the "pins" list 48 | for i in pins: 49 | GPIO.output(i,state) 50 | 51 | def led_activate(led,color): 52 | '''Enable the selected led(s) and set the required color(s) 53 | Will accept single or multiple values''' 54 | #Enable led 55 | led_gpiocontrol(led,LED_ENABLE) 56 | #Enable color 57 | led_gpiocontrol(color,RGB_ENABLE) 58 | 59 | def led_deactivate(led,color): 60 | '''Deactivate the selected led(s) and set the required 61 | color(s) will accept single or multiple values''' 62 | #Disable led 63 | led_gpiocontrol(led,LED_DISABLE) 64 | #Disable color 65 | led_gpiocontrol(color,RGB_DISABLE) 66 | 67 | def led_time(led, color, timeon): 68 | '''Switch on the led and color for the timeon period''' 69 | led_activate(led,color) 70 | time.sleep(timeon) 71 | led_deactivate(led,color) 72 | 73 | def led_clear(): 74 | '''Set the pins to default state.''' 75 | for val in LED: 76 | GPIO.output(val, LED_DISABLE) 77 | for val in RGB: 78 | GPIO.output(val, RGB_DISABLE) 79 | 80 | def led_cleanup(): 81 | '''Reset pins to default state and release GPIO''' 82 | led_clear() 83 | GPIO.cleanup() 84 | 85 | def led_rgbrandom(led,period,colors): 86 | ''' Light up the selected led, for period in seconds, 87 | in one of the possible colors. The colors can be 88 | 1 to 3 for RGB, or 1-6 for RGB plus combinations, 89 | 1-7 includes white. Anything over 7 will be set as 90 | OFF (larger the number more chance of OFF).''' 91 | value = randint(1,colors) 92 | if value < len(RGB_LIST): 93 | led_time(led,RGB_LIST[value-1],period) 94 | 95 | 96 | def main(): 97 | '''Directly run test function. 98 | This function will run if the file is executed directly''' 99 | led_setup() 100 | led_time(LED1,RGB_RED,5) 101 | led_time(LED2,RGB_GREEN,5) 102 | led_time(LED3,RGB_BLUE,5) 103 | led_time(LED,RGB_MAGENTA,2) 104 | led_time(LED,RGB_YELLOW,2) 105 | led_time(LED,RGB_CYAN,2) 106 | for i in range(20): 107 | for j in LED: 108 | #Select from all, plus OFF 109 | led_rgbrandom(j,0.1,20) 110 | 111 | 112 | if __name__=='__main__': 113 | try: 114 | main() 115 | finally: 116 | led_cleanup() 117 | #End 118 | -------------------------------------------------------------------------------- /Chapter09/rgbled.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | #rgbled-part2.py 3 | import time 4 | import RPi.GPIO as GPIO 5 | 6 | #Setup Active states 7 | #Common Cathode RGB-LEDs (Cathode=Active Low) 8 | LED_ENABLE = 0; LED_DISABLE = 1 9 | RGB_ENABLE = 1; RGB_DISABLE = 0 10 | #HARDWARE SETUP 11 | # P1 12 | # 2[=====1=23=4==]26 13 | # 1[===5=RGB=====]25 14 | #LED CONFIG - Set GPIO Ports 15 | LED1 = 12; LED2 = 16; LED3 = 18; LED4 = 22; LED5 = 7 16 | LED = [LED1,LED2,LED3,LED4,LED5] 17 | RGB_RED = 11; RGB_GREEN = 13; RGB_BLUE = 15 18 | RGB = [RGB_RED,RGB_GREEN,RGB_BLUE] 19 | #Mixed Colors 20 | RGB_CYAN = [RGB_GREEN,RGB_BLUE] 21 | RGB_MAGENTA = [RGB_RED,RGB_BLUE] 22 | RGB_YELLOW = [RGB_RED,RGB_GREEN] 23 | RGB_WHITE = [RGB_RED,RGB_GREEN,RGB_BLUE] 24 | RGB_LIST = [RGB_RED,RGB_GREEN,RGB_BLUE,RGB_CYAN, 25 | RGB_MAGENTA,RGB_YELLOW,RGB_WHITE] 26 | #Combo Colors 27 | RGB_AQUA = [RGB_CYAN,RGB_GREEN] 28 | RGB_LBLUE = [RGB_CYAN,RGB_BLUE] 29 | RGB_PINK = [RGB_MAGENTA,RGB_RED] 30 | RGB_PURPLE = [RGB_MAGENTA,RGB_BLUE] 31 | RGB_ORANGE = [RGB_YELLOW,RGB_RED] 32 | RGB_LIME = [RGB_YELLOW,RGB_GREEN] 33 | RGB_COLORS = [RGB_LIME,RGB_YELLOW,RGB_ORANGE,RGB_RED, 34 | RGB_PINK,RGB_MAGENTA,RGB_PURPLE,RGB_BLUE, 35 | RGB_LBLUE,RGB_CYAN,RGB_AQUA,RGB_GREEN] 36 | 37 | def led_combo(pins,colors,period): 38 | #determine if "colors" is a single integer or not 39 | if isinstance(colors,int): 40 | #Single integer - reference directly 41 | led_time(pins,colors,period) 42 | else: 43 | #if not, then cycle through the "colors" list 44 | for i in colors: 45 | led_time(pins,i,period) 46 | 47 | def led_setup(): 48 | '''Setup the RGB-LED module pins and state.''' 49 | #Set up the wiring 50 | GPIO.setmode(GPIO.BOARD) 51 | # Setup Ports 52 | for val in LED: 53 | GPIO.setup(val, GPIO.OUT) 54 | for val in RGB: 55 | GPIO.setup(val, GPIO.OUT) 56 | led_clear() 57 | 58 | def led_gpiocontrol(pins,state): 59 | '''This function will control the state of 60 | a single or multiple pins in a list.''' 61 | #determine if "pins" is a single integer or not 62 | if isinstance(pins,int): 63 | #Single integer - reference directly 64 | GPIO.output(pins,state) 65 | else: 66 | #if not, then cycle through the "pins" list 67 | for i in pins: 68 | GPIO.output(i,state) 69 | 70 | def led_activate(led,color): 71 | '''Enable the selected led(s) and set the required color(s) 72 | Will accept single or multiple values''' 73 | #Enable led 74 | led_gpiocontrol(led,LED_ENABLE) 75 | #Enable color 76 | led_gpiocontrol(color,RGB_ENABLE) 77 | 78 | def led_deactivate(led,color): 79 | '''Deactivate the selected led(s) and set the required 80 | color(s) will accept single or multiple values''' 81 | #Disable led 82 | led_gpiocontrol(led,LED_DISABLE) 83 | #Disable color 84 | led_gpiocontrol(color,RGB_DISABLE) 85 | 86 | def led_time(led, color, timeon): 87 | '''Switch on the led and color for the timeon period''' 88 | led_activate(led,color) 89 | time.sleep(timeon) 90 | led_deactivate(led,color) 91 | 92 | def led_clear(): 93 | '''Set the pins to default state.''' 94 | for val in LED: 95 | GPIO.output(val, LED_DISABLE) 96 | for val in RGB: 97 | GPIO.output(val, RGB_DISABLE) 98 | 99 | def led_cleanup(): 100 | '''Reset pins to default state and release GPIO''' 101 | led_clear() 102 | GPIO.cleanup() 103 | 104 | def main(): 105 | '''Directly run test function. 106 | This function will run if the file is executed directly''' 107 | led_setup() 108 | led_time(LED1,RGB_RED,5) 109 | led_time(LED2,RGB_GREEN,5) 110 | led_time(LED3,RGB_BLUE,5) 111 | led_time(LED,RGB_MAGENTA,2) 112 | led_time(LED,RGB_YELLOW,2) 113 | led_time(LED,RGB_CYAN,2) 114 | 115 | if __name__=='__main__': 116 | try: 117 | main() 118 | finally: 119 | led_cleanup() 120 | #End 121 | -------------------------------------------------------------------------------- /Chapter09/rgbledrainbow.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | #rgbledrainbow.py 3 | import time 4 | import rgbled as RGBLED 5 | 6 | def next_value(number,max): 7 | number = number % max 8 | return number 9 | 10 | def main(): 11 | print ("Setup the RGB module") 12 | RGBLED.led_setup() 13 | 14 | # Multiple LEDs with different Colors 15 | print ("Switch on Rainbow") 16 | led_num = 0 17 | col_num = 0 18 | for l in range(5): 19 | print ("Cycle LEDs") 20 | for k in range(100): 21 | #Set the starting point for the next set of colors 22 | col_num = next_value(col_num+1,len(RGBLED.RGB_COLORS)) 23 | for i in range(20): #cycle time 24 | for j in range(5): #led cycle 25 | led_num = next_value(j,len(RGBLED.LED)) 26 | led_color = next_value(col_num+led_num, 27 | len(RGBLED.RGB_COLORS)) 28 | RGBLED.led_combo(RGBLED.LED[led_num], 29 | RGBLED.RGB_COLORS[led_color],0.001) 30 | 31 | print ("Cycle COLORs") 32 | for k in range(100): 33 | #Set the next color 34 | col_num = next_value(col_num+1,len(RGBLED.RGB_COLORS)) 35 | for i in range(20): #cycle time 36 | for j in range(5): #led cycle 37 | led_num = next_value(j,len(RGBLED.LED)) 38 | RGBLED.led_combo(RGBLED.LED[led_num], 39 | RGBLED.RGB_COLORS[col_num],0.001) 40 | print ("Finished") 41 | 42 | if __name__=='__main__': 43 | try: 44 | main() 45 | finally: 46 | RGBLED.led_cleanup() 47 | #End 48 | -------------------------------------------------------------------------------- /Chapter09/shtdwn.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | #shtdown.py 3 | import time 4 | import RPi.GPIO as GPIO 5 | import os 6 | 7 | # Shutdown Script 8 | DEBUG=False 9 | SNDON=True 10 | #HARDWARE SETUP 11 | # P1 12 | # 2[==X==L=======]26 13 | # 1[===1=========]25 14 | #BTN CONFIG - Set GPIO Ports 15 | GPIO_MODE=GPIO.BOARD 16 | SHTDWN_BTN = 7 #1 17 | LED = 12 #L 18 | 19 | def gpio_setup(): 20 | #Setup the wiring 21 | GPIO.setmode(GPIO_MODE) 22 | #Setup Ports 23 | GPIO.setup(SHTDWN_BTN,GPIO.IN,pull_up_down=GPIO.PUD_UP) 24 | GPIO.setup(LED,GPIO.OUT) 25 | 26 | def doShutdown(): 27 | if(DEBUG):print("Press detected") 28 | time.sleep(3) 29 | if GPIO.input(SHTDWN_BTN): 30 | if(DEBUG):print("Ignore the shutdown (<3sec)") 31 | else: 32 | if(DEBUG):print ("Would shutdown the RPi Now") 33 | GPIO.output(LED,0) 34 | time.sleep(0.5) 35 | GPIO.output(LED,1) 36 | if(SNDON):os.system("flite -t 'Warning commencing power down'") 37 | if(DEBUG==False):os.system("sudo shutdown -h now") 38 | if(DEBUG):GPIO.cleanup() 39 | if(DEBUG):exit() 40 | 41 | def main(): 42 | gpio_setup() 43 | GPIO.output(LED,1) 44 | while True: 45 | if(DEBUG):print("Waiting for >3sec button press") 46 | if GPIO.input(SHTDWN_BTN)==False: 47 | doShutdown() 48 | time.sleep(1) 49 | 50 | try: 51 | main() 52 | finally: 53 | GPIO.cleanup() 54 | print("Closed Everything. END") 55 | #End 56 | -------------------------------------------------------------------------------- /Chapter09/shtdwn_full.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import time 3 | import RPi.GPIO as GPIO 4 | import os 5 | 6 | # Shutdown Script 7 | DEBUG=False 8 | SNDON=True 9 | #HARDWARE SETUP 10 | # P1 11 | # 2[==X==L=======]26 12 | # 1[===1=2=======]25 13 | #BTN CONFIG - Set GPIO Ports 14 | GPIO_MODE=GPIO.BOARD 15 | SHTDWN_BTN = 7 #1 16 | LAN_SW = 11 #2 17 | LED = 12 #L 18 | 19 | 20 | def gpio_setup(): 21 | #Setup the wiring 22 | GPIO.setmode(GPIO_MODE) 23 | #Setup Ports 24 | GPIO.setup(SHTDWN_BTN,GPIO.IN,pull_up_down=GPIO.PUD_UP) 25 | GPIO.setup(LAN_SWA,GPIO.IN,pull_up_down=GPIO.PUD_UP) 26 | GPIO.setup(LED,GPIO.OUT) 27 | 28 | def doShutdown(): 29 | if(DEBUG):print("Press detected") 30 | time.sleep(3) 31 | if GPIO.input(SHTDWN_BTN): 32 | if(DEBUG):print("Ignore the shutdown (<3sec)") 33 | else: 34 | if(DEBUG):print ("Would shutdown the RPi Now") 35 | GPIO.output(LED,0) 36 | time.sleep(0.5) 37 | GPIO.output(LED,1) 38 | if(SNDON):os.system("flite -t 'Warning commencing power down in 3 2 1'") 39 | if(DEBUG==False):os.system("sudo shutdown -h now") 40 | if(DEBUG):GPIO.cleanup() 41 | if(DEBUG):exit() 42 | 43 | def doChangeLAN(direct): 44 | if(DEBUG):print("Direct LAN: %s" % direct) 45 | if GPIO.input(LAN_SWA) and direct==True: 46 | if(DEBUG):print("LAN Switch OFF") 47 | cmd="sudo dhclient eth0" 48 | direct=False 49 | GPIO.output(LED,1) 50 | elif GPIO.input(LAN_SWA)==False and direct==False: 51 | if(DEBUG):print("LAN Switch ON") 52 | cmd="sudo ifconfig eth0 169.254.69.69" 53 | direct=True 54 | else: 55 | return direct 56 | os.system(cmd) 57 | if(SNDON):os.system("hostname -I | flite") 58 | return direct 59 | 60 | def flashled(ledon): 61 | if ledon: 62 | ledon=False 63 | else: 64 | ledon=True 65 | GPIO.output(LED,ledon) 66 | return ledOn 67 | 68 | def main(): 69 | gpio_setup() 70 | GPIO.output(LED,1) 71 | directlan=False 72 | ledon=True 73 | while True: 74 | if(DEBUG):print("Waiting for >3sec button press") 75 | if GPIO.input(SHTDWN_BTN)==False: 76 | doShutdown() 77 | directlan = doChangeLAN(directlan) 78 | if directlan: 79 | flashled(ledon) 80 | time.sleep(1) 81 | 82 | try: 83 | main() 84 | finally: 85 | GPIO.cleanup() 86 | print("Closed Everything. END") 87 | #End 88 | -------------------------------------------------------------------------------- /Chapter10/data_adc.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | #data_adc.py 3 | import wiringpi2 4 | import time 5 | 6 | DEBUG=False 7 | LIGHT=0;TEMP=1;EXT=2;POT=3 8 | ADC_CH=[LIGHT,TEMP,EXT,POT] 9 | ADC_ADR=0x48 10 | ADC_CYCLE=0x04 11 | BUS_GAP=0.25 12 | DATANAME=["0:Light","1:Temperature", 13 | "2:External","3:Potentiometer"] 14 | 15 | class device: 16 | # Constructor: 17 | def __init__(self,addr=ADC_ADR): 18 | self.NAME=DATANAME 19 | self.i2c = wiringpi2.I2C() 20 | self.devADC=self.i2c.setup(addr) 21 | pwrup = self.i2c.read(self.devADC) #flush power up value 22 | if DEBUG==True and pwrup!=-1: 23 | print("ADC Ready") 24 | self.i2c.read(self.devADC) #flush first value 25 | time.sleep(BUS_GAP) 26 | self.i2c.write(self.devADC,ADC_CYCLE) 27 | time.sleep(BUS_GAP) 28 | self.i2c.read(self.devADC) #flush first value 29 | 30 | def getName(self): 31 | return self.NAME 32 | 33 | def getNew(self): 34 | data=[] 35 | for ch in ADC_CH: 36 | time.sleep(BUS_GAP) 37 | data.append(self.i2c.read(self.devADC)) 38 | return data 39 | 40 | def main(): 41 | ADC = device() 42 | print (str(ADC.getName())) 43 | for i in range(10): 44 | dataValues = ADC.getNew() 45 | print (str(dataValues)) 46 | time.sleep(1) 47 | 48 | if __name__=='__main__': 49 | main() 50 | #End 51 | -------------------------------------------------------------------------------- /Chapter10/data_local.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | #data_local.py 3 | import subprocess 4 | from random import randint 5 | import time 6 | 7 | MEM_TOTAL=0 8 | MEM_USED=1 9 | MEM_FREE=2 10 | MEM_OFFSET=7 11 | DRIVE_USED=0 12 | DRIVE_FREE=1 13 | DRIVE_OFFSET=9 14 | DEBUG=False 15 | DATANAME=["CPU_Load","System_Temp","CPU_Frequency", 16 | "Random","RAM_Total","RAM_Used","RAM_Free", 17 | "Drive_Used","Drive_Free"] 18 | 19 | def read_loadavg(): 20 | # function to read 1 minute load average from system uptime 21 | value = subprocess.check_output( 22 | ["awk '{print $1}' /proc/loadavg"], shell=True) 23 | return float(value) 24 | 25 | def read_systemp(): 26 | # function to read current system temperature 27 | value = subprocess.check_output( 28 | ["cat /sys/class/thermal/thermal_zone0/temp"], 29 | shell=True) 30 | return int(value) 31 | 32 | def read_cpu(): 33 | # function to read current clock frequency 34 | value = subprocess.check_output( 35 | ["cat /sys/devices/system/cpu/cpu0/cpufreq/"+ 36 | "scaling_cur_freq"], shell=True) 37 | return int(value) 38 | 39 | def read_rnd(): 40 | return randint(0,255) 41 | 42 | def read_mem(): 43 | # function to read RAM info 44 | value = subprocess.check_output(["free"], shell=True) 45 | memory=[] 46 | for val in value.split()[MEM_TOTAL+ 47 | MEM_OFFSET:MEM_FREE+ 48 | MEM_OFFSET+1]: 49 | memory.append(int(val)) 50 | return(memory) 51 | 52 | def read_drive(): 53 | # function to read drive info 54 | value = subprocess.check_output(["df"], shell=True) 55 | memory=[] 56 | for val in value.split()[DRIVE_USED+ 57 | DRIVE_OFFSET:DRIVE_FREE+ 58 | DRIVE_OFFSET+1]: 59 | memory.append(int(val)) 60 | return(memory) 61 | 62 | class device: 63 | # Constructor: 64 | def __init__(self,addr=0): 65 | self.NAME=DATANAME 66 | 67 | def getName(self): 68 | return self.NAME 69 | 70 | def getNew(self): 71 | data=[] 72 | data.append(read_loadavg()) 73 | data.append(read_systemp()) 74 | data.append(read_cpu()) 75 | data.append(read_rnd()) 76 | memory_ram = read_mem() 77 | data.append(memory_ram[MEM_TOTAL]) 78 | data.append(memory_ram[MEM_USED]) 79 | data.append(memory_ram[MEM_FREE]) 80 | memory_drive = read_drive() 81 | data.append(memory_drive[DRIVE_USED]) 82 | data.append(memory_drive[DRIVE_FREE]) 83 | return data 84 | 85 | def main(): 86 | LOCAL = device() 87 | print (str(LOCAL.getName())) 88 | for i in range(10): 89 | dataValues = LOCAL.getNew() 90 | print (str(dataValues)) 91 | time.sleep(1) 92 | 93 | if __name__=='__main__': 94 | main() 95 | #End -------------------------------------------------------------------------------- /Chapter10/del_data_lite.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Remove all the data in the table. 5 |
6 | query($strSQL); 12 | 13 | if ($response == 1) 14 | { 15 | echo "Result: DELETED DATA"; 16 | } 17 | else 18 | { 19 | echo "Error: Ensure table exists and database directory is owned by www-data"; 20 | } 21 | 22 | ?> 23 |

24 | Press button to return to data display. 25 |
26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /Chapter10/lcd_i2c.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import wiringpi2 3 | import time 4 | import datetime 5 | import data_adc as dataDevice 6 | 7 | AF_BASE=100 8 | AF_E=AF_BASE+13; AF_RW=AF_BASE+14; AF_RS=AF_BASE+15 9 | 10 | AF_DB4=AF_BASE+12; AF_DB5=AF_BASE+11; AF_DB6=AF_BASE+10; AF_DB7=AF_BASE+9 11 | 12 | AF_SELECT=AF_BASE+0; AF_RIGHT=AF_BASE+1; AF_DOWN=AF_BASE+2 13 | AF_UP=AF_BASE+3; AF_LEFT=AF_BASE+4; AF_BACK=AF_BASE+5 14 | 15 | AF_GREEN=AF_BASE+6; AF_BLUE=AF_BASE+7; AF_RED=AF_BASE+8 16 | BNK=" "*16 #16spaces 17 | 18 | def gpiosetup(): 19 | global lcd 20 | wiringpi2.wiringPiSetup() 21 | wiringpi2.mcp23017Setup(AF_BASE,0x20) 22 | wiringpi2.pinMode(AF_RIGHT,0) 23 | wiringpi2.pinMode(AF_LEFT,0) 24 | wiringpi2.pinMode(AF_SELECT,0) 25 | wiringpi2.pinMode(AF_RW,1) 26 | wiringpi2.digitalWrite(AF_RW,0) 27 | #lcdInit(int rows, int cols, int bits, int rs, int strb, int d0, int d1, int d2, int d3, int d4, int d5, int d6, int d7) 28 | lcd=wiringpi2.lcdInit(2,16,4,AF_RS,AF_E,AF_DB4,AF_DB5,AF_DB6,AF_DB7,0,0,0,0) 29 | #wiringpi2.lcdHome(lcd) 30 | #wiringpi2.lcdClear(lcd) 31 | #wiringpi2.lcdPosition(lcd,0,0) 32 | 33 | def printLCD(line0="",line1=""): 34 | wiringpi2.lcdPosition(lcd,0,0) 35 | wiringpi2.lcdPrintf(lcd,line0+BNK) 36 | wiringpi2.lcdPosition(lcd,0,1) 37 | wiringpi2.lcdPrintf(lcd,line1+BNK) 38 | 39 | def checkBtn(idx,size): 40 | global run 41 | if wiringpi2.digitalRead(AF_LEFT): 42 | idx-=1 43 | printLCD() 44 | elif wiringpi2.digitalRead(AF_RIGHT): 45 | idx+=1 46 | printLCD() 47 | if wiringpi2.digitalRead(AF_SELECT): 48 | printLCD("Exit Display") 49 | run=False 50 | return idx%size 51 | 52 | def main(): 53 | global run 54 | gpiosetup() 55 | myData = dataDevice.device() 56 | myDataNames=myData.getName() 57 | run=True 58 | index=0 59 | while(run): 60 | data=myData.getNew() 61 | printLCD(myDataNames[index],str(data[index])) 62 | time.sleep(1) 63 | index = checkBtn(index,len(myDataNames)) 64 | 65 | 66 | 67 | main() 68 | 69 | -------------------------------------------------------------------------------- /Chapter10/live_graph.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | #live_graph.py 3 | import numpy as np 4 | import matplotlib.pyplot as plt 5 | import matplotlib.animation as animation 6 | import data_local as dataDevice 7 | 8 | PADDING=5 9 | myData = dataDevice.device() 10 | dispdata = [] 11 | timeplot=0 12 | fig, ax = plt.subplots() 13 | line, = ax.plot(dispdata) 14 | 15 | def update(data): 16 | global dispdata,timeplot 17 | timeplot+=1 18 | dispdata.append(data) 19 | ax.set_xlim(0, timeplot) 20 | ymin = min(dispdata)-PADDING 21 | ymax = max(dispdata)+PADDING 22 | ax.set_ylim(ymin, ymax) 23 | line.set_data(range(timeplot),dispdata) 24 | return line 25 | 26 | def data_gen(): 27 | while True: 28 | yield myData.getNew()[1]/1000 29 | 30 | ani = animation.FuncAnimation(fig, update, 31 | data_gen, interval=1000) 32 | plt.show() 33 | #End -------------------------------------------------------------------------------- /Chapter10/live_graph_light.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | #live_graph.py 3 | import numpy as np 4 | import matplotlib.pyplot as plt 5 | import matplotlib.animation as animation 6 | import data_adc as dataDevice 7 | 8 | PADDING=5 9 | myData = dataDevice.device() 10 | dispdata = [] 11 | timeplot=0 12 | fig, ax = plt.subplots() 13 | line, = ax.plot(dispdata) 14 | 15 | def update(data): 16 | global dispdata,timeplot 17 | timeplot+=1 18 | dispdata.append(data) 19 | ax.set_xlim(0, timeplot) 20 | ymin = min(dispdata)-PADDING 21 | ymax = max(dispdata)+PADDING 22 | ax.set_ylim(ymin, ymax) 23 | line.set_data(range(timeplot),dispdata) 24 | return line 25 | 26 | def data_gen(): 27 | while True: 28 | yield myData.getNew()[0] 29 | 30 | ani = animation.FuncAnimation(fig, update, 31 | data_gen, interval=1000) 32 | plt.show() 33 | #End 34 | -------------------------------------------------------------------------------- /Chapter10/log_adc.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | #log_adc.py 3 | import time 4 | import datetime 5 | import data_adc as dataDevice 6 | 7 | DEBUG=True 8 | FILE=True 9 | VAL0=0;VAL1=1;VAL2=2;VAL3=3 #Set data order 10 | FORMATHEADER="\t%s\t%s\t%s\t%s\t%s" 11 | FORMATBODY="%d\t%s\t%f\t%f\t%f\t%f" 12 | 13 | if(FILE):f = open("data.log",'w') 14 | 15 | def timestamp(): 16 | ts=time.time() 17 | return datetime.datetime.fromtimestamp(ts).strftime( 18 | '%Y-%m-%d %H:%M:%S') 19 | 20 | def main(): 21 | counter=0 22 | myData = dataDevice.device() 23 | myDataNames=myData.getName() 24 | header=(FORMATHEADER%("Time", 25 | myDataNames[VAL0],myDataNames[VAL1], 26 | myDataNames[VAL2],myDataNames[VAL3])) 27 | if(DEBUG):print (header) 28 | if(FILE):f.write(header+"\n") 29 | while(1): 30 | data=myData.getNew() 31 | counter+=1 32 | body=(FORMATBODY%(counter,timestamp(), 33 | data[VAL0],data[VAL1],data[VAL2],data[VAL3])) 34 | if(DEBUG):print (body) 35 | if(FILE):f.write(body+"\n") 36 | time.sleep(0.1) 37 | 38 | try: 39 | main() 40 | finally: 41 | f.close() 42 | #End 43 | -------------------------------------------------------------------------------- /Chapter10/log_graph.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | #log_graph.py 3 | import numpy as np 4 | import matplotlib.pyplot as plt 5 | 6 | filename = "data.log" 7 | OFFSET=2 8 | with open(filename) as f: 9 | header = f.readline().split('\t') 10 | 11 | data = np.genfromtxt(filename, delimiter='\t', skip_header=1, 12 | names=['sample', 'date', 'DATA0', 13 | 'DATA1', 'DATA2', 'DATA3']) 14 | fig = plt.figure(1) 15 | ax1 = fig.add_subplot(211)#numrows, numcols, fignum 16 | ax2 = fig.add_subplot(212) 17 | ax1.plot(data['sample'],data['DATA0'],'r', 18 | label=header[OFFSET+0]) 19 | ax2.plot(data['sample'],data['DATA1'],'b', 20 | label=header[OFFSET+1]) 21 | ax1.set_title("ADC Samples") 22 | ax1.set_xlabel('Samples') 23 | ax1.set_ylabel('Reading') 24 | ax2.set_xlabel('Samples') 25 | ax2.set_ylabel('Reading') 26 | 27 | leg1 = ax1.legend() 28 | leg2 = ax2.legend() 29 | 30 | plt.show() 31 | #End -------------------------------------------------------------------------------- /Chapter10/log_local.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | #log_local.py 3 | import time 4 | import datetime 5 | import data_adc as dataDevice 6 | 7 | DEBUG=True 8 | FILE=True 9 | VAL0=0;VAL1=1;VAL2=2;VAL3=3 #Set data order 10 | FORMATHEADER="\t%s\t%s\t%s\t%s\t%s" 11 | FORMATBODY="%d\t%s\t%f\t%f\t%f\t%f" 12 | 13 | if(FILE):f = open("data.log",'w') 14 | def timestamp(): 15 | ts=time.time() 16 | return datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') 17 | 18 | def main(): 19 | counter=0 20 | myData = dataDevice.device() 21 | myDataNames=myData.getName() 22 | header=(FORMATHEADER%("Time",myDataNames[VAL0],myDataNames[VAL1],myDataNames[VAL2],myDataNames[VAL3])) 23 | if(DEBUG):print (header) 24 | if(FILE):f.write(header+"\n") 25 | while(1): 26 | data=myData.getNew() 27 | counter+=1 28 | body=(FORMATBODY%(counter,timestamp(),data[0],data[1],data[2],data[3])) 29 | if(DEBUG):print (body) 30 | if(FILE):f.write(body+"\n") 31 | time.sleep(0.1) 32 | 33 | try: 34 | main() 35 | finally: 36 | f.close() 37 | #end 38 | -------------------------------------------------------------------------------- /Chapter10/mysqlite_adc.py: -------------------------------------------------------------------------------- 1 | 2 | #!/usr/bin/python3 3 | #mysql_adc.py 4 | import sqlite3 5 | import datetime 6 | import data_adc as dataDevice 7 | import time 8 | import os 9 | 10 | DEBUG=True 11 | SHOWSQL=True 12 | CLEARDATA=False 13 | VAL0=0;VAL1=1;VAL2=2;VAL3=3 #Set data order 14 | FORMATBODY="%5s %8s %14s %12s %16s" 15 | FORMATLIST="%5s %12s %10s %16s %7s" 16 | DATEBASE_DIR="/var/databases/datasite/" 17 | DATEBASE=DATEBASE_DIR+"mydatabase.db" 18 | TABLE="recordeddata" 19 | DELAY=1 #approximate seconds between samples 20 | 21 | def captureSamples(cursor): 22 | if(CLEARDATA):cursor.execute("DELETE FROM %s" %(TABLE)) 23 | myData = dataDevice.device() 24 | myDataNames=myData.getName() 25 | 26 | if(DEBUG):print(FORMATBODY%("##",myDataNames[VAL0], 27 | myDataNames[VAL1],myDataNames[VAL2], 28 | myDataNames[VAL3])) 29 | for x in range(10): 30 | data=myData.getNew() 31 | for i,dataName in enumerate(myDataNames): 32 | sqlquery = "INSERT INTO %s (itm_name, itm_value) " %(TABLE) + \ 33 | "VALUES('%s', %s)" \ 34 | %(str(dataName),str(data[i])) 35 | if (SHOWSQL):print(sqlquery) 36 | cursor.execute(sqlquery) 37 | # cursor.execute("INSERT INTO ? (itm_name, itm_value) VALUES('?', ?)", 38 | # (TABLE,str(dataName),data[i])) 39 | # cursor.execute("INSERT INTO ? (itm_name, itm_value) VALUES('?', ?)", 40 | # (str(TABLE),str(dataName),str(data[i]))) 41 | ## sqlquery = "INSERT INTO %s (itm_name, itm_value) VALUES(?, ?)" %(TABLE) 42 | # sqlquery = "INSERT INTO ? (itm_name, itm_value) VALUES(?, ?)" 43 | ## cursor.execute(sqlquery,(str(dataName),str(data[i]))) 44 | 45 | if(DEBUG):print(FORMATBODY%(x, 46 | data[VAL0],data[VAL1], 47 | data[VAL2],data[VAL3])) 48 | time.sleep(DELAY) 49 | cursor.commit() 50 | 51 | def displayAll(connect): 52 | sqlquery="SELECT * FROM %s" %(TABLE) 53 | if (SHOWSQL):print(sqlquery) 54 | cursor = connect.execute (sqlquery) 55 | print(FORMATLIST%("","Date","Time","Name","Value")) 56 | 57 | for x,column in enumerate(cursor.fetchall()): 58 | print(FORMATLIST%(x,str(column[0]),str(column[1]), 59 | str(column[2]),str(column[3]))) 60 | 61 | def createTable(cursor): 62 | print("Create a new table: %s" %(TABLE)) 63 | sqlquery="CREATE TABLE %s (" %(TABLE) + \ 64 | "itm_date DEFAULT (date('now','localtime')), " + \ 65 | "itm_time DEFAULT (time('now','localtime')), " + \ 66 | "itm_name, itm_value)" 67 | if (SHOWSQL):print(sqlquery) 68 | cursor.execute(sqlquery) 69 | cursor.commit() 70 | 71 | def openTable(cursor): 72 | try: 73 | displayAll(cursor) 74 | except sqlite3.OperationalError: 75 | print("Table does not exist in database") 76 | createTable(cursor) 77 | finally: 78 | captureSamples(cursor) 79 | displayAll(cursor) 80 | 81 | try: 82 | if not os.path.exists(DATEBASE_DIR): 83 | os.makedirs(DATEBASE_DIR) 84 | connection = sqlite3.connect(DATEBASE) 85 | try: 86 | openTable(connection) 87 | finally: 88 | connection.close() 89 | except sqlite3.OperationalError: 90 | print("Unable to open Database") 91 | finally: 92 | print("Done") 93 | 94 | #End 95 | -------------------------------------------------------------------------------- /Chapter10/mysqlite_local.py: -------------------------------------------------------------------------------- 1 | 2 | #!/usr/bin/python3 3 | #mysql_adc.py 4 | import sqlite3 5 | import datetime 6 | import data_local as dataDevice 7 | import time 8 | import os 9 | 10 | DEBUG=True 11 | SHOWSQL=True 12 | CLEARDATA=False 13 | VAL0=0;VAL1=1;VAL2=2;VAL3=3 #Set data order 14 | FORMATBODY="%5s %8s %14s %12s %16s" 15 | FORMATLIST="%5s %12s %10s %16s %7s" 16 | DATEBASE_DIR="/var/databases/datasite/" 17 | DATEBASE=DATEBASE_DIR+"mydatabase.db" 18 | TABLE="recordeddata" 19 | DELAY=1 #approximate seconds between samples 20 | 21 | def captureSamples(cursor): 22 | if(CLEARDATA):cursor.execute("DELETE FROM %s" %(TABLE)) 23 | myData = dataDevice.device() 24 | myDataNames=myData.getName() 25 | 26 | if(DEBUG):print(FORMATBODY%("##",myDataNames[VAL0], 27 | myDataNames[VAL1],myDataNames[VAL2], 28 | myDataNames[VAL3])) 29 | for x in range(10): 30 | data=myData.getNew() 31 | for i,dataName in enumerate(myDataNames): 32 | sqlquery = "INSERT INTO %s (itm_name, itm_value) " %(TABLE) + \ 33 | "VALUES('%s', %s)" \ 34 | %(str(dataName),str(data[i])) 35 | if (SHOWSQL):print(sqlquery) 36 | cursor.execute(sqlquery) 37 | # cursor.execute("INSERT INTO ? (itm_name, itm_value) VALUES('?', ?)", 38 | # (TABLE,str(dataName),data[i])) 39 | # cursor.execute("INSERT INTO ? (itm_name, itm_value) VALUES('?', ?)", 40 | # (str(TABLE),str(dataName),str(data[i]))) 41 | ## sqlquery = "INSERT INTO %s (itm_name, itm_value) VALUES(?, ?)" %(TABLE) 42 | # sqlquery = "INSERT INTO ? (itm_name, itm_value) VALUES(?, ?)" 43 | ## cursor.execute(sqlquery,(str(dataName),str(data[i]))) 44 | 45 | if(DEBUG):print(FORMATBODY%(x, 46 | data[VAL0],data[VAL1], 47 | data[VAL2],data[VAL3])) 48 | time.sleep(DELAY) 49 | cursor.commit() 50 | 51 | def displayAll(connect): 52 | sqlquery="SELECT * FROM %s" %(TABLE) 53 | if (SHOWSQL):print(sqlquery) 54 | cursor = connect.execute (sqlquery) 55 | print(FORMATLIST%("","Date","Time","Name","Value")) 56 | 57 | for x,column in enumerate(cursor.fetchall()): 58 | print(FORMATLIST%(x,str(column[0]),str(column[1]), 59 | str(column[2]),str(column[3]))) 60 | 61 | def createTable(cursor): 62 | print("Create a new table: %s" %(TABLE)) 63 | sqlquery="CREATE TABLE %s (" %(TABLE) + \ 64 | "itm_date DEFAULT (date('now','localtime')), " + \ 65 | "itm_time DEFAULT (time('now','localtime')), " + \ 66 | "itm_name, itm_value)" 67 | if (SHOWSQL):print(sqlquery) 68 | cursor.execute(sqlquery) 69 | cursor.commit() 70 | 71 | def openTable(cursor): 72 | try: 73 | displayAll(cursor) 74 | except sqlite3.OperationalError: 75 | print("Table does not exist in database") 76 | createTable(cursor) 77 | finally: 78 | captureSamples(cursor) 79 | displayAll(cursor) 80 | 81 | try: 82 | if not os.path.exists(DATEBASE_DIR): 83 | os.makedirs(DATEBASE_DIR) 84 | connection = sqlite3.connect(DATEBASE) 85 | try: 86 | openTable(connection) 87 | finally: 88 | connection.close() 89 | except sqlite3.OperationalError: 90 | print("Unable to open Database") 91 | finally: 92 | print("Done") 93 | 94 | #End 95 | -------------------------------------------------------------------------------- /Chapter10/show_data_lite.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | Database Data 4 | 5 | 6 | 7 | 8 | Press button to remove the table data 9 |
10 | 11 |

12 | Recorded Data
13 | query($strSQL); 20 | //Loop through the response 21 | while($column = $response->fetch()) 22 | { 23 | //Display the content of the response 24 | echo $column[0] . " "; 25 | echo $column[1] . " "; 26 | echo $column[2] . " "; 27 | echo $column[3] . "
"; 28 | } 29 | ?> 30 | Done 31 | 32 | 33 | -------------------------------------------------------------------------------- /Chapter10/xivelylog.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | #xivelylog.py 3 | import xively 4 | import time 5 | import datetime 6 | import requests 7 | from random import randint 8 | import data_local as dataDevice 9 | 10 | # Set the FEED_ID and API_KEY from your account 11 | FEED_ID = 399948883 12 | API_KEY = "CcRxJbP5TuHp1PiOGVrN2kTGeXVsb6QZRJU236v6PjOdtzze" 13 | api = xively.XivelyAPIClient(API_KEY) # initialize api client 14 | DEBUG=True 15 | 16 | myData = dataDevice.device() 17 | myDataNames=myData.getName() 18 | 19 | def get_datastream(feed,name,tags): 20 | try: 21 | datastream = feed.datastreams.get(name) 22 | if DEBUG:print ("Found existing datastream") 23 | return datastream 24 | except: 25 | if DEBUG:print ("Creating new datastream") 26 | datastream = feed.datastreams.create(name, tags=tags) 27 | return datastream 28 | 29 | def run(): 30 | print ("Connecting to Xively") 31 | feed = api.feeds.get(FEED_ID) 32 | if DEBUG:print ("Got feed" + str(feed)) 33 | datastreams=[] 34 | for dataName in myDataNames: 35 | dstream = get_datastream(feed,dataName,dataName) 36 | #dstream.max_value = None 37 | #dstream.min_value = None 38 | if DEBUG:print ("Got %s datastream:%s"%(dataName,dstream)) 39 | datastreams.append(dstream) 40 | 41 | while True: 42 | data=myData.getNew() 43 | for idx,dataValue in enumerate(data): 44 | if DEBUG: 45 | print ("Updating %s: %s" % (dataName,dataValue)) 46 | datastreams[idx].current_value = dataValue 47 | datastreams[idx].at = datetime.datetime.utcnow() 48 | try: 49 | for ds in datastreams: 50 | ds.update() 51 | except requests.HTTPError as e: 52 | print ("HTTPError({0}): {1}".format(e.errno, e.strerror)) 53 | time.sleep(60) 54 | 55 | run() 56 | #End 57 | -------------------------------------------------------------------------------- /Chapter11/optical_charecter_recognition.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import neurolab as nl 3 | 4 | # Input file 5 | in_file = 'words.data' 6 | 7 | # Number of datapoints to load from the input file 8 | num_of_datapoints = 20 9 | 10 | # Distinct characters 11 | original_labels = 'omandig' 12 | 13 | # Number of distinct characters 14 | num_of_charect = len(original_labels) 15 | 16 | # Training and testing parameters 17 | train_param = int(0.9 * num_of_datapoints) 18 | test_param = num_of_datapoints - train_param 19 | 20 | # Define dataset extraction parameters 21 | s_index = 6 22 | e_index = -1 23 | 24 | # Creating the dataset 25 | information = [] 26 | labels = [] 27 | with open(in_file, 'r') as f: 28 | for line in f.readlines(): 29 | # Split the line tabwise 30 | list_of_values = line.split('\t') 31 | 32 | # If the label is not in our ground truth labels, skip it 33 | if list_of_values[1] not in original_labels: 34 | continue 35 | 36 | # Extract the label and append it to the main list 37 | label = np.zeros((num_of_charect , 1)) 38 | label[original_labels.index(list_of_values[1])] = 1 39 | labels.append(label) 40 | 41 | # Extract the character vector and append it to the main list 42 | extract_char = np.array([float(x) for x in list_of_values[s_index:e_index]]) 43 | information.append(extract_char) 44 | 45 | # Exit the loop once the required dataset has been loaded 46 | if len(information) >= num_of_datapoints: 47 | break 48 | 49 | # Convert information and labels to numpy arrays 50 | information = np.array(information) 51 | labels = np.array(labels).reshape(num_of_datapoints, num_of_charect) 52 | 53 | # Extract number of dimensions 54 | num_dimension = len(information[0]) 55 | 56 | # Create and train neural network 57 | neural_net = nl.net.newff([[0, 1] for _ in range(len(information[0]))], [128, 16, num_of_charect]) 58 | neural_net.trainf = nl.train.train_gd 59 | error = neural_net.train(information[:train_param,:], labels[:train_param,:], epochs=10000, show=100, goal=0.01) 60 | 61 | # Predict the output for test inputs 62 | p_output = neural_net.sim(information[train_param:, :]) 63 | print "\nTesting on unknown data:" 64 | for i in range(test_param): 65 | print "\nOriginal:", original_labels[np.argmax(labels[i])] 66 | print "Predicted:", original_labels[np.argmax(p_output[i])] 67 | 68 | -------------------------------------------------------------------------------- /Chapter11/visualize_characters.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | 4 | import cv2 5 | import numpy as np 6 | 7 | # Load input data 8 | in_file = 'words.data' 9 | 10 | # Define visualization parameters 11 | scale_factor = 10 12 | s_index = 6 13 | e_index = -1 14 | h, w = 16, 8 15 | 16 | # Loop until you encounter the Esc key 17 | with open(in_file, 'r') as f: 18 | for line in f.readlines(): 19 | information = np.array([255*float(x) for x in line.split('\t')[s_index:e_index]]) 20 | image = np.reshape(information, (h,w)) 21 | image_scaled = cv2.resize(image, None, fx=scale_factor, fy=scale_factor) 22 | cv2.imshow('Image', image_scaled) 23 | a = cv2.waitKey() 24 | if a == 10: 25 | break 26 | -------------------------------------------------------------------------------- /Chapter12/XLoBorg3-part1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | #XLoBorg3-part1.py 3 | import wiringpi2 4 | import struct 5 | import time 6 | 7 | global DEBUG 8 | DEBUG=False 9 | 10 | def readBlockData(bus,device,register,words): 11 | magData=[] 12 | for i in range(words): 13 | magData.append(bus.readReg16(device,register+i)) 14 | return magData 15 | 16 | class compass: 17 | def __init__(self): 18 | addr = 0x0E #compass 19 | self.i2c = wiringpi2.I2C() 20 | self.devMAG=self.i2c.setup(addr) 21 | self.initCompass() 22 | 23 | def initCompass(self): 24 | # Acquisition mode 25 | register = 0x11 # CTRL_REG2 26 | data = (1 << 7) # Reset before each acquisition 27 | data |= (1 << 5) # Raw mode, do not apply user offsets 28 | data |= (0 << 5) # Disable reset cycle 29 | self.i2c.writeReg8(self.devMAG,register,data) 30 | # System operation 31 | register = 0x10 # CTRL_REG1 32 | data = (0 << 5) # Output data rate 33 | # (10 Hz when paired with 128 oversample) 34 | data |= (3 << 3) # Oversample of 128 35 | data |= (0 << 2) # Disable fast read 36 | data |= (0 << 1) # Continuous measurement 37 | data |= (1 << 0) # Active mode 38 | self.i2c.writeReg8(self.devMAG,register,data) 39 | 40 | def readCompassRaw(self): 41 | #x, y, z = readCompassRaw() 42 | self.i2c.write(self.devMAG,0x00) 43 | [status, xh, xl, yh, yl, 44 | zh, zl, who, sm, oxh, oxl, 45 | oyh, oyl, ozh, ozl, 46 | temp, c1, c2] = readBlockData(self.i2c,self.devMAG, 0, 18) 47 | # Convert from unsigned to correctly signed values 48 | bytes = struct.pack('BBBBBB', xl, xh, yl, yh, zl, zh) 49 | x, y, z = struct.unpack('hhh', bytes) 50 | return x, y, z 51 | 52 | if __name__ == '__main__': 53 | DEBUG=True 54 | myCompass=compass() 55 | try: 56 | while True: 57 | # Read the MAG Data 58 | mx, my, mz = myCompass.readCompassRaw() 59 | print ("mX = %+06d, mY = %+06d, mZ = %+06d" % (mx, my, mz)) 60 | time.sleep(0.1) 61 | except KeyboardInterrupt: 62 | print("Finished") 63 | #End 64 | -------------------------------------------------------------------------------- /Chapter12/XLoBorg3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | #XLoBorg3.py 3 | import wiringpi2 4 | import struct 5 | import time 6 | import math 7 | 8 | CAL=100 #take CAL samples 9 | FILENAME="mag.cal" 10 | global DEBUG 11 | DEBUG=False 12 | 13 | def readBlockData(bus,device,register,words): 14 | magData=[] 15 | for i in range(words): 16 | magData.append(bus.readReg16(device,register+i)) 17 | return magData 18 | 19 | class compass: 20 | def __init__(self,newCal=False): 21 | addr = 0x0E #compass 22 | self.i2c = wiringpi2.I2C() 23 | self.devMAG=self.i2c.setup(addr) 24 | self.initCompass() 25 | self.offset,self.scaling=self.readCal(newCal) 26 | if DEBUG:print("offset:%s scaling:%s"%(str(self.offset), 27 | str(self.scaling))) 28 | 29 | def initCompass(self): 30 | # Acquisition mode 31 | register = 0x11 # CTRL_REG2 32 | data = (1 << 7) # Reset before each acquisition 33 | data |= (1 << 5) # Raw mode, do not apply user offsets 34 | data |= (0 << 5) # Disable reset cycle 35 | self.i2c.writeReg8(self.devMAG,register,data) 36 | # System operation 37 | register = 0x10 # CTRL_REG1 38 | data = (0 << 5) # Output data rate 39 | # (10 Hz when paired with 128 oversample) 40 | data |= (3 << 3) # Oversample of 128 41 | data |= (0 << 2) # Disable fast read 42 | data |= (0 << 1) # Continuous measurement 43 | data |= (1 << 0) # Active mode 44 | self.i2c.writeReg8(self.devMAG,register,data) 45 | 46 | def readCal(self,newCal=False,filename=FILENAME): 47 | if newCal==False: 48 | try: 49 | with open(FILENAME,'r') as magCalFile: 50 | line=magCalFile.readline() 51 | offset=line.split() 52 | line=magCalFile.readline() 53 | scaling=line.split() 54 | if len(offset)==0 or len(scaling)==0: 55 | raise ValueError() 56 | else: 57 | offset=list(map(float, offset)) 58 | scaling=list(map(float, scaling)) 59 | except (OSError,IOError,TypeError,ValueError) as e: 60 | print("No Cal Data") 61 | newCal=True 62 | pass 63 | if newCal==True: 64 | print("Perform New Calibration") 65 | offset,scaling=self.calibrateCompass() 66 | self.writeCal(offset,scaling) 67 | return offset,scaling 68 | 69 | def writeCal(self,offset,scaling): 70 | if DEBUG:print("Write Calibration") 71 | if DEBUG:print("offset:"+str(offset)) 72 | if DEBUG:print("scaling:"+str(scaling)) 73 | with open(FILENAME,'w') as magCalFile: 74 | for value in offset: 75 | magCalFile.write(str(value)+" ") 76 | magCalFile.write("\n") 77 | for value in scaling: 78 | magCalFile.write(str(value)+" ") 79 | magCalFile.write("\n") 80 | 81 | def calibrateCompass(self,samples=CAL): 82 | MAXS16=32768 83 | SCALE=1000.0 84 | avg=[0,0,0] 85 | min=[MAXS16,MAXS16,MAXS16];max=[-MAXS16,-MAXS16,-MAXS16] 86 | print("Move sensor around axis (start in 5 sec)") 87 | time.sleep(5) 88 | for calibrate in range(samples): 89 | for idx,value in enumerate(self.readCompassRaw()): 90 | avg[idx]+=value 91 | avg[idx]/=2 92 | if(value>max[idx]): 93 | max[idx]=value 94 | if(value180: 20 | CMD=LEFT 21 | else: 22 | CMD=RIGHT 23 | return CMD 24 | 25 | def main(): 26 | myCompass=XLoBorg.compass() 27 | myBot=drive.motor() 28 | while(True): 29 | print("Enter target angle:") 30 | ANGLE=input() 31 | try: 32 | angleTarget=float(ANGLE) 33 | CMD=LEFT 34 | while (CMD!=DONE): 35 | angleCompass=myCompass.readCompassAngle() 36 | CMD=calDir(angleTarget,angleCompass) 37 | print("CMD: %s"%CMD) 38 | time.sleep(1) 39 | myBot.cmd(CMD) 40 | print("Angle Reached!") 41 | except ValueError: 42 | print("Enter valid angle!") 43 | pass 44 | 45 | if __name__ == '__main__': 46 | try: 47 | main() 48 | except KeyboardInterrupt: 49 | print ("Finish") 50 | #End 51 | -------------------------------------------------------------------------------- /Chapter12/rover_drive.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | #rover_drivefwd.py 3 | #HARDWARE SETUP 4 | # P1 5 | # 2[==X====lRr===]26[=======]40 6 | # 1[=======L=====]25[=======]39 7 | import time 8 | import wiringpi2 9 | ON=1;OFF=0 10 | IN=0;OUT=1 11 | STEP=0.2 12 | PINS=[15,16,18,22] # PINS=[L_FWD,L_BWD,R_FWD,R_BWD] 13 | FWD=[ON,OFF,ON,OFF] 14 | BWD=[OFF,ON,OFF,ON] 15 | RIGHT=[OFF,ON,ON,OFF] 16 | LEFT=[ON,OFF,OFF,ON] 17 | DEBUG=True 18 | 19 | class motor: 20 | # Constructor 21 | def __init__(self,pins=PINS,steptime=STEP): 22 | self.pins = pins 23 | self.steptime=steptime 24 | self.GPIOsetup() 25 | 26 | def GPIOsetup(self): 27 | wiringpi2.wiringPiSetupPhys() 28 | for gpio in self.pins: 29 | wiringpi2.pinMode(gpio,OUT) 30 | 31 | def off(self): 32 | for gpio in self.pins: 33 | wiringpi2.digitalWrite(gpio,OFF) 34 | 35 | def drive(self,drive,step=STEP): 36 | for idx,gpio in enumerate(self.pins): 37 | wiringpi2.digitalWrite(gpio,drive[idx]) 38 | if(DEBUG):print("%s:%s"%(gpio,drive[idx])) 39 | time.sleep(step) 40 | self.off() 41 | 42 | def cmd(self,char,step=STEP): 43 | if char == 'f': 44 | self.drive(FWD,step) 45 | elif char == 'b': 46 | self.drive(BWD,step) 47 | elif char == 'r': 48 | self.drive(RIGHT,step) 49 | elif char == 'l': 50 | self.drive(LEFT,step) 51 | elif char == '#': 52 | time.sleep(step) 53 | 54 | def main(): 55 | import os 56 | if "CMD" in os.environ: 57 | CMD=os.environ["CMD"] 58 | INPUT=False 59 | print("CMD="+CMD) 60 | else: 61 | INPUT=True 62 | roverPi=motor() 63 | if INPUT: 64 | print("Enter CMDs [f,b,r,l,#]:") 65 | CMD=input() 66 | for idx,char in enumerate(CMD.lower()): 67 | if(DEBUG):print("Step %s of %s: %s"%(idx+1,len(CMD),char)) 68 | roverPi.cmd(char) 69 | 70 | if __name__ == '__main__': 71 | try: 72 | main() 73 | except KeyboardInterrupt: 74 | print ("Finish") 75 | #End 76 | -------------------------------------------------------------------------------- /Chapter12/rover_drive_hwpwm.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import time 3 | import wiringpi2 4 | ON=1;OFF=0 5 | IN=0;OUT=1 6 | STEP=0.2 7 | PINS=[15,16,18,22] # PINS=[L_FWD,L_BWD,R_FWD,R_BWD] 8 | FWD=[ON,OFF,ON,OFF] 9 | BWD=[OFF,ON,OFF,ON] 10 | RIGHT=[OFF,ON,ON,OFF] 11 | LEFT=[ON,OFF,OFF,ON] 12 | PWM_PIN=12; PWM=2; ON_TIME=512 #0-1024 Off-On 13 | DEBUG=True 14 | 15 | class motor: 16 | # Constructor 17 | def __init__(self,pins=PINS,steptime=STEP): 18 | self.pins = pins 19 | self.steptime=steptime 20 | self.GPIOsetup() 21 | 22 | def GPIOsetup(self): 23 | wiringpi2.wiringPiSetupPhys() 24 | wiringpi2.pinMode(PWM_PIN,PWM) 25 | wiringpi2.pwmWrite(PWM_PIN,ON_TIME) 26 | for gpio in self.pins: 27 | wiringpi2.pinMode(gpio,OUT) 28 | 29 | def off(self): 30 | for gpio in self.pins: 31 | wiringpi2.digitalWrite(gpio,OFF) 32 | 33 | def drive(self,drive,step=STEP): 34 | for idx,gpio in enumerate(self.pins): 35 | wiringpi2.digitalWrite(gpio,drive[idx]) 36 | if(DEBUG):print("%s:%s"%(gpio,drive[idx])) 37 | time.sleep(step) 38 | self.off() 39 | 40 | def cmd(self,char,step=STEP): 41 | if char == 'f': 42 | self.drive(FWD,step) 43 | elif char == 'b': 44 | self.drive(BWD,step) 45 | elif char == 'r': 46 | self.drive(RIGHT,step) 47 | elif char == 'l': 48 | self.drive(LEFT,step) 49 | elif char == '#': 50 | time.sleep(step) 51 | 52 | def main(): 53 | import os 54 | if "CMD" in os.environ: 55 | CMD=os.environ["CMD"] 56 | INPUT=False 57 | print("CMD="+CMD) 58 | else: 59 | INPUT=True 60 | roverPi=motor() 61 | if INPUT: 62 | print("Enter CMDs [f,b,r,l,#]:") 63 | CMD=input() 64 | for idx,char in enumerate(CMD.lower()): 65 | print("Step %s of %s: %s"%(idx+1,len(CMD),char)) 66 | roverPi.cmd(char) 67 | 68 | if __name__ == '__main__': 69 | try: 70 | main() 71 | except KeyboardInterrupt: 72 | print ("Finish") 73 | #End 74 | 75 | -------------------------------------------------------------------------------- /Chapter12/rover_drive_i2c.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import time 3 | import wiringpi2 4 | ON=1;OFF=0 5 | IN=0;OUT=1 6 | STEP=0.2 7 | PINS=[15,16,18,22] # PINS=[L_FWD,L_BWD,R_FWD,R_BWD] 8 | FWD=[ON,OFF,ON,OFF] 9 | BWD=[OFF,ON,OFF,ON] 10 | RIGHT=[OFF,ON,ON,OFF] 11 | LEFT=[ON,OFF,OFF,ON] 12 | IO_ADDR=0x20 13 | DEBUG=True 14 | 15 | class motor: 16 | # Constructor 17 | def __init__(self,pins=PINS,steptime=STEP,pinbase=0,ADDR=IO_ADDR): 18 | self.pins=[] 19 | for p in pins: 20 | self.pins.append(p+pinbase) 21 | self.steptime=steptime 22 | self.GPIOsetup(pinbase) 23 | 24 | def GPIOsetup(self,pinbase=0,ADDR=IO_ADDR): 25 | wiringpi2.wiringPiSetupPhys() 26 | if (pinbase!=0): 27 | wiringpi2.mcp23017Setup(pinbase,ADDR) 28 | for gpio in self.pins: 29 | wiringpi2.pinMode(gpio,OUT) 30 | 31 | def off(self): 32 | for gpio in self.pins: 33 | wiringpi2.digitalWrite(gpio,OFF) 34 | 35 | def drive(self,drive,step=STEP): 36 | for idx,gpio in enumerate(self.pins): 37 | wiringpi2.digitalWrite(gpio,drive[idx]) 38 | if(DEBUG):print("%s:%s"%(gpio,drive[idx])) 39 | time.sleep(step) 40 | self.off() 41 | 42 | def cmd(self,char,step=STEP): 43 | if char == 'f': 44 | self.drive(FWD,step) 45 | elif char == 'b': 46 | self.drive(BWD,step) 47 | elif char == 'r': 48 | self.drive(RIGHT,step) 49 | elif char == 'l': 50 | self.drive(LEFT,step) 51 | elif char == '#': 52 | time.sleep(step) 53 | 54 | def main(): 55 | import os 56 | if "CMD" in os.environ: 57 | CMD=os.environ["CMD"] 58 | INPUT=False 59 | print("CMD="+CMD) 60 | else: 61 | INPUT=True 62 | roverPi=motor(pins=[0,1,2,3],pinbase=100) 63 | if INPUT: 64 | print("Enter CMDs [f,b,r,l,#]:") 65 | CMD=input() 66 | for idx,char in enumerate(CMD.lower()): 67 | print("Step %s of %s: %s"%(idx+1,len(CMD),char)) 68 | roverPi.cmd(char) 69 | 70 | if __name__ == '__main__': 71 | try: 72 | main() 73 | except KeyboardInterrupt: 74 | print ("Finish") 75 | #End 76 | 77 | -------------------------------------------------------------------------------- /Chapter12/rover_drive_swpwm.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import time 3 | import wiringpi2 4 | ON=1;OFF=0 5 | IN=0;OUT=1 6 | STEP=0.2 7 | PINS=[15,16,18,22] # PINS=[L_FWD,L_BWD,R_FWD,R_BWD] 8 | FWD=[ON,OFF,ON,OFF] 9 | BWD=[OFF,ON,OFF,ON] 10 | RIGHT=[OFF,ON,ON,OFF] 11 | LEFT=[ON,OFF,OFF,ON] 12 | PWM_PIN_ENA=7;PWM_PIN_ENA=11;RANGE=100 #0-100 (100Hz Max) 13 | ON_TIME1=20; ON_TIME2=75 #0-100 14 | DEBUG=True 15 | 16 | class motor: 17 | # Constructor 18 | def __init__(self,pins=PINS,steptime=STEP): 19 | self.pins = pins 20 | self.steptime=steptime 21 | self.GPIOsetup() 22 | 23 | def GPIOsetup(self): 24 | wiringpi2.wiringPiSetupPhys() 25 | wiringpi2.softPwmCreate(PWM_PIN_ENA,ON_TIME1,RANGE) 26 | wiringpi2.softPwmCreate(PWM_PIN_ENB,ON_TIME2,RANGE) 27 | for gpio in self.pins: 28 | wiringpi2.pinMode(gpio,OUT) 29 | 30 | def off(self): 31 | for gpio in self.pins: 32 | wiringpi2.digitalWrite(gpio,OFF) 33 | 34 | def drive(self,drive,step=STEP): 35 | for idx,gpio in enumerate(self.pins): 36 | wiringpi2.digitalWrite(gpio,drive[idx]) 37 | if(DEBUG):print("%s:%s"%(gpio,drive[idx])) 38 | time.sleep(step) 39 | self.off() 40 | 41 | def cmd(self,char,step=STEP): 42 | if char == 'f': 43 | self.drive(FWD,step) 44 | elif char == 'b': 45 | self.drive(BWD,step) 46 | elif char == 'r': 47 | self.drive(RIGHT,step) 48 | elif char == 'l': 49 | self.drive(LEFT,step) 50 | elif char == '#': 51 | time.sleep(step) 52 | 53 | def main(): 54 | import os 55 | if "CMD" in os.environ: 56 | CMD=os.environ["CMD"] 57 | INPUT=False 58 | print("CMD="+CMD) 59 | else: 60 | INPUT=True 61 | roverPi=motor() 62 | if INPUT: 63 | print("Enter CMDs [f,b,r,l,#]:") 64 | CMD=input() 65 | for idx,char in enumerate(CMD.lower()): 66 | print("Step %s of %s: %s"%(idx+1,len(CMD),char)) 67 | roverPi.cmd(char) 68 | 69 | if __name__ == '__main__': 70 | try: 71 | main() 72 | except KeyboardInterrupt: 73 | print ("Finish") 74 | #End 75 | 76 | -------------------------------------------------------------------------------- /Chapter12/rover_drivefwd.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | #rover_drivefwd.py 3 | #HARDWARE SETUP 4 | # P1 5 | # 2[==X====LR====]26[=======]40 6 | # 1[=============]25[=======]39 7 | import time 8 | import wiringpi2 9 | ON=1;OFF=0 10 | IN=0;OUT=1 11 | STEP=0.5 12 | PINS=[16,18] # PINS=[L-motor,R-motor] 13 | FWD=[ON,ON] 14 | RIGHT=[ON,OFF] 15 | LEFT=[OFF,ON] 16 | DEBUG=True 17 | 18 | class motor: 19 | # Constructor 20 | def __init__(self,pins=PINS,steptime=STEP): 21 | self.pins = pins 22 | self.steptime=steptime 23 | self.GPIOsetup() 24 | 25 | def GPIOsetup(self): 26 | wiringpi2.wiringPiSetupPhys() 27 | for gpio in self.pins: 28 | wiringpi2.pinMode(gpio,OUT) 29 | 30 | def off(self): 31 | for gpio in self.pins: 32 | wiringpi2.digitalWrite(gpio,OFF) 33 | 34 | def drive(self,drive,step=STEP): 35 | for idx,gpio in enumerate(self.pins): 36 | wiringpi2.digitalWrite(gpio,drive[idx]) 37 | if(DEBUG):print("%s:%s"%(gpio,drive[idx])) 38 | time.sleep(step) 39 | self.off() 40 | 41 | def cmd(self,char,step=STEP): 42 | if char == 'f': 43 | self.drive(FWD,step) 44 | elif char == 'r': 45 | self.drive(RIGHT,step) 46 | elif char == 'l': 47 | self.drive(LEFT,step) 48 | elif char == '#': 49 | time.sleep(step) 50 | 51 | def main(): 52 | import os 53 | if "CMD" in os.environ: 54 | CMD=os.environ["CMD"] 55 | INPUT=False 56 | print("CMD="+CMD) 57 | else: 58 | INPUT=True 59 | roverPi=motor() 60 | if INPUT: 61 | print("Enter CMDs [f,r,l,#]:") 62 | CMD=input() 63 | for idx,char in enumerate(CMD.lower()): 64 | if(DEBUG):print("Step %s of %s: %s"%(idx+1,len(CMD),char)) 65 | roverPi.cmd(char) 66 | 67 | if __name__ == '__main__': 68 | try: 69 | main() 70 | except KeyboardInterrupt: 71 | print ("Finish") 72 | #End 73 | 74 | -------------------------------------------------------------------------------- /Chapter12/servoAdafruit.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | #servoAdafruit.py 3 | import wiringpi2 4 | import time 5 | 6 | #PWM Registers 7 | MODE1=0x00 8 | PRESCALE=0xFE 9 | LED0_ON_L=0x06 10 | LED0_ON_H=0x07 11 | LED0_OFF_L=0x08 12 | LED0_OFF_H=0x09 13 | 14 | PWMHZ=50 15 | PWMADR=0x40 16 | 17 | 18 | class servo: 19 | # Constructor 20 | def __init__(self,pwmFreq=PWMHZ,addr=PWMADR): 21 | self.i2c = wiringpi2.I2C() 22 | self.devPWM=self.i2c.setup(addr) 23 | self.GPIOsetup(pwmFreq,addr) 24 | 25 | def GPIOsetup(self,pwmFreq,addr): 26 | self.i2c.read(self.devPWM) 27 | self.pwmInit(pwmFreq) 28 | 29 | def pwmInit(self,pwmFreq): 30 | prescale = 25000000.0 / 4096.0 # 25MHz / 12-bit 31 | prescale /= float(pwmFreq) 32 | prescale = prescale - 0.5 #-1 then +0.5 to round to 33 | # nearest value 34 | prescale = int(prescale) 35 | self.i2c.writeReg8(self.devPWM,MODE1,0x00) #RESET 36 | mode=self.i2c.read(self.devPWM) 37 | self.i2c.writeReg8(self.devPWM,MODE1, 38 | (mode & 0x7F)|0x10) #SLEEP 39 | self.i2c.writeReg8(self.devPWM,PRESCALE,prescale) 40 | self.i2c.writeReg8(self.devPWM,MODE1,mode) #restore mode 41 | time.sleep(0.005) 42 | self.i2c.writeReg8(self.devPWM,MODE1,mode|0x80) #restart 43 | 44 | def setPWM(self,channel, on, off): 45 | on=int(on) 46 | off=int(off) 47 | self.i2c.writeReg8(self.devPWM, 48 | LED0_ON_L+4*channel,on & 0xFF) 49 | self.i2c.writeReg8(self.devPWM,LED0_ON_H+4*channel,on>>8) 50 | self.i2c.writeReg8(self.devPWM, 51 | LED0_OFF_L+4*channel,off & 0xFF) 52 | self.i2c.writeReg8(self.devPWM,LED0_OFF_H+4*channel,off>>8) 53 | 54 | def main(): 55 | servoMin = 205 # Min pulse 1ms 204.8 (50Hz) 56 | servoMax = 410 # Max pulse 2ms 409.6 (50Hz) 57 | myServo=servo() 58 | myServo.setPWM(0,0,servoMin) 59 | time.sleep(2) 60 | myServo.setPWM(0,0,servoMax) 61 | 62 | if __name__ == '__main__': 63 | try: 64 | main() 65 | except KeyboardInterrupt: 66 | print ("Finish") 67 | #End 68 | 69 | -------------------------------------------------------------------------------- /Chapter12/servo_control.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | #servo_control.py 3 | import curses 4 | import os 5 | #HARDWARE SETUP 6 | # GPIO 7 | # 2[=VX==2=======]26[=======]40 8 | # 1[===013=======]25[=======]39 9 | # V=5V X=Gnd 10 | # Servo 0=Turn 1=Shoulder 2=Elbox 3=Claw 11 | name=["Turn","Shoulder","Elbow","Claw"] 12 | CAL=[90,90,90,90] 13 | MIN=[0,60,40,60]; MAX=[180,165,180,180] 14 | POS=list(CAL) 15 | KEY_CMD=[ord('c'),ord('x')] 16 | #Keys to rotate counter-clockwise 17 | KEY_LESS={ord('d'):0,ord('s'):1,ord('j'):2,ord('k'):3} 18 | #Keys to rotate clockwise 19 | KEY_MORE={ord('a'):0,ord('w'):1,ord('l'):2,ord('i'):3} 20 | 21 | STEP=5; LESS=-STEP; MORE=STEP #Define control steps 22 | DEG2MS=8.3333; OFFSET=1000 #mseconds 23 | IDLE=2000 #Timeout servo after command 24 | SERVOD="/home/pi/PiBits/ServoBlaster/user/servod" #Location of servod 25 | DEBUG=True 26 | text="Use a-d, w-s, j-l and i-k to control the MeArm. c=Cal x=eXit" 27 | 28 | def initalise(): 29 | cmd=("sudo %s --idle-timeout=%s"%(SERVOD, IDLE)) 30 | os.system(cmd) 31 | 32 | def limitServo(servo,value): 33 | global text 34 | if value > MAX[servo]: 35 | text=("Max %s position %s:%s"%(name[servo],servo,POS[servo])) 36 | return MAX[servo] 37 | elif value < MIN[servo]: 38 | text=("Min %s position %s:%s"%(name[servo],servo,POS[servo])) 39 | return MIN[servo] 40 | else: 41 | return value 42 | 43 | def updateServo(servo,change): 44 | global text 45 | POS[servo]=limitServo(servo,POS[servo]+change) 46 | setServo(servo,POS[servo]) 47 | text=str(POS) 48 | 49 | def setServo(servo,position): 50 | ms=OFFSET+(position*DEG2MS) 51 | os.system("echo %d=%dus > /dev/servoblaster" %(servo,ms)) 52 | 53 | def calibrate(): 54 | global text 55 | text="Calibrate 90deg" 56 | for i,value in enumerate(CAL): 57 | POS[i]=value 58 | setServo(i,value) 59 | 60 | def main(term): 61 | term.nodelay(1) 62 | term.addstr(text) 63 | term.refresh() 64 | while True: 65 | term.move(1,0) 66 | c = term.getch() 67 | if c != -1: 68 | if c in KEY_MORE: 69 | updateServo(KEY_MORE[c],MORE) 70 | elif c in KEY_LESS: 71 | updateServo(KEY_LESS[c],LESS) 72 | elif c in KEY_CMD: 73 | if c == ord('c'): 74 | calibrate() 75 | elif c == ord('x'): 76 | exit() 77 | if DEBUG:term.addstr(text+" ") 78 | 79 | if __name__=='__main__': 80 | initalise() 81 | curses.wrapper(main) 82 | #End 83 | -------------------------------------------------------------------------------- /Chapter12/sonic.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | #sonic.py 3 | import wiringpi2 4 | import time 5 | import datetime 6 | 7 | ON=1;OFF=0; IN=0;OUT=1 8 | TRIGGER=15 9 | ECHO=7 10 | PULSE=0.00001 #10us pulse 11 | SPEEDOFSOUND=34029 #34029 cm/s 12 | 13 | def gpiosetup(): 14 | wiringpi2.wiringPiSetupPhys() 15 | wiringpi2.pinMode(TRIGGER,OUT) 16 | wiringpi2.pinMode(ECHO,IN) 17 | wiringpi2.digitalWrite(TRIGGER,OFF) 18 | time.sleep(0.5) 19 | 20 | def pulse(): 21 | wiringpi2.digitalWrite(TRIGGER,ON) 22 | time.sleep(PULSE) 23 | wiringpi2.digitalWrite(TRIGGER,OFF) 24 | starttime=time.time() 25 | stop=starttime 26 | start=starttime 27 | while wiringpi2.digitalRead(ECHO)==0 and start>bit & 1) 24 | 25 | def setBit(value,bit,state=1): 26 | mask=1<', self.mouseClick) 66 | 67 | def mouseClick(self,event): 68 | itemsClicked=self.canvas.find_overlapping(event.x, 69 | event.y,event.x+1,event.y+1) 70 | for item in itemsClicked: 71 | self.toggleLight(item) 72 | 73 | def setLight(self,num): 74 | state=isBitSet(self.lightStatus,num) 75 | self.canvas.itemconfig(self.light[num], 76 | fill=LIGHTOFFON[state]) 77 | 78 | def toggleLight(self,num): 79 | if num != 0: 80 | self.lightStatus=toggleBit(self.lightStatus,num-1) 81 | self.setLight(num-1) 82 | self.generateCode() 83 | 84 | def generateCode(self): 85 | self.codeText.set("0x%016x"%self.lightStatus) 86 | 87 | def changedCode(self,*args): 88 | updated=False 89 | try: 90 | codeValue=int(self.codeText.get(),16) 91 | if(codeValue>MAX_VALUE): 92 | codeValue=codeValue>>4 93 | self.updateLight(codeValue) 94 | updated=True 95 | except: 96 | self.generateCode() 97 | updated=False 98 | return updated 99 | 100 | def updateLight(self,lightsetting): 101 | self.lightStatus=lightsetting 102 | for num in range(NUM_LIGHTS): 103 | self.setLight(num) 104 | self.generateCode() 105 | self.updateHardware() 106 | 107 | def updateHardware(self): 108 | sendBytes=self.lightStatus.to_bytes(NUM_BUTTON, 109 | byteorder='big') 110 | print(sendBytes) 111 | for idx,row in enumerate(MC.MAX7219_DIGIT): 112 | response = self.matrix.sendCmd(row,sendBytes[idx]) 113 | print(response) 114 | 115 | def main(): 116 | global root 117 | root=TK.Tk() 118 | root.title("Matrix GUI") 119 | myMatrixHW=MC.matrix(DEBUG) 120 | myMatrixGUI=matrixGUI(root,myMatrixHW) 121 | TK.mainloop() 122 | 123 | if __name__ == '__main__': 124 | main() 125 | #End 126 | -------------------------------------------------------------------------------- /Chapter13/missileControl.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # missileControl.py 3 | import time 4 | import usb.core 5 | 6 | class SamMissile(): 7 | idVendor=0x1130 8 | idProduct=0x0202 9 | idName="Tenx Technology SAM Missile" 10 | # Protocol control bytes 11 | bmRequestType=0x21 12 | bmRequest=0x09 13 | wValue=0x02 14 | wIndex=0x01 15 | # Protocol command bytes 16 | INITA = [ord('U'), ord('S'), ord('B'), ord('C'), 17 | 0, 0, 4, 0] 18 | INITB = [ord('U'), ord('S'), ord('B'), ord('C'), 19 | 0, 64, 2, 0] 20 | CMDFILL = [ 8, 8, 21 | 0, 0, 0, 0, 0, 0, 0, 0, 22 | 0, 0, 0, 0, 0, 0, 0, 0, 23 | 0, 0, 0, 0, 0, 0, 0, 0, 24 | 0, 0, 0, 0, 0, 0, 0, 0, 25 | 0, 0, 0, 0, 0, 0, 0, 0, 26 | 0, 0, 0, 0, 0, 0, 0, 0, 27 | 0, 0, 0, 0, 0, 0, 0, 0]#48 zeros 28 | STOP = [ 0, 0, 0, 0, 0, 0] 29 | LEFT = [ 0, 1, 0, 0, 0, 0] 30 | RIGHT = [ 0, 0, 1, 0, 0, 0] 31 | UP = [ 0, 0, 0, 1, 0, 0] 32 | DOWN = [ 0, 0, 0, 0, 1, 0] 33 | LEFTUP = [ 0, 1, 0, 1, 0, 0] 34 | RIGHTUP = [ 0, 0, 1, 1, 0, 0] 35 | LEFTDOWN = [ 0, 1, 0, 0, 1, 0] 36 | RIGHTDOWN = [ 0, 0, 1, 0, 1, 0] 37 | FIRE = [ 0, 0, 0, 0, 0, 1] 38 | def __init__(self): 39 | self.dev = usb.core.find(idVendor=self.idVendor, 40 | idProduct=self.idProduct) 41 | def move(self,cmd,duration): 42 | print("Move:%s %d sec"% (cmd,duration)) 43 | self.dev.ctrl_transfer(self.bmRequestType, 44 | self.bmRequest,self.wValue, 45 | self.wIndex, self.INITA) 46 | self.dev.ctrl_transfer(self.bmRequestType, 47 | self.bmRequest,self.wValue, 48 | self.wIndex, self.INITB) 49 | self.dev.ctrl_transfer(self.bmRequestType, 50 | self.bmRequest, self.wValue, 51 | self.wIndex, cmd+self.CMDFILL) 52 | time.sleep(duration) 53 | self.dev.ctrl_transfer(self.bmRequestType, 54 | self.bmRequest, self.wValue, 55 | self.wIndex, self.INITA) 56 | self.dev.ctrl_transfer(self.bmRequestType, 57 | self.bmRequest, self.wValue, 58 | self.wIndex, self.INITB) 59 | self.dev.ctrl_transfer(self.bmRequestType, 60 | self.bmRequest, self.wValue, 61 | self.wIndex, self.STOP+self.CMDFILL) 62 | 63 | class ChesenMissile(): 64 | idVendor=0x0a81 65 | idProduct=0x0701 66 | idName="Chesen Electronics/Dream Link" 67 | # Protocol control bytes 68 | bmRequestType=0x21 69 | bmRequest=0x09 70 | wValue=0x0200 71 | wIndex=0x00 72 | # Protocol command bytes 73 | DOWN = [0x01] 74 | UP = [0x02] 75 | LEFT = [0x04] 76 | RIGHT = [0x08] 77 | FIRE = [0x10] 78 | STOP = [0x20] 79 | def __init__(self): 80 | self.dev = usb.core.find(idVendor=self.idVendor, 81 | idProduct=self.idProduct) 82 | def move(self,cmd,duration): 83 | print("Move:%s"%cmd) 84 | self.dev.ctrl_transfer(self.bmRequestType, 85 | self.bmRequest, 86 | self.wValue, self.wIndex, cmd) 87 | time.sleep(duration) 88 | self.dev.ctrl_transfer(self.bmRequestType, 89 | self.bmRequest, self.wValue, 90 | self.wIndex, self.STOP) 91 | 92 | class ThunderMissile(): 93 | idVendor=0x2123 94 | idProduct=0x1010 95 | idName="Dream Cheeky Thunder" 96 | # Protocol control bytes 97 | bmRequestType=0x21 98 | bmRequest=0x09 99 | wValue=0x00 100 | wIndex=0x00 101 | # Protocol command bytes 102 | CMDFILL = [0,0,0,0,0,0] 103 | DOWN = [0x02,0x01] 104 | UP = [0x02,0x02] 105 | LEFT = [0x02,0x04] 106 | RIGHT = [0x02,0x08] 107 | FIRE = [0x02,0x10] 108 | STOP = [0x02,0x20] 109 | def __init__(self): 110 | self.dev = usb.core.find(idVendor=self.idVendor, 111 | idProduct=self.idProduct) 112 | def move(self,cmd,duration): 113 | print("Move:%s"%cmd) 114 | self.dev.ctrl_transfer(self.bmRequestType, 115 | self.bmRequest, self.wValue, 116 | self.wIndex, cmd+self.CMDFILL) 117 | time.sleep(duration) 118 | self.dev.ctrl_transfer(self.bmRequestType, 119 | self.bmRequest, self.wValue, 120 | self.wIndex, self.STOP+self.CMDFILL) 121 | 122 | 123 | class Missile(): 124 | def __init__(self): 125 | print("Initialize Missiles") 126 | self.usbDevice=SamMissile() 127 | 128 | if self.usbDevice.dev is not None: 129 | print("Device Initialized:" + 130 | " %s" % self.usbDevice.idName) 131 | #Detach the kernel driver if active 132 | if self.usbDevice.dev.is_kernel_driver_active(0): 133 | print("Detaching kernel driver 0") 134 | self.usbDevice.dev.detach_kernel_driver(0) 135 | if self.usbDevice.dev.is_kernel_driver_active(1): 136 | print("Detaching kernel driver 1") 137 | self.usbDevice.dev.detach_kernel_driver(1) 138 | self.usbDevice.dev.set_configuration() 139 | else: 140 | raise Exception("Missile device not found") 141 | def __enter__(self): 142 | return self 143 | def left(self,duration=1): 144 | self.usbDevice.move(self.usbDevice.LEFT,duration) 145 | def right(self,duration=1): 146 | self.usbDevice.move(self.usbDevice.RIGHT,duration) 147 | def up(self,duration=1): 148 | self.usbDevice.move(self.usbDevice.UP,duration) 149 | def down(self,duration=1): 150 | self.usbDevice.move(self.usbDevice.DOWN,duration) 151 | def fire(self,duration=1): 152 | self.usbDevice.move(self.usbDevice.FIRE,duration) 153 | def stop(self,duration=1): 154 | self.usbDevice.move(self.usbDevice.STOP,duration) 155 | def __exit__(self, type, value, traceback): 156 | print("Exit") 157 | 158 | def main(): 159 | try: 160 | with Missile() as myMissile: 161 | myMissile.down() 162 | time.sleep(2) 163 | myMissile.up() 164 | except Exception as detail: 165 | print("Error: %s" % detail) 166 | 167 | if __name__ == '__main__': 168 | main() 169 | #End 170 | -------------------------------------------------------------------------------- /Chapter13/missileMenu.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | #missileMenu.py 3 | import tkinter as TK 4 | import missileControl as MC 5 | 6 | BTN_SIZE=10 7 | 8 | def menuInit(): 9 | btnLeft = TK.Button(root, text="Left", 10 | command=sendLeft, width=BTN_SIZE) 11 | btnRight = TK.Button(root, text="Right", 12 | command=sendRight, width=BTN_SIZE) 13 | btnUp = TK.Button(root, text="Up", 14 | command=sendUp, width=BTN_SIZE) 15 | btnDown = TK.Button(root, text="Down", 16 | command=sendDown, width=BTN_SIZE) 17 | btnFire = TK.Button(root, text="Fire",command=sendFire, 18 | width=BTN_SIZE, bg="red") 19 | btnLeft.grid(row=2,column=0) 20 | btnRight.grid(row=2,column=2) 21 | btnUp.grid(row=1,column=1) 22 | btnDown.grid(row=3,column=1) 23 | btnFire.grid(row=2,column=1) 24 | 25 | def sendLeft(): 26 | print("Left") 27 | myMissile.left() 28 | 29 | def sendRight(): 30 | print("Right") 31 | myMissile.right() 32 | 33 | def sendUp(): 34 | print("Up") 35 | myMissile.up() 36 | 37 | def sendDown(): 38 | print("Down") 39 | myMissile.down() 40 | 41 | def sendFire(): 42 | print("Fire") 43 | myMissile.fire() 44 | 45 | 46 | root = TK.Tk() 47 | root.title("Missile Command") 48 | prompt = "Select action" 49 | label1 = TK.Label(root, text=prompt, width=len(prompt), 50 | justify=TK.CENTER, bg='lightblue') 51 | label1.grid(row=0,column=0,columnspan=3) 52 | menuInit() 53 | with MC.Missile() as myMissile: 54 | root.mainloop() 55 | #End 56 | -------------------------------------------------------------------------------- /Chapter13/robotarmControl.py: -------------------------------------------------------------------------------- 1 | class OwiArm(): 2 | idVendor=0x1267 3 | idProduct=0x0000 4 | idName="Owi Robot Arm" 5 | # Protocol control bytes 6 | bmRequestType=0x40 7 | bmRequest=0x06 8 | wValue=0x0100 9 | wIndex=0x00 10 | # Protocol command bytes 11 | BASE_CCW = [0x00,0x01,0x00] 12 | BASE_CW = [0x00,0x02,0x00] 13 | SHOLDER_UP = [0x40,0x00,0x00] 14 | SHOLDER_DWN = [0x80,0x00,0x00] 15 | ELBOW_UP = [0x10,0x00,0x00] 16 | ELBOW_DWN = [0x20,0x00,0x00] 17 | WRIST_UP = [0x04,0x00,0x00] 18 | WRIST_DOWN = [0x08,0x00,0x00] 19 | GRIP_OPEN = [0x02,0x00,0x00] 20 | GRIP_CLOSE = [0x01,0x00,0x00] 21 | LIGHT_ON = [0x00,0x00,0x01] 22 | LIGHT_OFF = [0x00,0x00,0x00] 23 | STOP = [0x00,0x00,0x00] 24 | -------------------------------------------------------------------------------- /Chapter13/serialControl.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | #serialControl.py 3 | import serial 4 | import time 5 | 6 | #Serial Port settings 7 | SERNAME="/dev/ttyUSB0" 8 | #SERNAME="/dev/ttyAMA0" 9 | #default setting is 9600,8,N,1 10 | IDLE=0; SEND=1; RECEIVE=1 11 | 12 | def b2s(message): 13 | '''Byte to String''' 14 | return bytes.decode(message) 15 | def s2b(message): 16 | '''String to Byte''' 17 | return bytearray(message,"ascii") 18 | 19 | class serPort(): 20 | def __init__(self,serName="/dev/ttyAMA0"): 21 | self.ser = serial.Serial(serName) 22 | print (self.ser.name) 23 | print (self.ser) 24 | self.state=IDLE 25 | def __enter__(self): 26 | return self 27 | def send(self,message): 28 | if self.state==IDLE and self.ser.isOpen(): 29 | self.state=SEND 30 | self.ser.write(s2b(message)) 31 | self.state=IDLE 32 | 33 | def receive(self, chars=1, timeout=5, echo=True, 34 | terminate="\r"): 35 | message="" 36 | if self.state==IDLE and self.ser.isOpen(): 37 | self.state=RECEIVE 38 | self.ser.timeout=timeout 39 | while self.state==RECEIVE: 40 | echovalue="" 41 | while self.ser.inWaiting() > 0: 42 | echovalue += b2s(self.ser.read(chars)) 43 | if echo==True: 44 | self.ser.write(s2b(echovalue)) 45 | message+=echovalue 46 | if terminate in message: 47 | self.state=IDLE 48 | return message 49 | def __exit__(self,type,value,traceback): 50 | self.ser.close() 51 | 52 | def main(): 53 | try: 54 | with serPort(serName=SERNAME) as mySerialPort: 55 | mySerialPort.send("Send some data to me!\r\n") 56 | while True: 57 | print ("Waiting for input:") 58 | print (mySerialPort.receive()) 59 | except OSError: 60 | print ("Check selected port is valid: %s" %serName) 61 | except KeyboardInterrupt: 62 | print ("Finished") 63 | 64 | if __name__=="__main__": 65 | main() 66 | #End 67 | -------------------------------------------------------------------------------- /Chapter13/serialMenu.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | #serialMenu.py 3 | import time 4 | import RPi.GPIO as GPIO 5 | import serialControl as SC 6 | SERNAME = "/dev/ttyUSB0" 7 | running=True 8 | 9 | CMD=0;PIN=1;STATE=2;OFF=0;ON=1 10 | GPIO_PINS=[7,11,12,13,15,16,18,22] 11 | GPIO_STATE=["OFF","ON"] 12 | EXIT="EXIT" 13 | 14 | def gpioSetup(): 15 | GPIO.setmode(GPIO.BOARD) 16 | for pin in GPIO_PINS: 17 | GPIO.setup(pin,GPIO.OUT) 18 | 19 | def handleCmd(cmd): 20 | global running 21 | commands=cmd.upper() 22 | commands=commands.split() 23 | valid=False 24 | print ("Received: "+ str(commands)) 25 | if len(commands)==3: 26 | if commands[CMD]=="GPIO": 27 | for pin in GPIO_PINS: 28 | if str(pin)==commands[PIN]: 29 | print ("GPIO pin is valid") 30 | if GPIO_STATE[OFF]==commands[STATE]: 31 | print ("Switch GPIO %s %s"% (commands[PIN], 32 | commands[STATE])) 33 | GPIO.output(pin,OFF) 34 | valid=True 35 | elif GPIO_STATE[ON]==commands[STATE]: 36 | print ("Switch GPIO %s %s"% (commands[PIN], 37 | commands[STATE])) 38 | GPIO.output(pin,ON) 39 | valid=True 40 | elif commands[CMD]==EXIT: 41 | print("Exit") 42 | valid=True 43 | running=False 44 | if valid==False: 45 | print ("Received command is invalid") 46 | response=" Invalid:GPIO Pin#(%s) %s\r\n"% ( 47 | str(GPIO_PINS), str(GPIO_STATE)) 48 | else: 49 | response=" OK\r\n" 50 | return (response) 51 | 52 | def main(): 53 | try: 54 | gpioSetup() 55 | with SC.serPort(serName=SERNAME) as mySerialPort: 56 | mySerialPort.send("\r\n") 57 | mySerialPort.send(" GPIO Serial Control\r\n") 58 | mySerialPort.send(" -------------------\r\n") 59 | mySerialPort.send(" CMD PIN STATE "+ 60 | "[GPIO Pin# ON]\r\n") 61 | while running==True: 62 | print ("Waiting for command...") 63 | mySerialPort.send(">>") 64 | cmd = mySerialPort.receive(terminate="\r\n") 65 | response=handleCmd(cmd) 66 | mySerialPort.send(response) 67 | mySerialPort.send(" Finished!\r\n") 68 | except OSError: 69 | print ("Check selected port is valid: %s" %serName) 70 | except KeyboardInterrupt: 71 | print ("Finished") 72 | finally: 73 | GPIO.cleanup() 74 | 75 | main() 76 | #End 77 | -------------------------------------------------------------------------------- /Chapter13/serialTest.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | #serialTest.py 3 | import serial 4 | import time 5 | 6 | WAITTIME=1 7 | serName="/dev/ttyAMA0" 8 | ser = serial.Serial(serName) 9 | print (ser.name) 10 | print (ser) 11 | if ser.isOpen(): 12 | try: 13 | print("For Serial Loopback - connect GPIO Pin8 and Pin10") 14 | print("[Type Message and Press Enter to continue]") 15 | print("#:") 16 | command=input() 17 | ser.write(bytearray(command+"\r\n","ascii")) 18 | time.sleep(WAITTIME) 19 | out="" 20 | while ser.inWaiting() > 0: 21 | out += bytes.decode(ser.read(1)) 22 | if out != "": 23 | print (">>" + out) 24 | else: 25 | print ("No data Received") 26 | except KeyboardInterrupt: 27 | ser.close() 28 | #End 29 | 30 | -------------------------------------------------------------------------------- /Chapter13/socketControl.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # socketControl.py 3 | import time 4 | import RPi.GPIO as GPIO 5 | #HARDWARE SETUP 6 | # P1 7 | # 2[V=G====XI====]26[=======]40 8 | # 1[=====321=====]25[=======]39 9 | #V=5V G=Gnd 10 | sw_num=[15,13,11]#Pins for Switch 1,2,3 11 | sw_state=[16,18]#Pins for State X=Off,I=On 12 | MSGOFF=0; MSGON=1 13 | SW_ACTIVE=0; SW_INACTIVE=1 14 | 15 | class Switch(): 16 | def __init__(self): 17 | self.setup() 18 | def __enter__(self): 19 | return self 20 | def setup(self): 21 | print("Do init") 22 | #Setup the wiring 23 | GPIO.setmode(GPIO.BOARD) 24 | for pin in sw_num: 25 | GPIO.setup(pin,GPIO.OUT) 26 | for pin in sw_state: 27 | GPIO.setup(pin,GPIO.OUT) 28 | self.clear() 29 | def message(self,number,state): 30 | print ("SEND SW_CMD: %s %d" % (number,state)) 31 | if state==MSGON: 32 | self.on(number) 33 | else: 34 | self.off(number) 35 | def on(self,number): 36 | print ("ON: %d"% number) 37 | GPIO.output(sw_num[number-1],SW_ACTIVE) 38 | GPIO.output(sw_state[MSGON],SW_ACTIVE) 39 | GPIO.output(sw_state[MSGOFF],SW_INACTIVE) 40 | time.sleep(0.5) 41 | self.clear() 42 | def off(self,number): 43 | print ("OFF: %d"% number) 44 | GPIO.output(sw_num[number-1],SW_ACTIVE) 45 | GPIO.output(sw_state[MSGON],SW_INACTIVE) 46 | GPIO.output(sw_state[MSGOFF],SW_ACTIVE) 47 | time.sleep(0.5) 48 | self.clear() 49 | def clear(self): 50 | for pin in sw_num: 51 | GPIO.output(pin,SW_INACTIVE) 52 | for pin in sw_state: 53 | GPIO.output(pin,SW_INACTIVE) 54 | def __exit__(self, type, value, traceback): 55 | self.clear() 56 | GPIO.cleanup() 57 | 58 | def main(): 59 | with Switch() as mySwitches: 60 | mySwitches.on(1) 61 | time.sleep(5) 62 | mySwitches.off(1) 63 | 64 | if __name__ == "__main__": 65 | main() 66 | #End 67 | -------------------------------------------------------------------------------- /Chapter13/socketMenu.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | #socketMenu.py 3 | import tkinter as TK 4 | import socketControl as SC 5 | 6 | #Define Switches ["Switch name","Switch number"] 7 | switch1 = ["Living Room Lamp",1] 8 | switch2 = ["Coffee Machine",2] 9 | switch3 = ["Bedroom Fan",3] 10 | sw_list = [switch1,switch2,switch3] 11 | SW_NAME = 0; SW_CMD = 1 12 | SW_COLOR=["gray","green"] 13 | 14 | class swButtons: 15 | def __init__(self,gui,sw_index,switchCtrl): 16 | #Add the buttons to window 17 | self.msgType=TK.IntVar() 18 | self.msgType.set(SC.MSGOFF) 19 | self.btn = TK.Button(gui, 20 | text=sw_list[sw_index][SW_NAME], 21 | width=30, command=self.sendMsg, 22 | bg=SW_COLOR[self.msgType.get()]) 23 | self.btn.pack() 24 | msgOn = TK.Radiobutton(gui,text="On", 25 | variable=self.msgType, value=SC.MSGON) 26 | msgOn.pack() 27 | msgOff = TK.Radiobutton(gui,text="Off", 28 | variable=self.msgType,value=SC.MSGOFF) 29 | msgOff.pack() 30 | self.sw_num=sw_list[sw_index][SW_CMD] 31 | self.sw_ctrl=switchCtrl 32 | def sendMsg(self): 33 | print ("SW_CMD: %s %d" % (self.sw_num, 34 | self.msgType.get())) 35 | self.btn.configure(bg=SW_COLOR[self.msgType.get()]) 36 | self.sw_ctrl.message(self.sw_num, 37 | self.msgType.get()) 38 | 39 | root = TK.Tk() 40 | root.title("Remote Switches") 41 | prompt = "Control a switch" 42 | label1 = TK.Label(root, text=prompt, width=len(prompt), 43 | justify=TK.CENTER, bg='lightblue') 44 | label1.pack() 45 | #Create the switch 46 | with SC.Switch() as mySwitches: 47 | #Create menu buttons from sw_list 48 | for index, app in enumerate(sw_list): 49 | swButtons(root,index,mySwitches) 50 | root.mainloop() 51 | #End 52 | -------------------------------------------------------------------------------- /Chapter13/spiTest.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # spiTest.py 3 | import wiringpi 4 | 5 | print("Add SPI Loopback - connect GPIO Pin19 and Pin21") 6 | print("[Press Enter to continue]") 7 | input() 8 | wiringpi.wiringPiSPISetup(1,500000) 9 | buffer=str.encode("HELLO") 10 | print("Buffer sent %s" % buffer) 11 | wiringpi.wiringPiSPIDataRW(1,buffer) 12 | print("Buffer received %s" % buffer) 13 | print("Remove the SPI Loopback") 14 | print("[Press Enter to continue]") 15 | input() 16 | buffer=str.encode("HELLO") 17 | print("Buffer sent %s" % buffer) 18 | wiringpi.wiringPiSPIDataRW(1,buffer) 19 | print("Buffer received %s" % buffer) 20 | #End 21 | -------------------------------------------------------------------------------- /Chapter14/Euclidean_distance.py: -------------------------------------------------------------------------------- 1 | import json 2 | import numpy as np 3 | 4 | def euclidean_dist_score(dataset, FirstUser, SecondUser): 5 | if FirstUser not in dataset: 6 | raiseTypeError('User ' + FirstUser + ' not present in the dataset') 7 | if SecondUser not in dataset: 8 | raiseTypeError('User ' + SecondUser + ' not present in the dataset') 9 | 10 | # Movies rated by both FirstUser and SecondUser 11 | Both_User_rated = {} 12 | for element in dataset[FirstUser]: 13 | if element in dataset[SecondUser]: 14 | Both_User_rated[element] = 1 15 | 16 | # Score 0 indicate no common movies 17 | if len(Both_User_rated) == 0: 18 | return 0 19 | 20 | SquareDifference = [] 21 | for element in dataset[FirstUser]: 22 | if element in dataset[SecondUser]: 23 | SquareDifference.append(np.square(dataset[FirstUser][element] - dataset[SecondUser][element])) 24 | 25 | return 1 / (1 + np.sqrt(np.sum(SquareDifference))) 26 | 27 | if __name__=='__main__': 28 | data_file = 'movie_rating.json' 29 | with open(data_file, 'r') as m: 30 | dataset = json.loads(m.read()) 31 | 32 | FirstUser = 'Steven Ferndndes' 33 | SecondUser = 'Ramesh Nayak' 34 | print "\nEuclidean score:" 35 | print euclidean_dist_score(dataset, FirstUser, SecondUser) 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /Chapter14/Pearson_correlation.py: -------------------------------------------------------------------------------- 1 | import json 2 | import numpy as np 3 | 4 | # Returns the Pearson correlation score between user1 and user2 5 | def pearson_dist_score(dataset, FirstUser, SecondUser): 6 | if FirstUser not in dataset: 7 | raise TypeError('User ' + FirstUser + ' not present in the dataset') 8 | if SecondUser not in dataset: 9 | raise TypeError('User ' + SecondUser + ' not present in the dataset') 10 | 11 | # Movies rated by both FirstUser and SecondUser 12 | both_User_rated = {} 13 | for element in dataset[FirstUser]: 14 | if element in dataset[SecondUser]: 15 | both_User_rated[element] = 1 16 | 17 | rating_number = len(both_User_rated) 18 | 19 | # Score 0 indicate no common movies 20 | if rating_number == 0: 21 | return 0 22 | 23 | # Calculate the sum of ratings of all the common preferences 24 | FirstUser_sum = np.sum([dataset[FirstUser][element] for element in both_User_rated]) 25 | SecondUser_sum = np.sum([dataset[SecondUser][element] for element in both_User_rated]) 26 | 27 | # Calculate the sum of squared ratings of all the common preferences 28 | FirstUser_squared_sum = np.sum([np.square(dataset[FirstUser][element]) for element in both_User_rated]) 29 | SecondUser_squared_sum = np.sum([np.square(dataset[SecondUser][element]) for element in both_User_rated]) 30 | 31 | # Calculate the sum of products of the common ratings 32 | sum_product = np.sum([dataset[FirstUser][element] * dataset[SecondUser][element] for element in both_User_rated]) 33 | 34 | # Pearson correlation calculation 35 | 36 | PSxy = sum_product - (FirstUser_sum * SecondUser_sum / rating_number) 37 | PSxx = FirstUser_squared_sum - np.square(FirstUser_sum) / rating_number 38 | PSyy = SecondUser_squared_sum - np.square(SecondUser_sum) / rating_number 39 | 40 | if PSxx * PSyy == 0: 41 | return 0 42 | 43 | return PSxy / np.sqrt(PSxx * PSyy) 44 | 45 | if __name__=='__main__': 46 | data_file = 'movie_rating.json' 47 | with open(data_file, 'r') as m: 48 | dataset = json.loads(m.read()) 49 | FirstUser = 'Steven Ferndndes' 50 | SecondUser = 'Ramesh Nayak' 51 | print "\nPearson score:" 52 | print pearson_dist_score(dataset, FirstUser, SecondUser) 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /Chapter14/movie_rating.json: -------------------------------------------------------------------------------- 1 | { 2 | "Steven Ferndndes": 3 | { 4 | "50 Shades of Gray": 3.5, 5 | "Angry Bird": 3.0, 6 | "Jerry Maguire": 3.0 7 | }, 8 | "Ramesh Nayak": 9 | { 10 | "Intersteller": 3.0, 11 | "50 Shades of Gray": 3.5, 12 | "Angry Bird": 1.5, 13 | "Avengers": 5.0, 14 | "Dark night": 3.0, 15 | "Jerry Maguire": 3.0 16 | }, 17 | "William Reynolds": 18 | { 19 | "Intersteller": 2.5, 20 | "50 Shades of Gray": 3.0, 21 | "Avengers": 3.5, 22 | "Dark night": 4.0 23 | }, 24 | "Jillian Hobart": 25 | { 26 | "50 Shades of Gray": 3.5, 27 | "Angry Bird": 3.0, 28 | "Jerry Maguire": 4.5, 29 | "Avengers": 4.0, 30 | "Dark night": 2.5 31 | }, 32 | "Melissa Jones": 33 | { 34 | "Intersteller": 3.0, 35 | "50 Shades of Gray": 4.0, 36 | "Angry Bird": 2.0, 37 | "Avengers": 3.0, 38 | "Dark night": 3.0, 39 | "Jerry Maguire": 2.0 40 | }, 41 | "Alex Roberts": 42 | { 43 | "Intersteller": 3.0, 44 | "50 Shades of Gray": 4.0, 45 | "Dark night": 3.0, 46 | "Avengers": 5.0, 47 | "Jerry Maguire": 3.5 48 | }, 49 | "Michael Henry": 50 | { 51 | "Intersteller": 4.5, 52 | "Jerry Maguire": 1.0, 53 | "Avengers": 4.0 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /Chapter14/movie_recommendations.py: -------------------------------------------------------------------------------- 1 | import json 2 | import numpy as np 3 | 4 | def pearson_dist_score(dataset, user, s): 5 | if user not in dataset: 6 | raise TypeError('User ' + user + ' not present in the dataset') 7 | if s not in dataset: 8 | raise TypeError('User ' + s + ' not present in the dataset') 9 | 10 | # Movies rated by both FirstUser and SecondUser 11 | both_User_rated = {} 12 | for element in dataset[user]: 13 | if element in dataset[s]: 14 | both_User_rated[element] = 1 15 | 16 | rating_number = len(both_User_rated) 17 | 18 | # Score 0 indicate no common movies 19 | if rating_number == 0: 20 | return 0 21 | 22 | # Calculate the sum of ratings of all the common preferences 23 | user_sum = np.sum([dataset[user][element] for element in both_User_rated]) 24 | s_sum = np.sum([dataset[s][element] for element in both_User_rated]) 25 | 26 | # Calculate the sum of squared ratings of all the common preferences 27 | user_squared_sum = np.sum([np.square(dataset[user][element]) for element in both_User_rated]) 28 | s_squared_sum = np.sum([np.square(dataset[s][element]) for element in both_User_rated]) 29 | 30 | # Calculate the sum of products of the common ratings 31 | sum_product = np.sum([dataset[user][element] * dataset[s][element] for element in both_User_rated]) 32 | 33 | # Pearson correlation calculation 34 | 35 | PSxy = sum_product - (user_sum * s_sum / rating_number) 36 | PSxx = user_squared_sum - np.square(user_sum) / rating_number 37 | PSyy = s_squared_sum - np.square(s_sum) / rating_number 38 | 39 | 40 | if PSxx * PSyy == 0: 41 | return 0 42 | 43 | return PSxy / np.sqrt(PSxx * PSyy) 44 | 45 | # Generate recommendations for a given user 46 | def movie_recommendations(dataset , user): 47 | if user not in dataset: 48 | raise TypeError('User ' + user + ' not present in the dataset') 49 | 50 | scores_sum = {} 51 | sum_similarity = {} 52 | 53 | for s in [a for a in dataset if a != user]: 54 | score_similarity = pearson_dist_score(dataset , user, s) 55 | 56 | if score_similarity <= 0: 57 | continue 58 | 59 | for element in [a for a in dataset[s] if a not in dataset[user] or dataset[user][a] == 0]: 60 | 61 | scores_sum.update({element: dataset[s][element] * score_similarity}) 62 | sum_similarity.update({element: score_similarity}) 63 | 64 | if len(scores_sum) == 0: 65 | return ['No recommendations possible'] 66 | 67 | # Create the normalized list 68 | movie_ranking = np.array([[total/sum_similarity[element], element] 69 | for element, total in scores_sum.items()]) 70 | 71 | # Sort in decreasing order based on the first column 72 | movie_ranking = movie_ranking[np.argsort(movie_ranking[:, 0])[::-1]] 73 | 74 | # Extract the recommended movies 75 | recommendies = [movie for _,movie in movie_ranking] 76 | 77 | return recommendies 78 | 79 | if __name__=='__main__': 80 | data_file = 'movie_rating.json' 81 | 82 | with open(data_file, 'r') as f: 83 | dataset = json.loads(f.read()) 84 | 85 | user = 'Steven Ferndndes' 86 | print "\nRecommendations for " + user + ":" 87 | movie = movie_recommendations(dataset, user) 88 | for i, movies in enumerate(movie): 89 | print str(i+1) + '. ' + movies 90 | 91 | user = 'Ramesh Nayak' 92 | print "\nRecommendations for " + user + ":" 93 | movie = movie_recommendations(dataset, user) 94 | for i, movies in enumerate(movie): 95 | print str(i+1) + '. ' + movies 96 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Packt 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Raspberry Pi 3 Cookbook for Python Programmers - Third Edition 2 | This is the code repository for [Raspberry Pi 3 Cookbook for Python Programmers - Third Edition](https://www.packtpub.com/hardware-and-creative/raspberry-pi-3-cookbook-python-programmers-third-edition?utm_source=github&utm_medium=repository&utm_campaign=9781788629874), published by [Packt](https://www.packtpub.com/?utm_source=github). It contains all the supporting project files necessary to work through the book from start to finish. 3 | ## About the Book 4 | Raspberry Pi 3 Cookbook for Python Programmers – Third Edition begins by guiding you through setting up Raspberry Pi 3, performing tasks using Python 3.6, and introducing the first steps to interface with electronics. As you work through each chapter, you will build your skills and apply them as you progress. You will learn how to build text classifiers, predict sentiments in words, develop applications using the popular Tkinter library, and create games by controlling graphics on your screen. You will harness the power of a built in graphics processor using Pi3D to generate your own high-quality 3D graphics and environments. 5 | 6 | You will understand how to connect Raspberry Pi’s hardware pins directly to control electronics, from switching on LEDs and responding to push buttons to driving motors and servos. Get to grips with monitoring sensors to gather real-life data, using it to control other devices, and viewing the results over the internet. You will apply what you have learned by creating your own Pi-Rover or Pi-Hexipod robots. You will also learn about sentiment analysis, face recognition techniques, and building neural network modules for optical character recognition. 7 | 8 | 9 | ## Instructions and Navigation 10 | All of the code is organized into folders. Each folder starts with a number followed by the application name. For example, Chapter02. 11 | 12 | All chapters contain code files 13 | 14 | The code will look like the following: 15 | ``` 16 | #!/usr/bin/python3 17 | # bouncingball.py 18 | import tkinter as TK 19 | import time 20 | VERT,HOREZ=0,1 21 | xTOP,yTOP = 0,1 22 | xBTM,yBTM = 2,3 23 | MAX_WIDTH,MAX_HEIGHT = 640,480 24 | xSTART,ySTART = 100,200 25 | BALL_SIZE=20 26 | RUNNING=True 27 | ``` 28 | 29 | Readers are expected to know the basics of Python programming. 30 | It would be beneficial for readers to have a basic understanding of machine learning, computer vision, and neural networks. 31 | 32 | ## Related Products 33 | * [Mastering Python Networking - Second Edition](https://www.packtpub.com/networking-and-servers/mastering-python-networking-second-edition?utm_source=github&utm_medium=repository&utm_campaign=9781789135992) 34 | 35 | * [Learn Python Programming - Fundamentals of Python - Second Edition](https://www.packtpub.com/application-development/learn-python-programming-fundamentals-python?utm_source=github&utm_medium=repository&utm_campaign=9781788996662) 36 | 37 | * [Python Artificial Intelligence Projects](https://www.packtpub.com/big-data-and-business-intelligence/python-artificial-intelligence-projects?utm_source=github&utm_medium=repository&utm_campaign=9781788996921) 38 | 39 | ### Suggestions and Feedback 40 | [Click here](https://docs.google.com/forms/d/e/1FAIpQLSe5qwunkGf6PUvzPirPDtuy1Du5Rlzew23UBp2S-P3wB-GcwQ/viewform) if you have any feedback or suggestions. 41 | --------------------------------------------------------------------------------