要實(shí)現(xiàn)一個(gè)人臉識(shí)別系統(tǒng),可以使用 Python 的 OpenCV 和 face_recognition 模塊。下面是一個(gè)簡(jiǎn)單的人臉識(shí)別系統(tǒng)實(shí)現(xiàn)的示例代碼:
import cv2
import face_recognition
# 加載已知人臉圖像和相應(yīng)名稱
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))
# 打開(kāi)攝像頭
cap = cv2.VideoCapture(0)
while True:
# 讀取攝像頭畫(huà)面
ret, frame = cap.read()
# 轉(zhuǎn)換畫(huà)面顏色格式
rgb_frame = frame[:, :, ::-1]
# 檢測(cè)當(dāng)前畫(huà)面中的人臉
face_locations = face_recognition.face_locations(rgb_frame)
face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)
# 對(duì)檢測(cè)到的人臉進(jìn)行識(shí)別
for face_encoding, face_location in zip(face_encodings, face_locations):
matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
# 如果找到了匹配的人臉,則在畫(huà)面上顯示名稱標(biāo)簽
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)
# 顯示畫(huà)面
cv2.imshow('frame', frame)
# 等待按鍵事件
key = cv2.waitKey(1)
if key == ord('q'):
break
# 關(guān)閉攝像頭
cap.release()
cv2.destroyAllWindows()
運(yùn)行此程序?qū)?huì)打開(kāi)電腦的攝像頭,并檢測(cè)當(dāng)前畫(huà)面中的人臉,并將識(shí)別出的人臉名稱標(biāo)簽添加到畫(huà)面上。你可以根據(jù)自己的需要使用 OpenCV 和 face_recognition 模塊中的其他函數(shù)和方法來(lái)實(shí)現(xiàn)更多的人臉識(shí)別系統(tǒng)功能。
未經(jīng)允許不得轉(zhuǎn)載:445IT之家 » 用python實(shí)現(xiàn)臉識(shí)別系統(tǒng) 超簡(jiǎn)單