|
pip install opencv-python face_recognition
import cv2
import face_recognition
import os
# 載入已知人臉圖片並編碼
known_face_encodings = []
known_face_names = []
# 指定已知人臉資料夾
known_faces_dir = "known_faces"
for filename in os.listdir(known_faces_dir):
if filename.endswith(".jpg") or filename.endswith(".png"):
img_path = os.path.join(known_faces_dir, filename)
image = face_recognition.load_image_file(img_path)
encodings = face_recognition.face_encodings(image)
if encodings:
known_face_encodings.append(encodings[0])
known_face_names.append(os.path.splitext(filename)[0]) # 使用檔名當作人名
# 開啟攝影機
video_capture = cv2.VideoCapture(0)
while True:
ret, frame = video_capture.read()
if not ret:
break
# 調整圖片尺寸以加快處理速度
small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
rgb_small_frame = small_frame[:, :, ::-1] # BGR 轉 RGB
# 偵測當前影像中的所有人臉
face_locations = face_recognition.face_locations(rgb_small_frame)
face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)
face_names = []
for face_encoding in face_encodings:
matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
name = "Unknown"
# 使用距離來找到最接近的人臉
face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
if face_distances.size > 0:
best_match_index = face_distances.argmin()
if matches[best_match_index]:
name = known_face_names[best_match_index]
face_names.append(name)
# 顯示結果
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, 255, 0), 2)
cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 255, 0), cv2.FILLED)
cv2.putText(frame, name, (left + 6, bottom - 6),
cv2.FONT_HERSHEY_DUPLEX, 1.0, (0, 0, 0), 1)
cv2.imshow('Face Recognition', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 釋放資源
video_capture.release()
cv2.destroyAllWindows()
|
|