人脸识别之facenet代码实现

article/2025/8/27 21:39:40

上一篇博文介绍了facenet的原理,这篇讲解一下代码的实现,对于facenet的代码目前也有写好的部分。具体见链接facenet代码实现 。大家可以通过git直接下载代码,然后运行里面的validata_on_lfw.py。输入对应的lfw数据的路径就可以检测模型对lfw数据的准确度。

 validata_on_lfw.py中,主要是通过data/pairs.txt对lfw进行分对读取。并标记出每一对图片是不是一类。对于训练的结果计算其对应的距离并和给出的阀值进行比较,当距离小于给出的阀值时是一类,大于时不是一类。最后根据判断的结果和标记的结果计算对应的准确率和其他的值。

在该代码中通过(use_fixed_image_standardizatiion来控制采用固定值归一化(减去127.5然后除以128.0)),根据代码可以看出该处理并没有给use_fixed_image_standardizatiion赋值所以采用的是每张图片单独处理的方式。并且没有给crop赋值所以采用了resize_image_with_crop_or_pad的裁剪方式。同时准确度的计算方面才用看10折交叉交叉验证把输入的数据分成训练和测试在训练上找到一个合适的阀值(开始输入的阀值时0到4每隔0.01取一个),最后对测试数据采用找到的阀值计算准去度最后平均得到的。

另外在代码实现的过程中建议使用tf.cast(imag ,tf.float32)将读出的图片类型转换为float型,这样在进行去噪操作时会避免数值计算带来的误差。也会相应的提高准确度。

 

 

use_fixed_image_standardization

 cluster.py:该程序主要是采用密度聚类的方式对提取出的特征进行聚类分析。对于这个文件大家可以运行一下,并且好好理解一下,可以帮助大家理解模型的使用。

对于项目中的代码,建议大家运行上述2个即可。然后根据自己的想法对模型结果进行自己的处理。我开始的时候把里面每个代码的实现过程都看了一遍,但是后来发现看完之后除了浪费时间没有别的其他作用。

基于该代码,我自己写了一个人脸的识别过程。主要是在图片中识别对应的每个人是谁。该问题主要分为两部分:第一标签的采集。首先对于输入的图片进行人脸对齐,将对齐之后的图片采用网络进行处理并将产生的向量和标签的名字存为对应的.npy文件方便后续的使用。具体如下:

 

from __future__ import absolute_import
from __future__ import division
from __future__ import print_functionfrom scipy import misc
import tensorflow as tf
import numpy as np
import os
import sys
import argparse
from facenetuse.use_model import until
from facenetuse.mtcnn import detect_face
from sklearn.cluster import DBSCAN
# 对标签文件中的图片进行处理,生成最终的标签和特征
# 最终返回一个二维数据对数组,第一个元素表示标签名字,第二个元素表示标签对应的特征向量def main(args):pnet, rnet, onet = create_network_face_detection()with tf.Graph().as_default():with tf.Session() as sess:until.load_model(args.model)# 从文件夹中读取数据生成对应的列表label, image_list = until.load_label_image_from_folder(args.data_dir)print(len(label))# print(image_list)# 采用MTCNN将读取的数据进行人脸检测,生成对应的大小的人脸数据images = until.align_data(image_list, args.image_size, args.margin, pnet, rnet, onet)# 定义模型中的输入和输出张量images_placeholder = sess.graph.get_tensor_by_name("input:0")embeddings = sess.graph.get_tensor_by_name("embeddings:0")phase_train_placeholder = sess.graph.get_tensor_by_name("phase_train:0")feed_dict = {images_placeholder: images, phase_train_placeholder: False}emb = sess.run(embeddings, feed_dict=feed_dict)np.save(os.path.join(args.output_dir, "label.npy"), label)np.save(os.path.join(args.output_dir, "emb.npy"), emb)def create_network_face_detection():with tf.Graph().as_default():sess = tf.Session()with sess.as_default():pnet, rnet, onet = detect_face.create_mtcnn(sess, None)return pnet, rnet, onetdef parse_arguments(argv):parser = argparse.ArgumentParser()parser.add_argument('--model', type=str,help='Either a directory containing the meta_file and ckpt_file or a model'' protobuf (.pb) file',)parser.add_argument('--data_dir', type=str,help='The directory containing the images to cluster into folders.',)parser.add_argument('--output_dir', type=str,help='The directory containing the images to cluster into folders.',)parser.add_argument('--image_size', type=int,help='Image size (height, width) in pixels.', default=160)parser.add_argument('--margin', type=int,help='Margin for the crop around the bounding box (height, width) in pixels.', default=44)parser.add_argument('--min_cluster_size', type=int,help='The minimum amount of pictures required for a cluster.', default=1)parser.add_argument('--cluster_threshold', type=float,help='The minimum distance for faces to be in the same cluster', default=1.0)parser.add_argument('--largest_cluster_only', action='store_true',help='This argument will make that only the biggest cluster is saved.')return parser.parse_args(argv)if __name__ == '__main__':main(parse_arguments(sys.argv[1:]))

对于输入的图片,采用相同的人脸对齐技术处理,然后对处理后的图片调用同样的网络生成对应的特征向量,并使用生成的特征向量和标签向量计算其对应的距离。选择距离最小的标签作为识别出来的结果。具体代码如下:

 

from __future__ import absolute_import
from __future__ import division
from __future__ import print_functionfrom scipy import misc
import tensorflow as tf
import numpy as np
import os
import sys
import argparse
from facenetuse.use_model import  until
from facenetuse.mtcnn import detect_face
from sklearn.cluster import DBSCAN
# 对文件夹内的图像进行读取,取出其对应的特征向量后并与标签中的特征向量
# 行比较,最终确定最终的图片类别def main(args):pnet, rnet, onet = create_network_face_detection()with tf.Graph().as_default():with tf.Session() as sess:until.load_model(args.model)# 从标签数据中读入对应的标签信息label = np.load(os.path.join(args.label_dir, "label.npy"))label_feature = np.load(os.path.join(args.label_dir, "emb.npy"))print(label.shape)print(label_feature.shape)# 从文件夹中读取数据生成对应的列表image_list, _ = until.load_images_from_folder(args.data_dir)# 采用MTCNN将读取的数据进行人脸检测,生成对应的大小的人脸数据images = until.align_data(image_list, args.image_size, args.margin, pnet, rnet, onet)# 定义模型中的输入和输出张量images_placeholder = sess.graph.get_tensor_by_name("input:0")embeddings = sess.graph.get_tensor_by_name("embeddings:0")phase_train_placeholder = sess.graph.get_tensor_by_name("phase_train:0")feed_dict = {images_placeholder: images, phase_train_placeholder: False}emb = sess.run(embeddings, feed_dict=feed_dict)print(emb.shape)# 后续均为对模型算出的数据进行的处理nrof_images = len(images)label_num = label.shape[0]matrix = np.zeros((nrof_images, label_num))# Print distance matrixprint('Distance matrix')for i in range(nrof_images):for j in range(label_num):dist = np.sqrt(np.sum(np.square(np.subtract(emb[i, :], label_feature[j, :]))))matrix[i][j] = distprint('  %1.4f  ' % dist, end='')print()for i in range(nrof_images):list_dir = matrix[i, :]min_dir = np.min(list_dir)index = np.where(min_dir == list_dir)[0]print(label[index])def create_network_face_detection():with tf.Graph().as_default():sess = tf.Session()with sess.as_default():pnet, rnet, onet = detect_face.create_mtcnn(sess, None)return pnet, rnet, onetdef parse_arguments(argv):parser = argparse.ArgumentParser()parser.add_argument('--model', type=str,help='Either a directory containing the meta_file and ckpt_file or a model'' protobuf (.pb) file',)parser.add_argument('--data_dir', type=str,help='The directory containing the images to cluster into folders.',)parser.add_argument('--out_dir', type=str,help='The output directory where the image clusters will be saved.',)parser.add_argument('--label_dir', type=str,help='The directory containing the images to cluster into folders.',')parser.add_argument('--image_size', type=int,help='Image size (height, width) in pixels.', default=160)parser.add_argument('--margin', type=int,help='Margin for the crop around the bounding box (height, width) in pixels.', default=44)parser.add_argument('--min_cluster_size', type=int,help='The minimum amount of pictures required for a cluster.', default=1)parser.add_argument('--cluster_threshold', type=float,help='The minimum distance for faces to be in the same cluster', default=1.0)parser.add_argument('--largest_cluster_only', action='store_true',help='This argument will make that only the biggest cluster is saved.')return parser.parse_args(argv)if __name__ == '__main__':main(parse_arguments(sys.argv[1:]))

 

经过上述两步的处理就可以识别自己的图片了。当然也可以使用结果对图片进行其他的操作,无论进行什么样的操作其实就和模型本身没有关系了。主要是对特征向量的处理。

注意:

1. 在识别过程中,我们发现图片经过处理后生成的特征向量是512维,不是128维,不知道是不是和选取的模型有关

2. 阀值的选取:在validata_on_lfw实现的过程中,阀值并不是1.1,而是在0-4每隔0.01进行切分,利用分出来的值分别作为阀值进行准确率的计算,最终选择准确率最大的阀值作为分类的依据。该值是1.23。所以在平时使用过程中当数据量较大时也可以借鉴该方法;数据量较小时可以选取最小的值作为阀值(此时最小是指生成的标签向量之间的距离最小)。


http://chatgpt.dhexx.cn/article/5AJElNvS.shtml

相关文章

聪明的人脸识别1——Keras 搭建自己的Facenet人脸识别平台

聪明的人脸识别1——Keras 搭建自己的Facenet人脸识别平台 学习前言什么是Facenet源码下载Facenet的实现思路一、预测部分1、主干网络介绍2、根据初步特征获得长度为128的特征向量3、l2标准化4、构建分类器(用于辅助Triplet Loss的收敛) 二、训练部分1、…

人脸识别系列(六):FaceNet

原文链接:FaceNet:A Unified Embedding for Face Recognition and Clustering 首先可以看一下最终的效果,数字表示两张图片经过Facenet提取的特征之间的欧式距离,可以直接表示两张图片的差异: 从图中可以看出,若取阈值…

人脸识别(Facenet)

人脸识别是目前应用非常广泛的一种生物识别技术,与其他生物识别技术(指纹识别,掌形识别,眼虹膜识别和声音识别)相比,人脸识别具有以下优势: 其他每种生物识别方法都需要一些人的配合动作&#x…

全网首发,Swin Transformer+FaceNet实现人脸识别

目录 一、 简介 二、Swin Transformer作为Backbone 1.Swin Transformer整体结构 2.PatchEmbed Patch Partition Linear Embedding 3.Swin Transformer Block (1)Window Partition (2)Shifted Window based Self-Attenti…

深度学习之facenet人脸识别网络介绍

1.前言 照例先来一段废话,不要跟我说什么物质决定意识,也不要告诉我意识超越物质。在我眼中,这个世界本就是一个战场。软弱的意志自然无法战胜物质,但是足够强大的意识也是能够做到的。在战争没有进行完之前,谁也不知道…

聪明的人脸识别4——Pytorch 利用Retinaface+Facenet搭建人脸识别平台

睿智的目标检测51——Pytorch 利用RetinafaceFacenet搭建人脸识别平台 学习前言什么是Retinface和Facenet1、Retinface2、Facenet 整体实现代码实现流程一、数据库的初始化二、检测图片的处理1、人脸的截取与对齐2、利用Facenet对矫正后的人脸进行编码3、将实时图片中的人脸特征…

Facenet 原理介绍

引子[编辑 | 编辑源代码] 这篇wiki主要介绍facenet人脸相似比较的基本原理,另外两篇wiki主要介绍基于tensorflow实现facenet的准确率测试及源码解读。经过在网上的一番搜索,找到了facenet实现人脸聚类的论文和论文解读,以及github上根据facen…

【 facenet-retinaface】快速复现 实现 facenet-retinaface-pytorch 人脸识别 windows上 使用cpu实现

目录 0 前言1 搭建环境与项目2 人脸预测与结果展示 0 前言 这一次要复现的是人脸识别中的 facenet-retinaface-pytorch 是在上一次博客的内容上更进一步 快速复现 实现 facenet-pytorch 人脸识别 windows上 使用cpu实现 人脸对比 参考了: Pytorch 利用Facenet和Re…

FaceNet

摘要: 尽管人脸识别领域最近取得了重大进展[10,14,15,17],但大规模有效地实施人脸验证和识别对当前方法提出了严峻挑战。在本文中,我们提出了一个称为 FaceNet 的系统,它直接学习从人脸图像到紧凑欧几里得空间的映射,其…

【facenet】快速复现 实现 facenet-pytorch 人脸识别 windows上 使用cpu实现 人脸对比

目录 0 前言1 搭建环境与项目2 人脸预测与结果展示 0 前言 这一次要复现的是人脸识别中的 facenet-pytorch 参考了: Pytorch 搭建自己的Facenet人脸识别网络(Bubbliiiing 深度学习 教程) https://gitee.com/xiaozhao123666/facenet-pytorch …

利用MTCNN和facenet实现人脸检测和人脸识别

利用MTCNN和facenet实现人脸检测和人脸识别 人脸检测和人脸识别技术算是目前人工智能方面应用最成熟的技术了。本博客将利用mtcnn和faceNet搭建一个实现人脸检测和人脸识别的系统。基本思路也很简单,先利用mtcnn的进行人脸检测,当然也可以使用其他的人脸…

facenet 总结一

Facenet是谷歌研发的人脸识别系统,该系统是基于百万级人脸数据训练的深度卷积神经网络,可以将人脸图像embedding(映射)成128维度的特征向量。以该向量为特征,采用knn或者svm等机器学习方法实现人脸识别。 CASIA-WebFac…

【人脸识别】FaceNet详解

论文题目:《FaceNet: A Unified Embedding for Face Recognition and Clustering》 论文地址:FaceNet 1、概述 FaceNet(A Unified Embedding for Face Recognition and Clustering)直接把输入图像变成欧式空间中的特征向量&#…

人脸识别系统FaceNet原理

1. 概述 近年来,随着深度学习在CV领域的广泛应用,人脸识别领域也得到了巨大的发展。在深度学习中,通过多层网络的连接,能够学习到图像的特征表示,那么两张人脸的图像,是不是可以通过深度学习判别其是否是相…

聪明的人脸识别3——Pytorch 搭建自己的Facenet人脸识别平台

聪明的人脸识别3——Pytorch 搭建自己的Facenet人脸识别平台 学习前言什么是Facenet源码下载Facenet的实现思路一、预测部分1、主干网络介绍2、根据初步特征获得长度为128的特征向量3、l2标准化4、构建分类器(用于辅助Triplet Loss的收敛) 二、训练部分1…

syscall()

1、syscall的定义 #include<unistd.h> #include<sys/syscall.h> / For SYS_xxx definitions /long syscall(long number, ...);syscall执行间接系统调用&#xff0c;使用该函数会执行一个系统调用&#xff0c;根据指定的参数 number 和所有系统调用的汇编语言接口…

linux systemctl命令详解

笔者在前文中概要的介绍了 systemd 的基本概念和主要特点。由于 systemd 相关的绝大多数任务都是通过 systemctl 命令管理的&#xff0c;所以本文将集中的介绍 systemctl 命令的用法。注意&#xff0c;本文以 ubuntu 16.04 进行介绍&#xff0c;文中所有的 demo 都在 ubuntu 16…

Linux常用命令——sysctl命令

在线Linux命令查询工具(http://www.lzltool.com/LinuxCommand) sysctl 时动态地修改内核的运行参数 补充说明 sysctl命令被用于在内核运行时动态地修改内核的运行参数&#xff0c;可用的内核参数在目录/proc/sys中。它包含一些TCP/ip堆栈和虚拟内存系统的高级选项&#xff…

Linux之systemctl命令基本使用

文章目录 1. systemctl 管理指令2. systemctl 设置服务的自启动状态3. 应用案例&#xff1a;4. 细节讨论&#xff1a; 1. systemctl 管理指令 基本语法&#xff1a; systemctl [start | stop | restart | status] 服务名systemctl 指令管理的服务在 /usr/lib/systemd/system 查…

systemctl命令解析

原文链接如果有效&#xff0c;请点击原文链接查看。 原文&#xff1a;http://www.ruanyifeng.com/blog/2016/03/systemd-tutorial-commands.html 一、由来 历史上&#xff0c;Linux 的启动一直采用init进程。 下面的命令用来启动服务。 $ sudo /etc/init.d/apache2 start # …