用已經搭建好 face_recognition,dlib 環境來進行人臉識別 未搭建好環境請參考:https://www.cnblogs.com/guihua-pingting/p/12201077.html 使用OpenCV 調用攝像頭 import face_recognition import ...
用已經搭建好
import face_recognition import cv2 video_capture = cv2.VideoCapture(0) # VideoCapture打開攝像頭,0為筆記本內置攝像頭,1為外USB攝像頭,或寫入視頻路徑 mayun_img = face_recognition.load_image_file("mayun.jpg") jobs_img = face_recognition.load_image_file("jobs.jpg") mayun_face_encoding = face_recognition.face_encodings(mayun_img)[0] jobs_face_encoding = face_recognition.face_encodings(jobs_img)[0] face_locations = [] face_encodings = [] face_names = [] process_this_frame = True while True: ret, frame = video_capture.read() # video_capture.read()按幀讀取視頻,ret,frame是獲video_capture.read()方法的兩個返回值。 # 其中ret是布爾值,如果讀取幀是正確的則返回True, # 如果文件讀取到結尾,它的返回值就為False。frame就是每一幀的圖像,是個三維矩陣。 small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25) # 對截取到的圖像進行處理 if process_this_frame: face_locations = face_recognition.face_locations(small_frame) face_encodings = face_recognition.face_encodings(small_frame, face_locations) face_names = [] for face_encoding in face_encodings: match = face_recognition.compare_faces([mayun_face_encoding, jobs_face_encoding], face_encoding) if match[0]: name = "mayun" elif match[1]: name = "jobs" else: name = "unknown" print(name) face_names.append(name) process_this_frame = not process_this_frame for (top, right, bottom, left), name in zip(face_locations, face_names): top *= 4 right *= 4 bottom *= 4 left *= 4 cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2) cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), 2) font = cv2.FONT_HERSHEY_DUPLEX cv2.putText(frame, name, (left+6, bottom-6), font, 1.0, (255, 255, 255), 1) cv2.imshow('Video', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break video_capture.release() cv2.destroyAllWindows()
我使用手機中的照片來進行驗證
因為是按每一幀進行讀取:
有些人在使用時會出現攝像頭打不開的情況
我使用的是win10系統給出一個建議:
在設置中找到隱私設置,在找到相機選項,把許可權打開即可