据说MTCNN检测人脸十分靠谱,即使是侧脸也能检测得出,今天就查找资料做了个测试。有关MTCNN原理和训练等概不论述,只记录实现过程。
安装facenet,输入命令:
pip install facenet
安装完毕后找到detect_face.py文件目录,我的是win10系统,该文件在以下目录下:
C:\ProgramData\Anaconda3\Lib\site-packages\facenet\src\align
我就直接把align文件拷贝出来,和mtcnn.py文件放在一起,mtcnn.py文件内容为:
# coding=gbk
import tensorflow as tf
import align.detect_face
import cv2
minsize = 20 # minimum size of face
threshold = [ 0.6, 0.7, 0.7 ] # three steps's threshold
factor = 0.709 # scale factor
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 = align.detect_face.create_mtcnn(sess, None)
capture = cv2.VideoCapture(0)
while True:
ret, frame = capture.read()
if ret is True:
bounding_boxes, _ = align.detect_face.detect_face(frame, minsize, pnet, rnet, onet, threshold, factor)
for face_position in bounding_boxes:
face_position=face_position.astype(int)
cv2.rectangle(frame, (face_position[0], face_position[1]), (face_position[2], face_position[3]), (0, 255, 0), 2)
cv2.imshow("frame", frame)
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
c = cv2.waitKey(10)
if c == 27:
break
else:
break
在Windows下cmd进入命令行,找到mtcnn.py所在目录,输入命令:python mtcnn.py
注意插上USB摄像头,win10安装了Python,TensorFlow,opencv-python
该程序在台式机上可实时监测,在树莓派3b+上实时效果并不理想