For your convenience, the code below is what we developed to allow training our face recognition model.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import face_recognition import cv2 import os import pickle print(cv2.__version__) Encodings=[] Names=[] j=0 image_dir='/home/pjm/Desktop/pyPro/demoimages/known' for root, dirs, files in os.walk(image_dir): print(files) for file in files: fullPath=os.path.join(root,file) print(fullPath) name=os.path.splitext(file)[0] print(name) person=face_recognition.load_image_file(fullPath) encoding=face_recognition.face_encodings(person)[0] Encodings.append(encoding) Names.append(name) print(Names) with open('train.pkl','wb') as f: pickle.dump(Names,f) pickle.dump(Encodings,f) |
Then this is a simple program that loads the trained model, and uses it to recognize people in unknown images.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import cv2 print(cv2.__version__) import face_recognition import pickle with open('train.pkl','rb') as f: Names=pickle.load(f) Encodings=pickle.load(f) font=cv2.FONT_HERSHEY_SIMPLEX testImage=face_recognition.load_image_file('/home/pjm/Desktop/pyPro/demoimages/unkno$ facePositions=face_recognition.face_locations(testImage) allEncodings=face_recognition.face_encodings(testImage,facePositions) testImage=cv2.cvtColor(testImage,cv2.COLOR_RGB2BGR) for (top,right,bottom,left), face_encoding in zip(facePositions, allEncodings): name='Unknown Life Form' matches=face_recognition.compare_faces(Encodings,face_encoding) if True in matches: first_match_index=matches.index(True) name=Names[first_match_index] cv2.rectangle(testImage,(left,top),(right,bottom),(255,0,0),2) cv2.rectangle(testImage, (left,top),(left+200, top+30),(0,255,255),-1) cv2.putText(testImage,name,(left,top+20),font,.75,(255,0,0),2) cv2.imshow('mywindow',testImage) cv2.moveWindow('mywindow',0,0) if cv2.waitKey(0)==ord('q'): cv2.destroyAllWindows() |