用FaceNet的模型计算人脸之间距离(TensorFlow)

来源:互联网 发布:cdn网络加速 书 编辑:程序博客网 时间:2024/06/14 00:31

2015年Google的研究人员发表了一篇论文:FaceNet: A Unified Embedding for Face Recognition and Clustering,是关于人脸识别的,他们训练一个网络来得到人脸的128维特征向量,从而通过计算特征向量之间的欧氏距离来得到人脸相似程度。在LFW上面取得了当时最好的成绩,识别率为99.63%。

传统的基于CNN的人脸识别方法为:利用CNN的siamese网络来提取人脸特征,然后利用SVM等方法进行分类。而这篇文章中他们提出了一个方法系统叫作FaceNet,它直接学习图像到欧式空间上点的映射,其中呢,两张图像所对应的特征的欧式空间上的点的距离直接对应着两个图像是否相似。

人脸之间距离

如上图所示,直接得出不同人脸图片之间的距离,通过距离就可以判断是否是同一个人,阈值大概在1.1左右。

而现在我要做的,就是用训练好的模型文件,实现任意两张人脸图片,计算其FaceNet距离。然后就可以将这个距离用来做其他的事情了。

环境

  • macOS 10.12.6
  • Python 3.6.3
  • TensorFlow 1.3.0

实现

模型文件

首先我们需要训练好的模型文件,这个可以在FaceNet官方的github中获取:

github的README中有

注意他们是存放在Google云盘中的,需要翻墙获取(没个翻墙能力连科研都做不好了。。)

代码

这里我们需要FaceNet官方的github中获取到的facenet.py文件以供调用,需要注意的是其github中的文件一直在更新,我参考的很多代码中用到的facenet.py文件里方法居然有的存在有的不存在,所以可能随着时间流逝有些现在能成功以后需要修改代码才能成功了。

代码如下:

# -*- coding: utf-8 -*-import tensorflow as tfimport numpy as npimport scipy.miscimport cv2import facenetimage_size = 200 #don't need equal to real image size, but this value should not small than thismodeldir = './model_check_point/20170512-110547.pb' #change to your model dirimage_name1 = 'x.jpg' #change to your image nameimage_name2 = 'y.jpg' #change to your image nameprint('建立facenet embedding模型')tf.Graph().as_default()sess = tf.Session()facenet.load_model(modeldir)images_placeholder = tf.get_default_graph().get_tensor_by_name("input:0")embeddings = tf.get_default_graph().get_tensor_by_name("embeddings:0")phase_train_placeholder = tf.get_default_graph().get_tensor_by_name("phase_train:0")embedding_size = embeddings.get_shape()[1]print('facenet embedding模型建立完毕')scaled_reshape = []image1 = scipy.misc.imread(image_name1, mode='RGB')image1 = cv2.resize(image1, (image_size, image_size), interpolation=cv2.INTER_CUBIC)image1 = facenet.prewhiten(image1)scaled_reshape.append(image1.reshape(-1,image_size,image_size,3))emb_array1 = np.zeros((1, embedding_size))emb_array1[0, :] = sess.run(embeddings, feed_dict={images_placeholder: scaled_reshape[0], phase_train_placeholder: False })[0]image2 = scipy.misc.imread(image_name2, mode='RGB')image2 = cv2.resize(image2, (image_size, image_size), interpolation=cv2.INTER_CUBIC)image2 = facenet.prewhiten(image2)scaled_reshape.append(image2.reshape(-1,image_size,image_size,3))emb_array2 = np.zeros((1, embedding_size))emb_array2[0, :] = sess.run(embeddings, feed_dict={images_placeholder: scaled_reshape[1], phase_train_placeholder: False })[0]dist = np.sqrt(np.sum(np.square(emb_array1[0]-emb_array2[0])))print("128维特征向量的欧氏距离:%f "%dist)

代码的逻辑就是
1. 先导入模型参数
2. 然后导入两张图片,分别获取其经过模型后得到的128维特征向量
3. 最后计算两个向量的欧氏距离

代码中有几个参数:
* image_size:图片长宽尺寸,这里要求输入的图片是长宽相等的,但是不要求两张人脸图大小一致,这里设置的尺寸是代码中会将人脸图读取后重新拉伸压缩成这个大小,这个尺寸最好比200大,太小了会运行失败
* modeldir:预训练好的模型路径
* image_name1:第一张人脸图的图片名
* image_name2:第二张人脸图的图片名

实验

给两个不同人的人脸图片,得到的结果如下:

终端运行输出

如果比较两个相同的人脸图片,得到的距离会是零点几;如果是两张一样的图,得到的距离会是0,符合要求。

这里有我的工程代码:https://github.com/Cloudox/facenet_distance


查看作者首页

原创粉丝点击