1.环境

pip install face_recognition
pip install opencv-python

2.代码

在当前目录下,创建一个文件夹known_faces,存放各种人脸

测试代码

import face_recognition 
import cv2
import os

def face(path):
    #存储知道人名列表
    known_names=[] 
    #存储知道的特征值
    known_encodings=[]
    for image_name in os.listdir(path):
        load_image = face_recognition.load_image_file(path+image_name) #加载图片
        image_face_encoding = face_recognition.face_encodings(load_image)[0] #获得128维特征值
        known_names.append(image_name.split(".")[0])
        known_encodings.append(image_face_encoding)
    print(known_encodings)
    
    #打开摄像头,0表示内置摄像头
    video_capture = cv2.VideoCapture(0) 
    process_this_frame = True
    while True:
        #ret, frame = video_capture.read()
        frame = cv2.imread("2.jpg")
        # opencv的图像是BGR格式的,而我们需要是的RGB格式的,因此需要进行一个转换。
        rgb_frame = frame.copy()
        if process_this_frame:
            face_locations = face_recognition.face_locations(rgb_frame)#获得所有人脸位置
            face_encodings = face_recognition.face_encodings(rgb_frame, face_locations) #获得人脸特征值
            face_names = [] #存储出现在画面中人脸的名字
            for face_encoding in face_encodings:         
                matches = face_recognition.compare_faces(known_encodings, face_encoding,tolerance=0.5)
                if True in matches:
                    first_match_index = matches.index(True)
                    name = known_names[first_match_index]
                else:
                    name="unknown"
                face_names.append(name)

        process_this_frame = not process_this_frame

        # 将捕捉到的人脸显示出来
        for (top, right, bottom, left), name in zip(face_locations, face_names):
            cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2) # 画人脸矩形框
            # 加上人名标签
            cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)
            font = cv2.FONT_HERSHEY_DUPLEX 
            cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)
        
        cv2.imshow('frame', frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    video_capture.release()
    cv2.destroyAllWindows()

if __name__=='__main__':
    face("known_faces/") #存放已知图像路径

PYTHON人脸识别_帧率

3.增加可信度

import face_recognition
import cv2
import numpy as np
import os
import time

known_faces_dir = "known_faces"
known_face_encodings = []
known_face_names = []

# 在循环开始前初始化变量
start_time = time.time()
frame_count = 0
fps = 0

for file in os.listdir(known_faces_dir):
    image = face_recognition.load_image_file(os.path.join(known_faces_dir, file))
    encoding = face_recognition.face_encodings(image)[0]
    known_face_encodings.append(encoding)
    known_face_names.append(os.path.splitext(file)[0])

video_capture = cv2.VideoCapture(0)

while True:
    #ret, frame = video_capture.read()
    frame = cv2.imread("7.jpeg")
    rgb_frame = frame.copy()

    face_locations = face_recognition.face_locations(rgb_frame)
    face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)

    for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
        matches = face_recognition.compare_faces(known_face_encodings, face_encoding)

        face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
        best_match_index = np.argmin(face_distances)
        name = "Unknown"
    
        if True in matches:
            name = known_face_names[best_match_index]
            confidence = 1 - face_distances[best_match_index]  # 计算可信度

            if confidence > 0.5:  # 只显示高于一定可信度的匹配
                cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
                cv2.putText(frame, f'{name} {confidence:.2f}', (left + 6, bottom - 6), cv2.FONT_HERSHEY_DUPLEX, 0.5, (255, 255, 255), 1)


    # 在循环中增加帧数计数
    frame_count += 1
    # 计算帧率
    if frame_count % 10 == 0:  # 每20帧计算一次帧率
        end_time = time.time()
        duration = end_time - start_time
        fps = frame_count / duration
        print("帧率: {:.2f}".format(fps))

    # 在界面上显示帧率
    cv2.putText(frame, "FPS: {:.2f}".format(fps), (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)

    cv2.imshow('Video', frame)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

video_capture.release()
cv2.destroyAllWindows()

PYTHON人脸识别_开发语言_02