基于face_recognition库的人脸识别、对比实现

github

介绍

本项目是世界上最简洁的人脸识别库,你可以使用Python和命令行工具提取、识别、操作人脸。

本项目的人脸识别是基于业内领先的C++开源库 dlib中的深度学习模型,用Labeled Faces in the Wild人脸数据集进行测试,有高达99.38%的准确率。但对小孩和亚洲人脸的识别准确率尚待提升。

Labeled Faces in the Wild是美国麻省大学安姆斯特分校(University of Massachusetts Amherst)制作的人脸数据集,该数据集包含了从网络收集的13,000多张面部图像。

本项目提供了简易的face_recognition命令行工具,你可以用它处理整个文件夹里的图片。

实现

#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
@File    :   main.py
@Time    :   2023/09/25 15:30:22
@Author  :   Carry
@Version :   1.0
@Desc    :   人脸识别、人脸比对
'''

import time
import cv2
import sys
import face_recognition
import gradio as gr


def draw_face_rectangles(image, locations):
    """
    # 定义一个函数来绘制人脸区域
    """
    for location in locations:
        top, right, bottom, left = location
        cv2.rectangle(image, (left, top), (right, bottom), (0, 255, 0), 2)


def find_largest_face(face_locations):
    """
    # 找到每张图片中最大的人脸
    """
    if not face_locations:
        return None
    largest_face = face_locations[0]
    largest_area = (largest_face[2] - largest_face[0]) * (largest_face[1] - largest_face[3])
    for face_location in face_locations:
        area = (face_location[2] - face_location[0]) * (face_location[1] - face_location[3])
        if area > largest_area:
            largest_area = area
            largest_face = face_location
    return largest_face


def is_same_person(image1, image2, local=False, save_img=False):
    """
    # 判断两张图片中的人脸是否是同一个人
    """
    if local:
        # 加载两张图片
        image1 = face_recognition.load_image_file(image1)
        image2 = face_recognition.load_image_file(image2)

    # 在每张图片中找到所有人脸的面部位置
    t1 = time.time()
    face_locations1 = face_recognition.face_locations(image1)
    face_locations2 = face_recognition.face_locations(image2)
    t2 = time.time()
    print("face location time:", t2-t1)

    if save_img:
        # 绘制人脸区域并保存图像
        image1_with_faces = image1.copy()
        draw_face_rectangles(image1_with_faces, face_locations1)
        cv2.imwrite("image1_with_faces.jpg", image1_with_faces)

        image2_with_faces = image2.copy()
        draw_face_rectangles(image2_with_faces, face_locations2)
        cv2.imwrite("image2_with_faces.jpg", image2_with_faces)

    # 找到每张图片中最大的人脸
    largest_face1 = find_largest_face(face_locations1)
    largest_face2 = find_largest_face(face_locations2)
    print(f"largest face1: {largest_face1}")
    print(f"largest face2: {largest_face2}")

    if largest_face1 is None or largest_face2 is None:
        return "未能找到图片中的人脸"
    else:
        # 提取人脸特征
        t1 = time.time()
        face_encodings1 = face_recognition.face_encodings(image1, [largest_face1], num_jitters=1, model="large")[0]
        face_encodings2 = face_recognition.face_encodings(image2, [largest_face2], num_jitters=1, model="large")[0]
        t2 = time.time()
        print("face encoding time:", t2-t1)

        face_distances = face_recognition.face_distance([face_encodings1], face_encodings2)
        print(f"face distance: {face_distances}")

        results = face_recognition.compare_faces([face_encodings1], face_encodings2, tolerance=0.4)
        print(f"compare faces: {results}")

        if results[0]:
            return f"这两张图片中的人脸是同一个人。score(越趋近0越相似,当前阈值0.4):{face_distances[0]}"
        else:
            return f"这两张图片中的人脸不是同一个人。score(越趋近0越相似,当前阈值0.4):{face_distances[0]}"


# 接收命令行输入的图片路径
# pic_1 = sys.argv[1]
# pic_2 = sys.argv[2]
# t1 = time.time()
# is_same_person(pic_1, pic_2, local=True)
# t2 = time.time()
# print("total time:", t2-t1)

# 创建 Gradio 交互式界面
iface = gr.Interface(fn=is_same_person, inputs=["image", "image"], outputs="text")
iface.launch(server_name="0.0.0.0")

运行

python main.py
http://localhost:7861/
在这里插入图片描述

好的,下面是一个简单的基于face_recognition人脸识别方案代码示例: ```python import face_recognition import cv2 # 加载已知人脸的图像和名称 known_face_encodings = [] known_face_names = [] image1 = face_recognition.load_image_file("person1.jpg") image2 = face_recognition.load_image_file("person2.jpg") image3 = face_recognition.load_image_file("person3.jpg") known_face_encodings.append(face_recognition.face_encodings(image1)[0]) known_face_encodings.append(face_recognition.face_encodings(image2)[0]) known_face_encodings.append(face_recognition.face_encodings(image3)[0]) known_face_names = ["person1", "person2", "person3"] # 打开摄像头 cap = cv2.VideoCapture(0) while True: # 读取一帧图像 ret, frame = cap.read() # 将图像转换为RGB格式 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] else: name = "unknown" # 绘制人脸矩形框和名称 top, right, bottom, left = face_location cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2) cv2.putText(frame, name, (left, top-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) # 显示图像 cv2.imshow('Face Recognition', frame) # 按下q键退出 if cv2.waitKey(1) & 0xFF == ord('q'): break # 释放摄像头和窗口 cap.release() cv2.destroyAllWindows() ``` 在这个代码示例中,我们使用face_recognition加载了已知人脸的图像和名称,并使用cv2.VideoCapture()方法打开了摄像头。在每一帧图像中,我们使用face_recognition检测人脸,并使用face_recognition.compare_faces()方法尝试匹配人脸。如果有匹配到的人脸,则取出其名称,并使用cv2.rectangle()和cv2.putText()方法绘制人脸矩形框和名称。最后,我们使用cv2.imshow()方法显示图像,并使用cv2.waitKey()方法等待用户按下q键退出程序。 值得注意的是,face_recognition是一个基于dlib人脸识别,其检测速度较慢,但是识别精度较高。在实际应用中,我们需要根据具体情况选择不同的人脸识别方法以达到更好的效果。 希望这个代码对您有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值