要實現(xiàn)一個人臉識別系統(tǒng),可以使用 Python 的 OpenCV 和 face_recognition 模塊。下面是一個簡單的人臉識別系統(tǒng)實現(xiàn)的示例代碼:
import cv2
import face_recognition
# 加載已知人臉圖像和相應名稱
known_face_encodings = []
known_face_names = []
for i in range(1, 4):
image = face_recognition.load_image_file('known_faces/{}.jpg'.format(i))
face_encoding = face_recognition.face_encodings(image)[0]
known_face_encodings.append(face_encoding)
known_face_names.append('Person {}'.format(i))
# 打開攝像頭
cap = cv2.VideoCapture(0)
while True:
# 讀取攝像頭畫面
ret, frame = cap.read()
# 轉(zhuǎn)換畫面顏色格式
rgb_frame = frame[:, :, ::-1]
# 檢測當前畫面中的人臉
face_locations = face_recognition.face_locations(rgb_frame)
face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)
# 對檢測到的人臉進行識別
for face_encoding, face_location in zip(face_encodings, face_locations):
matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
# 如果找到了匹配的人臉,則在畫面上顯示名稱標簽
if True in matches:
match_index = matches.index(True)
name = known_face_names[match_index]
top, right, bottom, left = face_location
cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
cv2.putText(frame, name, (left + 6, bottom - 6), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 255), 1)
# 顯示畫面
cv2.imshow('frame', frame)
# 等待按鍵事件
key = cv2.waitKey(1)
if key == ord('q'):
break
# 關(guān)閉攝像頭
cap.release()
cv2.destroyAllWindows()
運行此程序?qū)蜷_電腦的攝像頭,并檢測當前畫面中的人臉,并將識別出的人臉名稱標簽添加到畫面上。你可以根據(jù)自己的需要使用 OpenCV 和 face_recognition 模塊中的其他函數(shù)和方法來實現(xiàn)更多的人臉識別系統(tǒng)功能。
未經(jīng)允許不得轉(zhuǎn)載:445IT之家 » 用python實現(xiàn)臉識別系統(tǒng) 超簡單