face_recognition實現簡單的人臉識別
分別實現從圖片,視頻和攝像頭中進行人臉識別,並對人臉區域進行標注。
三種方式的實現方法本質上是一樣的,區別只在於對opencv的調用上存在一點區別。
下面以圖片中識別人臉的代碼為例:
#實現從圖片中進行人臉識別
#導入face_recognition 和 cv2 庫
import face_recognition
import cv2
import numpy as np
#讀入圖片
frame = cv2.imread('D:/test/3face.jpg')
#進行圖片縮放,這個十分重要,影響到識別是正確率和速度
#大圖片進行適當的縮小能明顯提高識別速度(在攝像頭和視頻識別中非常有效)(指數型)
#小圖片進行適當放大之后,可以明顯提高識別成功率
frame = cv2.resize(frame,(0,0),fx=0.25,fy=0.25)
#cv2的圖片排列方式為BGR,需要先轉變為RGB模式,face_recognition庫才能正常運行
rgb_frame = cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)
#執行face_locations,識別出圖片中人臉的位置(左上點,右下點)
face_locations = face_recognition.face_locations(rgb_frame)
for face_location in face_locations:
top = face_location[0]
right = face_location[1]
bottom = face_location[2]
left = face_location[3]
#畫出矩形框
cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
cv2.imshow('img', frame)
cv2.imwrite('3faceout.jpg', frame)
cv2.waitKey(0)
cv2.destroyAllWindows()
原圖片如下:
效果圖如下:
單人臉識別:
多人臉識別:
其他詳細代碼(視頻,攝像頭)和效果展示請見:https://github.com/1647790440/deeplearning/tree/master/face_recognition