【OpenCV】126 OpenCV DNN 基于残差网络的人脸检测

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研习社,本文为个人整理学习,已获得贾老师授权,有兴趣、有能力的可以加入贾老师的知识星球进行深入学习。
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值