← 返回首页
OpenCV+Dlib+Gradio的人脸对比系统
发表时间:2024-09-05 15:46:04
OpenCV+Dlib+Gradio的人脸对比系统

1.安装依赖

pip install opencv-python -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install numpy -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install cmake -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install dlib -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install face_recognition -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install gradio -i https://pypi.tuna.tsinghua.edu.cn/simple

2.程序实现

import cv2
import numpy as np
import face_recognition
import os
from datetime import datetime
import gradio as gr
from PIL import Image, ImageDraw, ImageFont
def face_compare(src,dest):
    imgSrc = cv2.cvtColor(src, cv2.COLOR_BGR2RGB)  # 将BGR彩色图像转化为RGB彩色图像
    imgDest = cv2.cvtColor(dest, cv2.COLOR_BGR2RGB)

    faceLoc = face_recognition.face_locations(imgSrc)[0]  # 定位人脸位置
    encodeSrc = face_recognition.face_encodings(imgSrc)[0]  # 提取人脸的面部特征
    cv2.rectangle(imgSrc, (faceLoc[3], faceLoc[0]), (faceLoc[1], faceLoc[2]), (255, 0, 255), 2)  # 框出人脸

    # print(faceLoc)
    faceLocDest = face_recognition.face_locations(imgDest)[0]
    encodeDest = face_recognition.face_encodings(imgDest)[0]
    cv2.rectangle(imgDest, (faceLocDest[3], faceLocDest[0]), (faceLocDest[1], faceLocDest[2]), (255, 0, 255), 2)

    result = face_recognition.compare_faces([encodeSrc], encodeDest)  # 比较人脸编码的相似度
    faceDis = face_recognition.face_distance([encodeSrc], encodeDest)  # 计算两个人脸的欧氏距离(欧氏距离用于计算样本之间的相似度或距离)
    print(result, faceDis)
    cv2.putText(imgDest, f'{result}{round(faceDis[0], 2)}', (50, 50), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 255),
                2)  # 显示比对结果
    src_filename = "detected/src_image.png"
    dest_filename = "detected/dest_image.png"
    cv2.imwrite(src_filename, imgSrc)
    cv2.imwrite(dest_filename,imgDest)
    result_text ='是同一个人' if result[0] else '不是同一个人'
    print(result[0])
    print(type(result))

    return src_filename,dest_filename,result_text



facecomp = gr.Interface(
    fn = face_compare,
    title='face_recognition的人脸对比系统',
    inputs = [gr.Image(label='源图片'),gr.Image(label='目标图片')],
    outputs = [gr.Image(show_label=False),gr.Image(show_label=False),gr.Text(label='人脸对比结果')]
)

if __name__ == "__main__":
    facecomp.launch()

运行效果: