[深度学习] Python人脸识别库Deepface使用教程

article/2025/10/25 1:01:09

deepface是一个Python轻量级人脸识别和人脸属性分析(年龄、性别、情感和种族)框架,提供非常简单的接口就可以实现各种人脸识别算法的应用。deepface官方仓库为deepface。deepface提供了多种模型,模型下载地址为deepface_models。

安装方式: pip install deepface -i https://pypi.tuna.tsinghua.edu.cn/simple

deepface主要提供以下人脸识别算法,具体对应接口为:

  • DeepFace.verify:人脸验证
  • DeepFace.find:人脸识别
  • DeepFace.analyze:人脸属性分析
  • DeepFace.detectFace:人脸检测
  • DeepFace.represent:人脸特征提取
  • DeepFace.stream:人脸实时分析

总体而言,这个项目的人脸识别模型识别效果还行,但是离工程应用还是有一定的距离,不过还是非常推荐学习该库内部代码。

某些网站会判定本文人脸图片违规,这是网站识别算法自身问题。

本文所有算法展示效果和代码见:

github: Python-Study-Notes

此外可以看一看另外一个人脸识别库,功能更加齐全:[深度学习] Python人脸识别库face_recognition使用教程

文章目录

  • 0 数据准备
  • 1 人脸验证DeepFace.verify
  • 2 人脸识别DeepFace.find
  • 3 人脸属性分析DeepFace.analyze
  • 4 人脸检测DeepFace.detectFace
  • 5 人脸特征提取DeepFace.represent
  • 6 参考

0 数据准备

# deep库的导入就一行代码
from deepface import DeepFace
import matplotlib.pyplot as plt
from PIL import Image, ImageDraw
import os
import cv2
import numpy as np

所使用的数据集为网络明星图片,共五个明星,每个明星三张人脸,数据集的路径如下:

root
├── images
│   ├── baijingting
│   │   ├── 0000.jpg
│   │   ├── 0001.jpg
│   ├── jiangwei
│   │   ├── 0000.jpg
│
├── code

数据展示结果如下:

# --- 展示图片
def show_img(imgs: list, img_names: list) -> None:imgs_count = len(imgs)for i in range(imgs_count):ax = plt.subplot(1, imgs_count, i+1)ax.imshow(imgs[i])ax.set_title(img_names[i])ax.set_xticks([])ax.set_yticks([])plt.tight_layout(h_pad=3)plt.show()img_path = "images"
for person_dir in os.listdir(img_path):imgs = []img_names = []for file in os.listdir(os.path.join(img_path, person_dir)):imgs.append(Image.open(os.path.join(img_path, person_dir, file)))img_names.append(person_dir + '/' + file)show_img(imgs, img_names)

png)

在这里插入图片描述

png

在这里插入图片描述

png)

1 人脸验证DeepFace.verify

此函数用于验证图像对是同一个人还是不同的人。函数接口为:

verify(img1_path, img2_path = '', model_name = 'VGG-Face', distance_metric = 'cosine', model = None, enforce_detection = True, detector_backend = 'opencv', align = True, prog_bar = True, normalization = 'base')

输入参数介绍:

img1_path:传递的图像路径、numpy数组(BGR)或based64编码图像
model_name:模型名,支持VGG-Face, Facenet, OpenFace, DeepFace, DeepID, Dlib, ArcFace,Ensemble等
distance_metric:度量标准,支持cosine, euclidean, euclidean_l2
model:构建deepface模型。每次调用verify函数都会重新建立人脸识别模型。可以选择传递预构建的人脸识别模型。如DeepFace.build_model('VGG-Face')构建模型
enforce_detection:如果在图像中检测不到任何人脸,则验证函数将返回异常。将此设置为False将不会出现此异常
detector_backend:人脸识别算法后端,支持retinaface, mtcnn, opencv, ssd,dlib
align:是否人脸对齐
prog_bar:启用或禁用进度条
normalization:人脸归一化的方式

输出结果介绍:

如果img1_path是输入一张人脸就是返回一个字典,如果输入列表则返回一个字典列表。具体参数如下:
verified:是否同一个人
distance:人脸距离,越小越相似
max_threshold_to_verify:判断为同一个人的阈值
model: 所用模型
similarity_metric: 相似性度量标准

各识别模型的精度如下,LFW和YTF都是小型数据集。Human-beings表示人类识别精度。

ModelLFW ScoreYTF Score
Facenet51299.65%-
SFace99.60%-
ArcFace99.41%-
Dlib99.38 %-
Facenet99.20%-
VGG-Face98.78%97.40%
Human-beings97.53%-
OpenFace93.80%-
DeepID-97.05%

demo1

# 模型名
models_name = ["VGG-Face", "Facenet", "Facenet512", "OpenFace","DeepFace", "DeepID", "ArcFace", "Dlib", "SFace", 'Ensemble']model_name = models_name[5]
result = DeepFace.verify(img1_path="images/baijingting/0001.jpg",img2_path="images/pengyuyan/0001.jpg",model_name=model_name)
# 展示结果,两个人不是同一个人
print(result)
1/1 [==============================] - 0s 170ms/step
1/1 [==============================] - 0s 20ms/step
{'verified': False, 'distance': 0.0751386867894902, 'threshold': 0.015, 'model': 'DeepID', 'detector_backend': 'opencv', 'similarity_metric': 'cosine'}

demo2

models_name = ["VGG-Face", "Facenet", "Facenet512", "OpenFace","DeepFace", "DeepID", "ArcFace", "Dlib", "SFace", 'Ensemble']
# 提前加载模型,避免重复加载
model_name = models_name[1]
# 创建模型
model = DeepFace.build_model(model_name)
# 列表中每一个子项表示用于对比的图像
img_paths = [["images/baijingting/0000.jpg", "images/baijingting/0001.jpg"],["images/baijingting/0000.jpg", "images/zhaoliying/0001.jpg"]]
# 度量标准
metrics = ["cosine", "euclidean", "euclidean_l2"]results = DeepFace.verify(img_paths,model_name=model_name,model=model,distance_metric=metrics[2],prog_bar=False)
# 展示结果
for result in results.items():print(result)
1/1 [==============================] - 2s 2s/step
1/1 [==============================] - 0s 52ms/step
1/1 [==============================] - 0s 55ms/step
1/1 [==============================] - 0s 66ms/step
('pair_1', {'verified': True, 'distance': 0.6328494898310356, 'threshold': 0.8, 'model': 'Facenet', 'detector_backend': 'opencv', 'similarity_metric': 'euclidean_l2'})
('pair_2', {'verified': False, 'distance': 1.1700473293978308, 'threshold': 0.8, 'model': 'Facenet', 'detector_backend': 'opencv', 'similarity_metric': 'euclidean_l2'})

2 人脸识别DeepFace.find

此函数用于从数据集中检索当前人脸相似的图片。函数接口为:

find(img_path, db_path, model_name ='VGG-Face', distance_metric = 'cosine', model = None, enforce_detection = True, detector_backend = 'opencv', align = True, prog_bar = True, normalization = 'base', silent=False):

输入参数和verify差不多,主要多了人脸检索库路径地址:

db_path:检索库路径,
silent: 是否静默显示数据,

输出结果介绍:

一个包含相似图像的pandas dataframe数据体,包括图像路径和距离值,
models_name = ["VGG-Face", "Facenet", "Facenet512", "OpenFace","DeepFace", "DeepID", "ArcFace", "Dlib", "SFace", 'Ensemble']# db_path是库文件地址
# 第一次会提取各个图像的特征,并保存到本地pkl文件以供下次直接调用
result = DeepFace.find(img_path="images/baijingting/0000.jpg",db_path="images", model_name=models_name[1])
1/1 [==============================] - 0s 55ms/step
1/1 [==============================] - 0s 64ms/step
1/1 [==============================] - 0s 63ms/step
1/1 [==============================] - 0s 61ms/step
1/1 [==============================] - 0s 64ms/step
1/1 [==============================] - 0s 58ms/step
1/1 [==============================] - 0s 55ms/step
1/1 [==============================] - 0s 65ms/step
1/1 [==============================] - 0s 59ms/step
1/1 [==============================] - 0s 55ms/step
1/1 [==============================] - 0s 51ms/step
1/1 [==============================] - 0s 52ms/step
1/1 [==============================] - 0s 53ms/step
1/1 [==============================] - 0s 52ms/step
1/1 [==============================] - 0s 55ms/step
Representations stored in  images / representations_facenet.pkl  file. Please delete this file when you add new identities in your database.
1/1 [==============================] - 0s 56ms/step
find function lasts  3.254298448562622  seconds
# 展示结果,第一个是识别图像本身,后面两个是相似图片
print(result)
                      identity  Facenet_cosine
0  images\baijingting/0000.jpg   -2.220446e-16
1  images\baijingting/0001.jpg    2.002492e-01
2  images\baijingting/0002.jpg    2.328966e-01

3 人脸属性分析DeepFace.analyze

此函数用于分析当前人脸的面部属性,包括年龄,性别,面部表情(包括愤怒、恐惧、正常、悲伤、厌恶、快乐和惊讶),种族(包括亚洲人、白人、中东人、印度人、拉丁裔和黑人)。函数接口为:

analyze(img_path, actions = ('emotion', 'age', 'gender', 'race') , models = None, enforce_detection = True, detector_backend = 'opencv', prog_bar = True)

输入参数和verify差不多,主要多了属性设置actions:

actions:识别属性,包括age, gender, emotion, race

输出结果介绍:

如果img_path是输入一张人脸就是返回一个字典,如果输入列表则返回一个字典列表。具体参数如下:
region:人脸坐标,wywh格式
age:年龄
gender:性别
dominant_emotion: 主导情绪,也就是情绪识别结果
emotion:各个情绪度量值,值越大表示越倾向
dominant_race:种族结果
race:各个种族度量值
# 输入检测图像,这里只识别情绪,因为其他模型实在太大了,下载下来要很久。
result = DeepFace.analyze(img_path = "images/jiangwen/0000.jpg", actions = ['emotion'])
print(result)
1/1 [==============================] - 0s 113ms/step
{'emotion': {'angry': 2.147514166495057e-06, 'disgust': 3.124029827739067e-14, 'fear': 1.990160924947304e-06, 'happy': 99.9697208404541, 'sad': 1.9864262412738753e-05, 'surprise': 0.01537421194370836, 'neutral': 0.014887277211528271}, 'dominant_emotion': 'happy', 'region': {'x': 198, 'y': 34, 'w': 185, 'h': 185}}

数据可视化看看结果

im = Image.open( "images/jiangwen/0000.jpg")
# 坐标位置
x,y,w,h = result['region']['x'],result['region']['y'],result['region']['w'],result['region']['h']
draw = ImageDraw.Draw(im)
# 画框
draw.rectangle((x,y,x+w,y+h), outline="red", width=3)
print("表情:{}".format(result["dominant_emotion"]))
show_img([im],["jiangwen"])
表情:happy

png

4 人脸检测DeepFace.detectFace

此函数用于检测人脸,如果图像中有多个人脸只会返回一个,函数接口为:

detectFace(img_path, target_size = (224, 224), detector_backend = 'opencv', enforce_detection = True, align = True)

输入参数和verify差不多,主要多了可以设置返回图像的尺寸的参数target_size,输出返回一张RGB的numpy数组图像

result = DeepFace.detectFace(img_path = "images/zhangziyi/0000.jpg",align = True)
print(result.shape)
show_img([result],["zhangziyi"])
(224, 224, 3)

png

# 不进行人脸对齐
result = DeepFace.detectFace(img_path = "images/zhangziyi/0000.jpg",align = False)
print(result.shape)
show_img([result],["zhangziyi"])
(224, 224, 3)

png

5 人脸特征提取DeepFace.represent

该函数用于将面部图像表示为特征向量,函数接口为:

represent(img_path, model_name = 'VGG-Face', model = None, enforce_detection = True, detector_backend = 'opencv', align = True, normalization = 'base')

输入参数和verify差不多。输出返回图像特征多维向量,特征向量的维度根据模型而变化。

models_name = ["VGG-Face", "Facenet", "Facenet512", "OpenFace","DeepFace", "DeepID", "ArcFace", "Dlib", "SFace", 'Ensemble']result = DeepFace.represent(img_path="images/baijingting/0000.jpg", model_name=models_name[1])
print("特征维度为:{}".format(len(result)))
1/1 [==============================] - 0s 61ms/step
特征维度为:128

当然提取特征可以自己计算距离,设置阈值。示例如下。

# 计算l2距离
def l2_distance(input1: np.ndarray, input2: np.ndarray) -> float:# 手动计算 np.sqrt(np.sum((result1- result2)**2))return np.linalg.norm(input1-input2)# 计算l1距离
def l1_distance(input1: np.ndarray, input2: np.ndarray) -> float:# 手动计算 np.sum(abs(input1-input2))return np.linalg.norm(input1-input2, ord=1)# 计算余弦距离
def IP_distance(input1: np.ndarray, input2: np.ndarray) -> float:return 1 - np.dot(input1, input2)/np.linalg.norm(input1)/np.linalg.norm(input2)
models_name = ["VGG-Face", "Facenet", "Facenet512", "OpenFace","DeepFace", "DeepID", "ArcFace", "Dlib", "SFace", 'Ensemble']# 提前加载模型,避免重复加载
model_name = models_name[1]
# 创建模型
model = DeepFace.build_model(model_name)# res1和res3为同一个人
res1 = DeepFace.represent(img_path="images/baijingting/0000.jpg", model_name=models_name[1], model=model)
res2 = DeepFace.represent(img_path="images/zhangziyi/0000.jpg", model_name=models_name[1], model=model)
res3 = DeepFace.represent(img_path="images/baijingting/0001.jpg", model_name=models_name[1], model=model)# 转换为numpy类型
res1 = np.array(res1)
res2 = np.array(res2)
res3 = np.array(res3)print("res1与res2的余弦距离为:{}".format(IP_distance(res1,res2)))
print("res1与res3的余弦距离为:{}".format(IP_distance(res1,res3)))
print("res1与res2的l2距离为:{}".format(l2_distance(res1,res2)))
print("res1与res3的l2距离为:{}".format(l2_distance(res1,res3)))
print("res1与res2的l1距离为:{}".format(l1_distance(res1,res2)))
print("res1与res3的l1距离为:{}".format(l1_distance(res1,res3)))
1/1 [==============================] - 0s 54ms/step
1/1 [==============================] - 0s 62ms/step
1/1 [==============================] - 0s 52ms/step
res1与res2的余弦距离为:0.6868675298615137
res1与res3的余弦距离为:0.2002492383897012
res1与res2的l2距离为:12.135816884638682
res1与res3的l2距离为:6.657409646028565
res1与res2的l1距离为:110.3180431430228
res1与res3的l1距离为:58.20380371063948

6 参考

  • deepface
  • deepface_models
  • [深度学习] Python人脸识别库face_recognition使用教程
  • Python-Study-Notes

http://chatgpt.dhexx.cn/article/IpD3u2FA.shtml

相关文章

[深度学习] Python人脸识别库face_recognition使用教程

Python人脸识别库face_recognition使用教程 face_recognition号称是世界上最简单的开源人脸识别库,可以通过Python或命令行识别和操作人脸。face_recognition提供了十分完整的技术文档和应用实例,人脸识别初学者建议研究该库上手。face_recognition的官…

Face Recognition 库-人脸识别

1. Face Recognition 库简介: 中文文档: [face_recognition/README_Simplified_Chinese.md] Face Recognition 库主要封装了dlib这一 C 图形库,通过 Python 语言将它封装为一个非常简单就可以实现人脸识别的 API 库,屏蔽了人脸识…

应用层下的人脸识别(二):人脸库

本文为系列文章的第二篇,介绍人脸库的相关内容。人脸库是人脸识别的基础,建立人脸库往往是人脸项目的首要任务,全文围绕着什么是人脸库及如何建立人脸库展开讨论。 1. 什么是人脸库 简单来讲,人脸库就是人脸数据的储存管理中心&a…

全国高校计算机能力挑战赛Java试题(一)

消除字符串 这个题目上来就是运用一个回文的一个思想&#xff0c;我目前算法也是入门阶段&#xff0c;所以也处于学习阶段。 public class xiaozfc {public static void main(String[] args) {Scanner sc new Scanner(System.in);String txt sc.next();ArrayList<String&…

Java课程设计--学生成绩管理系统

一、团队名称&#xff1a; 团队成员&#xff1a; 刘江华 2019122249819 19信管专升本杨利杰 2018122241648 18信管本张富强 2018122241658 18信管本 二、需求分析 1.数据存储在数据库和文件中 分为“教师”模块和“学生”模块。 2.学生模块提供登陆功能&#xff0c;登陆成功后…

Java8--20道关于Stream流的题目练习

正题开始 Student 类 具有属性&#xff1a; 不及格次数failCount&#xff0c; 名字name&#xff0c; 科任老师chineseTeacher&#xff0c; 班主任classTeacher题目1&#xff1a;筛选学生不及格次数3次及3次以上的学生列表 List<String> arrayList array.stream().filte…

第十三届蓝桥杯省赛 JAVA B组(真题解析+个人体会)(已更新完G题)

试题 A: 星期计算【填空题】 题目&#xff1a; 答案&#xff1a;7 解析&#xff1a; 此题直接对7求余即可。 public class Main {public static void main(String[] args) {System.out.println(Math.pow(20, 22) % 7 6);} } 贴一个BigInteger的代码 import java.math.Bi…

java的一些课程设计题目_Java课程设计

Java课程设计 1. 题目及要求 基于学校的搜索引擎 负责部分:Java GUI设计 2.界面调查 1)调查界面:百度 2)思考: 根据我的调查,我认为我需要完成三个界面的设计: 第一个是调查主界面,里面有一个集美大学的logo,一个搜索框用文本字段,因为需要在里面写入搜索内容,一个搜索…

计算机二级--java篇

计算机二级 全国计算机等级&#xff08;NCRE&#xff09;&#xff0c;计算机二级分为语言程序设计&#xff08;包括C、C、Java、Visual Basic&#xff09;、数据库程序设计&#xff08;包括Visual FoxPro、Access&#xff09;、MS Office高级应用&#xff0c;各项目均为机考。考…

java 课程设计题目_Java课程设计题目有哪些?Java课程设计题目汇总

在学习Java的路上,多多练习项目实践是很有必要的。因此,本文整理了20道Java课程设计题目,希望大家总结、回顾和实践学过的所有面向对象的编程思想以及编程方法。 1、编写一个记事本程序 要求:用图形用户界面实现。 能实现编辑、保存、另存为、查找替换等功能。 提示:使用文…

Java绘制圆形

package 坦克大战.draw;import javax.swing.*; import java.awt.*;/*** Auther:* Date: 2022/4/16 - 04 - 16 - 21:16* Description: 坦克大战.draw* version: 1.0*/ public class draw extends JFrame{//继承JFrame、JFrame对应窗口&#xff0c;可以当作一个画框//定义一个画板…

Java练习题(经典8题)

题目一 共有50枚硬币&#xff0c;可能包括4种类型&#xff1a;1元&#xff0c;5角&#xff0c;1角&#xff0c;5分。已知总价值为20元。求各种硬币的数量。 解题思路&#xff1a;简单分析可知硬币有多种组合&#xff0c;我们可以假设先抛开50枚硬币去寻找1元需要多少个硬币&…

Java中常见的30道例题(附代码)

目录 第一题&#xff1a;判断数组中奇数偶数的个数并求和 第二题&#xff1a;判断三个数中的最大值 第三题&#xff1a;剔除某些数据并打印输出 第四题&#xff1a;输入0到7判断星期几 第五题&#xff1a;将一个数组倒序输出 第六题&#xff1a;输入一个数判断是否是素数 …

Linux内核编译详细总结

一、实验目的 学习重新编译Linux内核&#xff0c;理解、掌握Linux内核和发行版本的区别。 二、实验内容 在Linux操作系统环境下重新编译内核。实验主要内容&#xff1a; A. 查找并且下载一份内核源代码&#xff0c;本实验使用最新的Linux内核2.6.36。 B. 配置内核。 C. 编…

LINUX内核目录文件说明以及配置并编译内核的方法

在下载内核前&#xff0c;我们应该讨论一些重要的术语和事实。Linux内核是一个宏内核&#xff0c;这意味着整个操作系统都运行在内核预留的内存里。说的更清楚一些&#xff0c;内核是放在内存里的。内核所使用的空间是内核预留的。只有内核可以使用预留的内核空间。内核拥有这些…

Linux内核的编译、安装、调试

这里写目录标题 编译安装内核下载内核安装依赖更改.config编译内核安装首先安装模块安装内核更改引导更改grub重启 其他操作清理内核源目录卸载安装的内核修改内核配置菜单实现对新加入内核源码的控制 常见问题1. Module.symvers is missing2. No rule to make target ‘debian…

linux内核编译及添加系统调用(详细版)

linux内核编译及添加系统调用 注&#xff1a;文章共四部分&#xff0c;分别是 1、编译更换内核 2、添加一个简单系统系统调用 3、添加读取/修改nice值的系统调用 4、自己设计简单&#xff08;真的简单&#xff09;系统调用 注&#xff1a;四个部分结构相似&#xff0c;请…

打造自己的专属linux(四):Linux内核编译过程简介

linux在前不久刚发布了最新的3.0内核&#xff0c;在linux的学习中&#xff0c;了解内核的编译是一个必不可少的功课。前几天&#xff0c;学习了linux内核的编译流程&#xff0c;在此总结下&#xff0c;大家来一起学习。 以最新的3.0内核为例&#xff0c;我下载的是linux3.0.1 …

Linux内核开发_1_编译LInux内核

目录 1. 准备工作 1.1 学习环境 1.2 下载Linux内核源码 1.3 解压Linux内核 1.4 目录结构介绍 2. Linux内核配置 2.1 配置选项 1. make config 2. make menuconfig 3. make gconfig 3 开始配置 1. 配置解释 General setup 通用选项 Enable loadable module support…

ubuntu上编译Linux内核步骤

一、虚拟机的准备 1.下载Ubuntu镜像 Enterprise Open Source and Linux | Ubuntu 在最左边Ubuntu Desktop处点22.04LTS下载iso文件 2.在VMware上创建新的虚拟机 Ubuntu 20.04 虚拟机安装教程_柯基的博客-CSDN博客_虚拟机安装ubuntu20.04 特别注意: 在"指定磁盘容量&…