OpenCV DNN
之前的opencv haar和dlib人脸检测。
现在深度学习不断发展,基于深度学习的人脸检测算法也在不断更新。OpenCV实现深度学习人脸检测是从OpenCV3.3版本后开始引入,算法出自论文《SSD: Single Shot MultiBox Detector》。Dlib也已经实现了。
Haar-Cascade,HOG-SVM,深度学习正是代表着人脸检测乃至目标检测的三个时代。他们的对比可以看这篇博客。
依据那个Learn OpenCV网站博主Vikas Gupta博士评测,OpenCV Dnn没啥缺点。下面是一些实现。确实比之前的准确率更高。采用的是TensorFlow实现的8位量化版本(2.7MB)。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File : opencv_dnn.py
# @Author: Shang
# @Date : 2020/6/13
from __future__ import division
import cv2
def detectFaceOpenCVDnn(net, frame):
blob = cv2.dnn.blobFromImage(frame, 1.0, (300, 300), [104, 117, 123], False, False)
frameHeight = frame.shape[0]
frameWidth = frame.shape[1]
net.setInput(blob)
detections = net.forward()
bboxes = []
for i in range(detections.shape[2]):
confidence = detections[0, 0, i, 2]
if confidence > conf_threshold:
x1 = int(detections[0, 0, i, 3] * frameWidth)
y1 = int(detections[0, 0, i, 4] * frameHeight)
x2 = int(detections[0, 0, i, 5] * frameWidth)
y2 = int(detections[0, 0, i, 6] * frameHeight)
bboxes.append([x1, y1, x2, y2])
return bboxes
if __name__ == '__main__':
# 加载人脸检测器
modelFile = "opencv_face_detector_uint8.pb"
configFile = "opencv_face_detector.pbtxt"
net = cv2.dnn.readNetFromTensorflow(modelFile, configFile)
conf_threshold = 0.7
print('Loading...')
# 输入图片
path = r'C:\Users\lenovo\Desktop\3.jpg'
img = cv2.imread(path)
# img = cv2.resize(img, (200, 200))
bboxes= detectFaceOpenCVDnn(net, img)
frameHeight = img.shape[0]
if len(bboxes)==0:
output=[]
print('抱歉,未检测到人脸')
else:
for i in bboxes:
img = cv2.rectangle(img, (i[0], i[1]), (i[2], i[3]), (171, 207, 49), int(round(frameHeight / 120)), 8)
# img = cv2.putText(img, str(j), (i[0], i[3]+15), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 142, 255), 1, cv2.LINE_AA)
print(bboxes)
cv2.imshow("Face Detection Comparison", img)
cv2.waitKey(0)
针对侧脸:
dlib和opencv haar都没有识别出。但是DNN能识别出。
针对多人,而且光线不充足情况:
dlib识别结果:
OpenCV haar识别结果:
DNN识别结果:识别出人脸更多!!!并且针对有许多遮挡的都能识别。
需要的人脸检测器:
链接:https://pan.baidu.com/s/1yew-310bNC8KhFn3Y3DmxQ
提取码:s0fj
完整代码见my github