實現(xiàn)人臉識別的python庫有很多,這里以OpenCV和face_recognition為例,具體實現(xiàn)步驟如下:
1. 安裝OpenCV和face_recognition庫
pip install opencv-python
pip install face_recognition
2. 獲取人臉圖像并存儲
import cv2
# 打開攝像頭
cap = cv2.VideoCapture(0)
while True:
# 讀取一幀圖像
ret, frame = cap.read()
# 顯示圖像
cv2.imshow('video', frame)
# 按下q鍵退出
if cv2.waitKey(1) & 0xff == ord('q'):
break
# 釋放攝像頭資源
cap.release()
cv2.destroyAllWindows()
3. 對圖像進行人臉檢測
import face_recognition
# 將圖像轉為RGB格式
rgb_frame = frame[:, :, ::-1]
# 檢測人臉位置
face_locations = face_recognition.face_locations(rgb_frame)
4. 對每個人臉進行識別
# 加載預先訓練好的人臉數(shù)據(jù)
known_image = face_recognition.load_image_file("known_face.jpg")
known_encoding = face_recognition.face_encodings(known_image)[0]
# 對檢測到的每個人臉進行識別
for face_location in face_locations:
# 提取人臉編碼
unknown_encoding = face_recognition.face_encodings(rgb_frame, [face_location])[0]
# 比對人臉
results = face_recognition.compare_faces([known_encoding], unknown_encoding)
if results[0]:
# 識別成功
print("This is known_face.")
else:
# 識別失敗
print("Unknown face.")
完整代碼如下:
import cv2
import face_recognition
# 加載預先訓練好的人臉數(shù)據(jù)
known_image = face_recognition.load_image_file("known_face.jpg")
known_encoding = face_recognition.face_encodings(known_image)[0]
# 打開攝像頭
cap = cv2.VideoCapture(0)
while True:
# 讀取一幀圖像
ret, frame = cap.read()
# 將圖像轉為RGB格式
rgb_frame = frame[:, :, ::-1]
# 檢測人臉位置
face_locations = face_recognition.face_locations(rgb_frame)
# 對每個人臉進行識別
for face_location in face_locations:
# 提取人臉編碼
unknown_encoding = face_recognition.face_encodings(rgb_frame, [face_location])[0]
# 比對人臉
results = face_recognition.compare_faces([known_encoding], unknown_encoding)
if results[0]:
# 識別成功
cv2.rectangle(frame, (face_location[3], face_location[0]), (face_location[1], face_location[2]), (0, 255, 0), 2)
cv2.putText(frame, "Known Face", (face_location[3], face_location[2] + 20), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
else:
# 識別失敗
cv2.rectangle(frame, (face_location[3], face_location[0]), (face_location[1], face_location[2]), (0, 0, 255), 2)
cv2.putText(frame, "Unknown Face", (face_location[3], face_location[2] + 20), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)
# 顯示圖像
cv2.imshow('video', frame)
# 按下q鍵退出
if cv2.waitKey(1) & 0xff == ord('q'):
break
# 釋放攝像頭資源
cap.release()
cv2.destroyAllWindows()