最近在發現一個很好的Face Service的API 介面 face_recognition可以很方便的用python實現一個即時監控人臉的程式。
先介紹一下這個API介面。這是一個可以通過python或者命令列即可實現Face Service的功能的Face Service的庫。
安裝配置,在我電腦上面安裝比較容易,我直接使用了代碼
pip install face_recognition
我python版本是3.6,在win10 64 位元系統下使用了anaconda 安裝的。
安裝好了以後顯示如下
這樣表明你已經安裝好了。
下面我們開始寫相關程式
import face_recognitionimport cv2image = face_recognition.load_image_file("face2.jpg")face_locations = face_recognition.face_locations(image)facenum = len(face_locations)for i in range(0, facenum): top = face_locations[i][0] right = face_locations[i][1] bottom = face_locations[i][2] left = face_locations[i][3] start = (left, top) end = (right, bottom) color = (0, 0, 255) thickness = 2 cv2.rectangle(img, start, end, color, thickness)cv2.namedWindow(u"識別")cv2.imshow(u"識別", img)cv2.waitKey(0)cv2.destroyAllWindows()
這裡就在網上隨便找了一副圖片,大家將就的看一下。當然這裡顯示我使用了opencv.大家還需要安裝一下opencv.也很簡單就一句代碼的事。
大家也許發現了上面的中文顯示出現了亂碼。這裡我也暫時沒解決。如果有解決的大家跟我說一下。
下面就調用網路攝影機即時識別人臉了。
import face_recognitionimport cv2video_capture = cv2.VideoCapture(0)obama_img = face_recognition.load_image_file("obama.jpg")obama_face_encoding = face_recognition.face_encodings(obama_img)[0]face_locations = []face_encodings = []face_names = []process_this_frame = Truewhile True: ret, frame = video_capture.read() 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([obama_face_encoding], face_encoding) if match[0]: name = "Barack" else: name = "unknown" 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'): breakvideo_capture.release()cv2.destroyAllWindows()
這裡要說明一下這裡是在一開始就定義了奧巴馬的圖片在程式中的。然後再調用網路攝影機進行檢測和識別的。整體看效果還不錯。
當然你也可以預先把自己的照片放上去,然後就可以即時把自己識別出來了。