人脸匹配——OpenCV

人脸匹配

    • 导入所需的库
    • 加载dlib的人脸识别模型和面部检测器
    • 读取图片并转换为灰度图
    • 比较两张人脸
    • 选择图片并显示结果
    • 比较图片
    • 创建GUI界面
    • 运行GUI主循环
    • 运行显示
    • 全部代码

导入所需的库

cv2:OpenCV库,用于图像处理。
dlib:一个机器学习库,用于人脸检测和特征点预测。
numpy:用于数值计算的库。
PILImageTk:用于处理图像和创建Tkinter兼容的图像对象。
filedialog:Tkinter的一个模块,用于打开文件对话框。
TkLabelButtonCanvas:Tkinter库的组件,用于创建GUI。

import cv2
import dlib
import numpy as np
from PIL import Image, ImageTk
from tkinter import filedialog
from tkinter import Tk, Label, Button, Canvas

加载dlib的人脸识别模型和面部检测器

使用dlib.get_frontal_face_detector()加载面部检测器。
使用dlib.shape_predictor()加载面部特征点预测模型。
使用dlib.face_recognition_model_v1()加载人脸识别模型。

detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
face_rec = dlib.face_recognition_model_v1("dlib_face_recognition_resnet_model_v1.dat")

读取图片并转换为灰度图

读取图片并转换为灰度图。
使用面部检测器检测图像中的面部。
如果检测到多张或没有脸,则抛出异常。
提取面部特征点并计算人脸编码。

def get_face_encoding(image_path):
    img = cv2.imread(image_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = detector(gray)
    if len(faces) != 1:
        raise ValueError("图片中检测到多张或没有脸")
    face = faces[0]
    shape = predictor(gray, face)
    face_encoding = np.array(face_rec.compute_face_descriptor(img, shape))
    return face_encoding

比较两张人脸

比较两个人脸编码。
计算两个编码之间的欧氏距离。
如果距离小于0.6,则认为它们是同一个人脸。

def compare_faces(face1, face2):
    distance = np.linalg.norm(face1 - face2)
    if distance < 0.6:
        return "相同人脸"
    else:
        return "不同人脸"

选择图片并显示结果

定义select_image1、select_image2和select_image3函数。
打开文件对话框让用户选择图片。
将选择的图片显示在相应的画布上。

def select_image1():
    global image1_path, image1
    image1_path = filedialog.askopenfilename()
    image1 = Image.open(image1_path)
    image1 = image1.resize((300, 300), Image.LANCZOS)  # 使用Image.LANCZOS替换ANTIALIAS
    photo1 = ImageTk.PhotoImage(image1)
    canvas1.create_image(0, 0, anchor='nw', image=photo1)
    canvas1.image = photo1


def select_image2():
    global image2_path, image2
    image2_path = filedialog.askopenfilename()
    image2 = Image.open(image2_path)
    image2 = image2.resize((300, 300), Image.LANCZOS)  # 使用Image.LANCZOS替换ANTIALIAS
    photo2 = ImageTk.PhotoImage(image2)
    canvas2.create_image(0, 0, anchor='nw', image=photo2)
    canvas2.image = photo2


def select_image3():
    global image3_path, image3
    image3_path = filedialog.askopenfilename()
    image3 = Image.open(image3_path)
    image3 = image3.resize((300, 300), Image.LANCZOS)  # 使用Image.LANCZOS替换ANTIALIAS
    photo3 = ImageTk.PhotoImage(image3)
    canvas3.create_image(0, 0, anchor='nw', image=photo3)
    canvas3.image = photo3

比较图片

定义compare_images1和compare_images2函数:
获取两个人脸编码并进行对比。
显示对比结果。

def compare_images1():
    try:
        face1 = get_face_encoding(image1_path)
        face2 = get_face_encoding(image2_path)
        result1 = compare_faces(face1, face2)
        result_label1.config(text=result1)
    except Exception as e:
        result_label1.config(text="发生错误: " + str(e))

def compare_images2():
    try:
        face2 = get_face_encoding(image2_path)
        face3 = get_face_encoding(image3_path)
        result2 = compare_faces(face2, face3)
        result_label2.config(text=result2)
    except Exception as e:
        result_label2.config(text="发生错误: " + str(e))

创建GUI界面

设置窗口标题和大小。
创建画布来显示图片。
创建标签来显示对比结果。
创建按钮让用户选择图片和进行对比。

# 创建GUI
root = Tk()
root.title("人脸对比")
root.geometry("1000x620")

# 创建画布来显示图片
canvas1 = Canvas(root, width=300, height=300, bg='white')
canvas1.pack(side='left', padx=10, pady=10)
canvas2 = Canvas(root, width=300, height=300, bg='white')
canvas2.pack(side='left', padx=10, pady=10)
canvas3 = Canvas(root, width=300, height=300, bg='white')
canvas3.pack(side='left', padx=10, pady=10)

# 创建标签来显示结果
result_label1 = Label(root, text="")
result_label1.place(x=300, y=120)
result_label2 = Label(root, text="")
result_label2.place(x=640, y=120)

# 创建按钮来选择图片
button1 = Button(root, text="选择第一张图片", command=select_image1)
button1.place(x=100, y=50)
button2 = Button(root, text="选择第二张图片", command=select_image2)
button2.place(x=450, y=50)
button3 = Button(root, text="选择第三张图片", command=select_image3)
button3.place(x=800, y=50)

# 创建按钮来对比图片
compare_button1 = Button(root, text="对比图像12", command=compare_images1)
compare_button1.place(x=300, y=80)
compare_button2 = Button(root, text="对比图像23", command=compare_images2)
compare_button2.place(x=640, y=80)

运行GUI主循环

root.mainloop()

运行显示

在这里插入图片描述

全部代码

import cv2
import dlib
import numpy as np
from PIL import Image, ImageTk
from tkinter import filedialog
from tkinter import Tk, Label, Button, Canvas

# 加载dlib的人脸识别模型和面部检测器
#使用dlib.get_frontal_face_detector()加载面部检测器,
# 使用dlib.shape_predictor()加载面部特征点预测模型,
# 使用dlib.face_recognition_model_v1()加载人脸识别模型
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
face_rec = dlib.face_recognition_model_v1("dlib_face_recognition_resnet_model_v1.dat")

# 读取图片并转换为灰度图
def get_face_encoding(image_path):
    img = cv2.imread(image_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = detector(gray)
    if len(faces) != 1:
        raise ValueError("图片中检测到多张或没有脸")
    face = faces[0]
    shape = predictor(gray, face)
    face_encoding = np.array(face_rec.compute_face_descriptor(img, shape))
    return face_encoding

# 比较两张人脸
def compare_faces(face1, face2):
    distance = np.linalg.norm(face1 - face2)
    if distance < 0.6:
        return "相同人脸"
    else:
        return "不同人脸"

# 选择图片并显示结果
def select_image1():
    global image1_path, image1
    image1_path = filedialog.askopenfilename()
    image1 = Image.open(image1_path)
    image1 = image1.resize((300, 300), Image.LANCZOS)  # 使用Image.LANCZOS替换ANTIALIAS
    photo1 = ImageTk.PhotoImage(image1)
    canvas1.create_image(0, 0, anchor='nw', image=photo1)
    canvas1.image = photo1


def select_image2():
    global image2_path, image2
    image2_path = filedialog.askopenfilename()
    image2 = Image.open(image2_path)
    image2 = image2.resize((300, 300), Image.LANCZOS)  # 使用Image.LANCZOS替换ANTIALIAS
    photo2 = ImageTk.PhotoImage(image2)
    canvas2.create_image(0, 0, anchor='nw', image=photo2)
    canvas2.image = photo2


def select_image3():
    global image3_path, image3
    image3_path = filedialog.askopenfilename()
    image3 = Image.open(image3_path)
    image3 = image3.resize((300, 300), Image.LANCZOS)  # 使用Image.LANCZOS替换ANTIALIAS
    photo3 = ImageTk.PhotoImage(image3)
    canvas3.create_image(0, 0, anchor='nw', image=photo3)
    canvas3.image = photo3


def compare_images1():
    try:
        face1 = get_face_encoding(image1_path)
        face2 = get_face_encoding(image2_path)
        result1 = compare_faces(face1, face2)
        result_label1.config(text=result1)
    except Exception as e:
        result_label1.config(text="发生错误: " + str(e))

def compare_images2():
    try:
        face2 = get_face_encoding(image2_path)
        face3 = get_face_encoding(image3_path)
        result2 = compare_faces(face2, face3)
        result_label2.config(text=result2)
    except Exception as e:
        result_label2.config(text="发生错误: " + str(e))

# 创建GUI
root = Tk()
root.title("人脸对比")
root.geometry("1000x620")

# 创建画布来显示图片
canvas1 = Canvas(root, width=300, height=300, bg='white')
canvas1.pack(side='left', padx=10, pady=10)
canvas2 = Canvas(root, width=300, height=300, bg='white')
canvas2.pack(side='left', padx=10, pady=10)
canvas3 = Canvas(root, width=300, height=300, bg='white')
canvas3.pack(side='left', padx=10, pady=10)

# 创建标签来显示结果
result_label1 = Label(root, text="")
result_label1.place(x=300, y=120)
result_label2 = Label(root, text="")
result_label2.place(x=640, y=120)

# 创建按钮来选择图片
button1 = Button(root, text="选择第一张图片", command=select_image1)
button1.place(x=100, y=50)
button2 = Button(root, text="选择第二张图片", command=select_image2)
button2.place(x=450, y=50)
button3 = Button(root, text="选择第三张图片", command=select_image3)
button3.place(x=800, y=50)

# 创建按钮来对比图片
compare_button1 = Button(root, text="对比图像12", command=compare_images1)
compare_button1.place(x=300, y=80)
compare_button2 = Button(root, text="对比图像23", command=compare_images2)
compare_button2.place(x=640, y=80)

root.mainloop()


本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/705562.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

用Python绘制yolo训练结果比较图-论文需要

代码内容来自于网络用博客记录 利用训练生成的result.csv中数据&#xff0c;形成多模型的比较图。 代码中演示的是map50、map50-95、losss的比较图 import matplotlib.pyplot as plt import pandas as pd import numpy as npif __name__ __main__:# 列出待获取数据内容的…

webstorm自定义vue模板

<!--* Description: ${COMPONENT_NAME} 页面* Author: * Date: ${DATE} --> <template><div>${COMPONENT_NAME} </div> </template><script> export default {name: "${COMPONENT_NAME}",components: {},data() {return {};},co…

【数据结构】单链表(C语言)

在数据结构和算法中&#xff0c;链表是一种常见的数据结构&#xff0c;它由一系列节点组成&#xff0c;每个节点包含数据和指向下一个节点的指针。在C语言中&#xff0c;我们可以使用指针来实现单向链表。下面将详细讲述如何利用C语言实现单向链表。 1.单链表的概念和结构 概…

Yolo-World训练过程中使用wandb进行可视化

训练过程可视化有两种方式&#xff1a;wandb和tensorboard&#xff0c;这里我采用的是wandb&#xff0c;想要在训练过程中调用wandb只需要在要训练的配置文件&#xff08;如yolo_world_v2_l_vlpan_bn_sgd_1e-3_40e_8gpus_finetune_coco.py&#xff09;中加上一行代码即可&#…

美业门店管理系统Java源码分享-【库存管理】的功能和作用

美业收银系统在美容行业中的作用和重要性体现在提高管理效率、提升客户满意度、降低成本、促进业务增长等方面。它为连锁美业提供了一个全面的管理工具&#xff0c;能够更好地应对市场挑战&#xff0c;提升竞争力。 美业系统中的【库存管理】在整个美容行业中起着非常重要的作…

【机器学习】以DIFY为例分享一种使用dockerhub镜像的方法

目录 一、引言 二、Dify在dockerhub被禁用后&#xff0c;如何部署、升级 2.1 网络及硬件条件 2.2 docker部署、升级方案 三、总结 一、引言 关于dify&#xff0c;之前力推过&#xff0c;大家可以跳转 AI智能体研发之路-工程篇&#xff08;二&#xff09;&#xff1a;Dify…

LayUI使用(二)处理表格会出现下拉框的问题

一、问题描述 如下&#xff0c;layui的表格渲染后&#xff0c;当鼠标悬停在表格项时会出现右侧的下拉框&#xff0c;layui版本较老&#xff0c;原因未知 二、处理办法 在cols里面加上width&#xff0c;也不用每个都加&#xff0c;加一部分表格项即可 注意&#xff1a;若想禁止…

18. 四数之和 - 力扣

1. 题目 给你一个由 n 个整数组成的数组 nums &#xff0c;和一个目标值 target 。请你找出并返回满足下述全部条件且不重复的四元组 [nums[a], nums[b], nums[c], nums[d]] &#xff08;若两个四元组元素一一对应&#xff0c;则认为两个四元组重复&#xff09;&#xff1a; 0 …

# RocketMQ 实战:模拟电商网站场景综合案例(十一)

RocketMQ 实战&#xff1a;模拟电商网站场景综合案例&#xff08;十一&#xff09; 一、RocketMQ 实战&#xff1a;模拟电商网站场景综合案例-- web 端项目开发 1、在 shop-order-web 工程模块中&#xff0c;创建 Controller 类 OrderControllre.java /*** shop\shop-order…

ABB光纤控制单元NDBU-95 64008366D

ABB光纤控制单元NDBU-95 64008366D 控制单元&#xff08;Control Unit&#xff09;负责程序的流程管理。正如工厂的物流分配部门&#xff0c;控制单元是整个CPU的指挥控制中心&#xff0c;由指令寄存器IR(Instruction Register)、指令译码器ID(Instruction Decoder)和操作控制…

easyexcel的简单使用(execl模板导出)

模板支持功能点 支持列表支持自定义头名称支持自定义fileName支持汇总 模板示例 操作 pom引入 <dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>${easyexcel.version}</version></dep…

【Python】教你彻底了解Python中的数据科学与机器学习

​​​​ 文章目录 一、数据科学的基本概念1. 数据收集2. 数据清洗3. 数据分析4. 数据可视化5. 机器学习 二、常用的数据科学库1. Pandas1.1 创建Series和DataFrame1.2 数据操作 2. NumPy2.1 创建数组2.2 数组操作 3. Scikit-learn3.1 数据预处理3.2 特征工程 三、数据预处理与…

力扣每日一题 6/13 反悔贪心算法

博客主页&#xff1a;誓则盟约系列专栏&#xff1a;IT竞赛 专栏关注博主&#xff0c;后期持续更新系列文章如果有错误感谢请大家批评指出&#xff0c;及时修改感谢大家点赞&#x1f44d;收藏⭐评论✍ 2813.子序列最大优雅度【困难】 题目&#xff1a; 给你一个长度为 n 的二…

vue技巧(十)全局配置使用(打包后可修改配置文件)

1、背景 vue打包目前主流用的有webpack和vite两种&#xff0c;默认用的webpack。&#xff08;二者的区别大家可以各自上网查&#xff0c;我没用过vite&#xff0c;所以不过多介绍&#xff09;vue通过webpack打包后&#xff0c;源码会被压缩&#xff0c;但一些关键配置可…

Redis高级特性和应用:慢查询、Pipeline、事务、Lua

Redis提供了许多高级特性&#xff0c;可以帮助优化和管理系统性能。本文将介绍Redis的慢查询、Pipeline、事务和Lua脚本的使用及其相关配置。 Redis的慢查询 慢查询日志是开发和运维人员定位系统慢操作的重要工具。Redis也提供了类似的功能&#xff0c;通过记录超过预设阀值的…

C# WPF入门学习主线篇(三十四)—— 图形和动画

C# WPF入门学习主线篇&#xff08;三十四&#xff09;—— 图形和动画 图形和动画是WPF的重要组成部分&#xff0c;能够大幅提升应用程序的用户体验。本篇博客将详细介绍WPF中图形和动画的使用方法&#xff0c;涵盖基本图形绘制、动画创建及多媒体的应用。通过本文&#xff0c;…

2024 Idea最新激活码

idea的激活与安装 操作如下&#xff1a; ① 打开网站&#xff1a;https://web.52shizhan.cn 切换到&#xff1a;激活码&#xff0c;点击获取 ② 这个时候就跳转到现成账号页面&#xff0c;点击获取体验号&#xff0c;如图 ③ 来到了获取现成账号的页面了。输入你的邮箱账号即…

二十三、生成帮助文档

二十一、Java工具类的创建 二十二、Jar包制作及使用 这一篇开始学习如何生成帮助文档。为什么要学习生成帮助文档&#xff1f; 1、工具类已经制作好了&#xff0c;Java工具类的创建的类是一个.java文件&#xff0c;编译后成.class文件看不懂&#xff0c;所以需要对应的帮助文档…

我的高考往事

高考对于每一个参加过的人来说&#xff0c;都是一段非常难忘的回忆。 我参加高考&#xff0c;是在2001年。虽然迄今已经过去了23年&#xff0c;但很多细节仍然记忆犹新。 今天这篇文章&#xff0c;我就和大家分享一下&#xff0c;我的高考往事。 █ 青少年时代 我的老家是在江西…

函数式开发接口( Consumer、Function)在实际开发中的应用场景

之前有个扫码下载文件需求&#xff0c;由于要同时进行记录下载人的记录。一开始用的是异步进行日志记录。发现有的用户扫码下载了一次文件&#xff0c;日志记录了三条。这种很容易联想到是因为网络抖动造成的。 问题代码 由于日志记录是异步的&#xff0c;文件下载需要时间。同…