126 OpenCV DNN 基于残差网络的人脸检测
代码
import cv2 as cv
model_bin = "../models/face_detector/opencv_face_detector_uint8.pb";
config_text = "../models/face_detector/opencv_face_detector.pbtxt";
# load tensorflow model
net = cv.dnn.readNetFromTensorflow(model_bin, config=config_text)
image = cv.imread("../images/persons.png")
h = image.shape[0]
w = image.shape[1]
# 获得所有层名称与索引
layerNames = net.getLayerNames()
lastLayerId = net.getLayerId(layerNames[-1])
lastLayer = net.getLayer(lastLayerId)
print(lastLayer.type)
# 人脸检测
blobImage = cv.dnn.blobFromImage(image, 1.0, (300, 300), (104.0, 177.0, 123.0), False, False);
net.setInput(blobImage)
cvOut = net.forward()
# Put efficiency information.
t, _ = net.getPerfProfile()
label = 'Inference time: %.2f ms' % (t * 1000.0 / cv.getTickFrequency())
cv.putText(image, label, (0, 15), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0))
# 绘制检测矩形
for detection in cvOut[0,0,:,:]:
score = float(detection[2])
objIndex = int(detection[1])
if score > 0.5:
left = detection[3]*w
top = detection[4]*h
right = detection[5]*w
bottom = detection[6]*h
# 绘制
cv.rectangle(image, (int(left), int(top)), (int(right), int(bottom)), (255, 0, 0), thickness=2)
cv.putText(image, "score:%.2f"%score, (int(left), int(top)), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1)
cv.imshow('face-detection-demo', image)
cv.waitKey(0)
cv.destroyAllWindows()
实验结果
解释
OpenCV在DNN模块中提供了基于残差SSD网络训练的人脸检测模型,该模型分别提供了tensorflow版本,caffe版本,torch版本模型文件,其中tensorflow版本的模型做了更加进一步的压缩优化,大小只有2MB左右,非常适合移植到移动端使用,实现人脸检测功能,而caffe版本的是fp16的浮点数模型,精准度更好。要先获得这些模型,只要下载OpenCV4.0源码之后,
打开运行sources\samples\dnn\face_detector\download_weights.py该脚本即可。
没有对比就没有伤害,同样一张图像,在OpenCV HAAR与LBP级联检测器中必须通过不断调整参数才可以检测出全部人脸,而通过使用该模型,基本在Python语言中基于OpenCV后台的推断,在25毫秒均可以检测出结果,网络支持输入size大小为300x300。
所有内容均来源于贾志刚老师的知识星球——OpenCV研习社,本文为个人整理学习,已获得贾老师授权,有兴趣、有能力的可以加入贾老师的知识星球进行深入学习。