人脸检测方法有许多,比如opencv自带的人脸Haar特征分类器和dlib人脸检测方法等。对于opencv的人脸检测方法,有点是简单,快速;存在的问题是人脸检测效果不好。正面/垂直/光线较好的人脸,该方法可以检测出来,而侧面/歪斜/光线不好的人脸,无法检测。因此,该方法不适合现场应用。对于dlib人脸检测方法 ,效果好于opencv的方法,但是检测力度也难以达到现场应用标准。
MTCNN是基于深度学习的人脸检测方法,对自然环境中光线,角度和人脸表情变化更具有鲁棒性,人脸检测效果更好;同时,内存消耗不大,可以实现实时人脸检测。
代码如下:
- from scipy import misc
- import tensorflow as tf
- import detect_face
- import cv2
- import matplotlib.pyplot as plt
- %pylab inline
-
- minsize = 20
- threshold = [ 0.6, 0.7, 0.7 ]
- factor = 0.709
- gpu_memory_fraction=1.0
-
-
- print('Creating networks and loading parameters')
-
- with tf.Graph().as_default():
- gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_memory_fraction)
- sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False))
- with sess.as_default():
- pnet, rnet, onet = detect_face.create_mtcnn(sess, None)
-
- image_path = '/home/cqh/faceData/multi_face/multi_face3.jpg'
-
- img = misc.imread(image_path)
- bounding_boxes, _ = detect_face.detect_face(img, minsize, pnet, rnet, onet, threshold, factor)
- nrof_faces = bounding_boxes.shape[0]
- print('找到人脸数目为:{}'.format(nrof_faces))
-
- print(bounding_boxes)
-
- crop_faces=[]
- for face_position in bounding_boxes:
- face_position=face_position.astype(int)
- print(face_position[0:4])
- cv2.rectangle(img, (face_position[0], face_position[1]), (face_position[2], face_position[3]), (0, 255, 0), 2)
- crop=img[face_position[1]:face_position[3],
- face_position[0]:face_position[2],]
-
- crop = cv2.resize(crop, (96, 96), interpolation=cv2.INTER_CUBIC )
- print(crop.shape)
- crop_faces.append(crop)
- plt.imshow(crop)
- plt.show()
-
- plt.imshow(img)
- plt.show()
实验效果如下:
![](https://img-blog.csdn.net/20170828170742377?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvTXJfRXZhbkNoZW4=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
![](https://img-blog.csdn.net/20170828170751169?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvTXJfRXZhbkNoZW4=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
![](https://img-blog.csdn.net/20170828170757432?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvTXJfRXZhbkNoZW4=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
![](https://img-blog.csdn.net/20170828171455326?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvTXJfRXZhbkNoZW4=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
再上一组效果图:
![](https://img-blog.csdn.net/20170828171159300?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvTXJfRXZhbkNoZW4=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
![](https://img-blog.csdn.net/20170828171206460?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvTXJfRXZhbkNoZW4=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
关于MTCNN,更多资料可以参见:https://kpzhang93.github.io/MTCNN_face_detection_alignment/index.html?from=timeline&isappinstalled=1