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

https://blog.csdn.net/guyuealian/article/details/84896733

    人脸检测和人脸识别技术算是目前人工智能方面应用最成熟的技术了。本博客将利用mtcnn和faceNet搭建一个实现人脸检测和人脸识别的系统。基本思路也很简单,先利用mtcnn的进行人脸检测,当然也可以使用其他的人脸检测方法,如Dilb,OpenCV,OpenFace人脸检测等等,然后再利用faceNet进行人脸识别,faceNet可简单看成是提取人脸特征的CNN网络,这个特征就是embadding了,有了人脸特征embadding,最后一步,就只需要与数据库人脸特征进行相似性比较,即可完成人脸识别的任务。

   老规矩,先上Github源码:记得给个“Star”哦,不然,对不起我的苦劳!!!

   本博客Github源码: https://github.com/PanJinquan/Face_Detection_Recognition/tree/master/faceRecognition


目录

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

一、项目结构:

二、实现流程

三、MTCNN人脸检测

四、faceNet人脸识别

五、产生数据库

(1)制作人脸数据图库:

(2)生成embedding数据库

六、人脸识别过程

(1)加载人脸数据库

(2)进行人脸检测

(3)人脸识别(比较相似性)

(4)人脸识别效果

七、参考资料:


一、项目结构:

    打开FaceNet Github地址: https://github.com/davidsandberg/facenet,把我们需要的文件拷贝到自己独立的工程中,(1)align文件夹,(2)facenet.py文件:

align:这个文件夹是从facenet中拷贝的,https://github.com/davidsandberg/facenet/tree/master/src/align,主要是MTCNN人脸检测的相关文件

facenet.py:这个Python文件也是从facenet中拷贝的,https://github.com/davidsandberg/facenet/blob/master/src/facenet.py

    其他文件介绍

dataset:这个文件夹主要存放数据,如人脸数据库

utils:这个文件是工具类文件,用于文件读写,图像相关操作的函数方法等

models:存放facenet预训练模型,下载地址

Pre-trained models:

Model nameLFW accuracyTraining datasetArchitecture
20180408-1029000.9905CASIA-WebFaceInception ResNet v1
20180402-1147590.9965VGGFace2Inception ResNet v1

NOTE: If you use any of the models, please do not forget to give proper credit to those providing the training dataset as well.

二、实现流程

1.通过MTCNN人脸检测模型,从照片中提取人脸图像。

2.把人脸图像输入到FaceNet,计算Embedding的特征向量。

3.比较特征向量间的欧式距离,判断是否为同一人,例如当特征距离小于1的时候认为是同一个人,特征距离大于1的时候认为是不同人。


三、Multi-task CNN(MTCNN)人脸检测

    人脸检测方法很多,如Dilb,OpenCV,OpenFace人脸检测等等,这里使用MTCNN进行人脸检测,一方面是因为其检测精度确实不错,另一方面facenet工程中,已经提供了用于人脸检测的mtcnn接口。  MTCNN是多任务级联CNN的人脸检测深度学习模型,该模型中综合考虑了人脸边框回归和面部关键点检测。在facenet工程中的位置是align/detect_face.py ,它的参数模型也保存在align文件夹下,分别是det1.npy,det2.npy,det3.npy

参考资料:

https://blog.csdn.net/qq_28618765/article/details/78127967

https://blog.csdn.net/gubenpeiyuan/article/details/80475307

    MTCNN一个深度卷积多任务的框架,这个框架利用了检测和对准之间固有的关系来增强他们的性能。特别是,在预测人脸及脸部标记点的时候,通过3个CNN级联的方式对任务进行从粗到精的处理。

Stage 1:使用P-Net是一个全卷积网络,用来生成候选窗和边框回归向量(bounding box regression vectors)。使用Bounding box regression的方法来校正这些候选窗,使用非极大值抑制(NMS)合并重叠的候选框。全卷积网络和Faster R-CNN中的RPN一脉相承。

Stage 2:使用N-Net改善候选窗。将通过P-Net的候选窗输入R-Net中,拒绝掉大部分false的窗口,继续使用Bounding box regression和NMS合并。

Stage 3:最后使用O-Net输出最终的人脸框和特征点位置。和第二步类似,但是不同的是生成5个特征点位置。

    这里提供一个使用MTCNN进行人脸检测的方法:


 
 
  1. def detection_face(img):
  2. minsize = 20 # minimum size of face
  3. threshold = [ 0.6, 0.7, 0.7] # three steps's threshold
  4. factor = 0.709 # scale factor
  5. print( 'Creating networks and loading parameters')
  6. with tf.Graph().as_default():
  7. # gpu_memory_fraction = 1.0
  8. # gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_memory_fraction)
  9. # sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False))
  10. sess = tf.Session()
  11. with sess.as_default():
  12. pnet, rnet, onet = detect_face.create_mtcnn(sess, None)
  13. bounding_boxes, points = detect_face.detect_face(img, minsize, pnet, rnet, onet, threshold, factor)
  14. return bounding_boxes,points

    当然,实际应用中,建议还是封装成一个类吧,方面初始化和单独调用:


 
 
  1. class Facedetection:
  2. def __init__(self):
  3. self.minsize = 20 # minimum size of face
  4. self.threshold = [ 0.6, 0.7, 0.7] # three steps's threshold
  5. self.factor = 0.709 # scale factor
  6. print( 'Creating networks and loading parameters')
  7. with tf.Graph().as_default():
  8. # gpu_memory_fraction = 1.0
  9. # gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_memory_fraction)
  10. # sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False))
  11. sess = tf.Session()
  12. with sess.as_default():
  13. self.pnet, self.rnet, self.onet = detect_face.create_mtcnn(sess, None)
  14. def detect_face(self,image):
  15. bounding_boxes, points = detect_face.detect_face(image, self.minsize, self.pnet, self.rnet, self.onet, self.threshold, self.factor)
  16. return bounding_boxes, points

四、faceNet人脸识别

    FaceNet Github地址: https://github.com/davidsandberg/facenet

    参考资料:https://blog.csdn.net/fire_light_/article/details/79592804

    Google工程师Florian Schroff,Dmitry Kalenichenko,James Philbin提出了人脸识别FaceNet模型,该模型没有用传统的softmax的方式去进行分类学习,而是抽取其中某一层作为特征,学习一个从图像到欧式空间的编码方法,然后基于这个编码再做人脸识别、人脸验证和人脸聚类等。

    FaceNet主要用于验证人脸是否为同一个人,通过人脸识别这个人是谁。FaceNet的主要思想是把人脸图像映射到一个多维空间,通过空间距离表示人脸的相似度。同个人脸图像的空间距离比较小,不同人脸图像的空间距离比较大。这样通过人脸图像的空间映射就可以实现人脸识别,FaceNet中采用基于深度神经网络的图像映射方法和基于triplets(三联子)的loss函数训练神经网络,网络直接输出为128维度的向量空间。

    FaceNet的网络结构如下图所示,其中Batch表示人脸的训练数据,接下来是深度卷积神经网络,然后采用L2归一化操作,得到人脸图像的特征表示,最后为三元组(Triplet Loss)的损失函数。

    下面是鄙人已经封装好的facenetEmbedding类,其中类函数get_embedding(self,images)方法用于提取facenet的人脸特征embadding,有了人脸embadding特征,就可以比较人脸相似性啦!


 
 
  1. class facenetEmbedding:
  2. def __init__(self,model_path):
  3. self.sess = tf.InteractiveSession()
  4. self.sess.run(tf.global_variables_initializer())
  5. # Load the model
  6. facenet.load_model(model_path)
  7. # Get input and output tensors
  8. self.images_placeholder = tf.get_default_graph().get_tensor_by_name( "input:0")
  9. self.tf_embeddings = tf.get_default_graph().get_tensor_by_name( "embeddings:0")
  10. self.phase_train_placeholder = tf.get_default_graph().get_tensor_by_name( "phase_train:0")
  11. def get_embedding(self,images):
  12. feed_dict = {self.images_placeholder: images, self.phase_train_placeholder: False}
  13. embedding = self.sess.run(self.tf_embeddings, feed_dict=feed_dict)
  14. return embedding
  15. def free(self):
  16. self.sess.close()

五、产生数据库

   既然是人脸识别,数据库肯定要有已知人脸的数据库,不然怎么知道被检测的人脸是哪位大神,所以先制作人脸数据库。

(1)制作人脸数据图库:

    把相关大神的人像收集放在dataset/images文件夹下:

 

特别说明:

  1. 这里只收集了4张胡歌和4张周杰伦的单人照片,
  2. 注意制作人脸数据图库时,所使用的照片必须是单人照片!!!
  3. 若需要新增图库,只需在dataset/images下,新建一个文件夹,如,新增“xietingfeng”(谢霆锋)的文件夹,然后把谢霆锋的单人照片放在里面即可,图片名称可以是任意
  4. 函数image_list,names_list=file_processing.gen_files_labels(images_dir,postfix='jpg')可以获取目录images_dir下所有文件,包括子目录下的所有文件路径(image_list),其中names_list就是子目录的文件名,一般子目录作为样本的标签。

    然后使用下面的代码,进行人脸检测,把人脸都crop下来,并保存在项目dataset\emb_face中,这些emb_face人脸数据图库将用于生成embedding数据库


 
 
  1. def create_face(images_dir, out_face_dir):
  2. '''
  3. 生成人脸数据图库,保存在out_face_dir中,这些数据库将用于生成embedding数据库
  4. :param images_dir:
  5. :param out_face_dir:
  6. :return:
  7. '''
  8. # image_list=file_processing.get_files_list(images_dir, postfix='jpg')
  9. image_list,names_list=file_processing.gen_files_labels(images_dir,postfix= 'jpg')
  10. face_detect=face_recognition.Facedetection()
  11. for image_path ,name in zip(image_list,names_list):
  12. image=image_processing.read_image(image_path, resize_height= 0, resize_width= 0, normalization= False)
  13. # 获取 判断标识 bounding_box crop_image
  14. bounding_box, points = face_detect.detect_face(image)
  15. bounding_box = bounding_box[:, 0: 4].astype(int)
  16. bounding_box=bounding_box[ 0,:]
  17. print( "face box:{}".format(bounding_box))
  18. face_image = image_processing.crop_image(image,bounding_box)
  19. # image_processing.show_image("face", face_image)
  20. # image_processing.show_image_box("face",image,bounding_box)
  21. out_path=os.path.join(out_face_dir,name)
  22. face_image=image_processing.resize_image(face_image, resize_height, resize_width)
  23. if not os.path.exists(out_path):
  24. os.mkdir(out_path)
  25. basename=os.path.basename(image_path)
  26. out_path=os.path.join(out_path,basename)
  27. image_processing.save_image(out_path,face_image)
  28. # cv2.waitKey(0)

(2)生成embedding数据库

    有了人脸数据图库,就可以生成embedding数据库(人脸特征),后面待检测识别的人脸,只需要与这些embedding数据库(人脸特征)进行相似性比较,就可以识别人脸啦!!!!


 
 
  1. def create_embedding(model_path, emb_face_dir, out_emb_path, out_filename):
  2. '''
  3. 产生embedding数据库,保存在out_data_path中,这些embedding其实就是人脸的特征
  4. :param model_path:
  5. :param emb_face_dir:
  6. :param out_emb_path:
  7. :param out_filename:
  8. :return:
  9. '''
  10. face_net = face_recognition.facenetEmbedding(model_path)
  11. # image_list=file_processing.get_files_list(emb_face_dir,postfix='jpg')
  12. image_list,names_list=file_processing.gen_files_labels(emb_face_dir,postfix= 'jpg')
  13. images= image_processing.get_images(image_list,resize_height,resize_width,whiten= True)
  14. compare_emb = face_net.get_embedding(images)
  15. np.save(out_emb_path, compare_emb)
  16. # 可以选择保存image_list或者names_list作为人脸的标签
  17. # 测试时建议保存image_list,这样方便知道被检测人脸与哪一张图片相似
  18. file_processing.write_data(out_filename, image_list, model= 'w')

六、人脸识别过程

(1)加载人脸数据库

     把上面制作的,已知的人脸数据库加载进来:


 
 
  1. def load_dataset(dataset_path,filename):
  2. '''
  3. 加载人脸数据库
  4. :param dataset_path: embedding.npy文件(faceEmbedding.npy)
  5. :param filename: labels文件路径路径(name.txt)
  6. :return:
  7. '''
  8. compare_emb=np.load(dataset_path)
  9. names_list=file_processing.read_data(filename)
  10. return compare_emb,names_list

(2)进行人脸检测


 
 
  1. def face_recognition_image(model_path,dataset_path, filename,image_path):
  2. # 加载数据库的数据
  3. dataset_emb,names_list=load_dataset(dataset_path, filename)
  4. # 初始化mtcnn人脸检测
  5. face_detect=face_recognition.Facedetection()
  6. # 初始化facenet
  7. face_net=face_recognition.facenetEmbedding(model_path)
  8. image=image_processing.read_image(image_path)
  9. # 进行人脸检测,获得bounding_box
  10. bounding_box, points = face_detect.detect_face(image)
  11. bounding_box = bounding_box[:, 0: 4].astype(int)
  12. # 获得人脸区域
  13. face_images = image_processing.get_crop_images(image,bounding_box,resize_height,resize_width,whiten= True)
  14. # image_processing.show_image("face", face_images[0,:,:,:])
  15. pred_emb=face_net.get_embedding(face_images)
  16. pred_name=compare_embadding(pred_emb, dataset_emb, names_list)
  17. # 在图像上绘制人脸边框和识别的结果
  18. bgr_image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
  19. image_processing.cv_show_image_text( "face_recognition", bgr_image,bounding_box,pred_name)
  20. cv2.waitKey( 0)

(3)人脸识别(比较相似性)

    比较特征向量间的欧式距离


 
 
  1. def compare_embadding(pred_emb, dataset_emb, names_list):
  2. # 为bounding_box 匹配标签
  3. pred_num = len(pred_emb)
  4. dataset_num = len(dataset_emb)
  5. pred_name = []
  6. for i in range(pred_num):
  7. dist_list = []
  8. for j in range(dataset_num):
  9. dist = np.sqrt(np.sum(np.square(np.subtract(pred_emb[i, :], dataset_emb[j, :]))))
  10. dist_list.append(dist)
  11. min_value = min(dist_list)
  12. if (min_value > 0.65):
  13. pred_name.append( 'unknow')
  14. else:
  15. pred_name.append(names_list[dist_list.index(min_value)])
  16. return pred_name

(4)人脸识别效果

    一切准备好了,开始run:


 
 
  1. if __name__== '__main__':
  2. model_path= 'models/20180408-102900'
  3. dataset_path= 'dataset/emb/faceEmbedding.npy'
  4. filename= 'dataset/emb/name.txt'
  5. image_path= 'dataset/test_images/1.jpg'
  6. face_recognition_image(model_path, dataset_path, filename,image_path)

    说明:

为了方便测试,  这里以文件的路径作为人脸label,这样方便知道被检测人脸与哪一张图片最相似

./dataset/emb_face\huge\huge_1.jpg
./dataset/emb_face\huge\huge_2.jpg
./dataset/emb_face\huge\huge_3.jpg
./dataset/emb_face\huge\huge_4.jpg
./dataset/emb_face\zhoujielun\zhoujielun_1.jpg
./dataset/emb_face\zhoujielun\zhoujielun_2.jpg
./dataset/emb_face\zhoujielun\zhoujielun_3.jpg
./dataset/emb_face\zhoujielun\zhoujielun_4.jpg

对应的label是:

huge
huge
huge
huge
zhoujielun
zhoujielun
zhoujielun
zhoujielun

七、参考资料:

【1】《如何应用MTCNN和FaceNet模型实现人脸检测及识别》http://www.uml.org.cn/ai/201806124.asp

 

如果你觉得该帖子帮到你,还望贵人多多支持,鄙人会再接再厉,继续努力的~

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值