施勢帆老師的教學網站

 找回密碼
 立即註冊
搜索
熱搜: 活動 交友 discuz
查看: 55|回復: 0

寫OpenCV 辨識不同人臉的python程式 II

[複製鏈接]

706

主題

717

帖子

3406

積分

管理員

Rank: 9Rank: 9Rank: 9

積分
3406
發表於 2025-4-10 16:25:18 | 顯示全部樓層 |閱讀模式
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()



回復

使用道具 舉報

您需要登錄後才可以回帖 登錄 | 立即註冊

本版積分規則

Archiver|手機版|小黑屋|施勢帆老師的教學網站

GMT+8, 2025-4-19 08:39 , Processed in 0.045541 second(s), 19 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回復 返回頂部 返回列表