SSD:
SSD是一种基于深度学习的目标检测算法,opencv在3.3版本以后将其引入作为基于深度学习的人脸检测器;
opencv实现的SSD人脸检测器的骨干网络是REsNet-10,当前它提供了两个训练好的模型:基于深度学习框架caffe训练的模型和基于TensorFlow训练的模型
下载地址:https://github.com/opencv/opencv/blob/master/samples/dnn/face_detector/weights.meta4
下载地址:
https://github.com/opencv/opencv/tree/master/samples/dnn/face_detector
face_detector文件分析:
deploy.prototxt:调用.caffemodel时的测试网络文件
how_to_train_face_detector.txt:如何使用自定义数据集来训练网络的说明
solver.prototxt:超参数文件
test.prototxt:测试网络文件
train.prototxt:训练网络文件
(1)基于深度学习框架caffe训练的模型导入
config_file = "face_detector/deploy.prototxt";
model_file = "face_detector/res10_300x300_ssd_iter_140000_fp16.caffemodel";
net = cv2.dnn.readNetFromCaffe(config_file, model_file)
(2)基于TensorFlow训练的模型导入
config_file = "face_detector/opencv_face_detect.pbtxt";
model_file = "face_detector/opencv_face_detect_uint8.pb";
net = cv2.dnn.readNetFromTensorflow(model_file, config_file)
完整测试示例:
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 16 09:27:01 2019
@author: zfjua
"""
import cv2 as cv
from cv2 import dnn
net = dnn.readNetFromCaffe('./data/face_detector/deploy.prototxt', './data/face_detector/res10_300x300_ssd_iter_140000_fp16.caffemodel')
inWidth = 300
inHeight = 300
confThreshold = 0.5
frame = cv.imread('.\\image\\test.png')
cols = frame.shape[1]
rows = frame.shape[0]
net.setInput(dnn.blobFromImage(frame, 1.0, (inWidth, inHeight), (104.0, 177.0, 123.0), False, False))
detections = net.forward()
# perf_stats = net.getPerfProfile()
# print('Inference time, ms: %.2f' % (perf_stats[0] / cv.getTickFrequency() * 1000))
for i in range(detections.shape[2]):
confidence = detections[0, 0, i, 2]
if confidence > confThreshold:
xLeftBottom = int(detections[0, 0, i, 3] * cols)
yLeftBottom = int(detections[0, 0, i, 4] * rows)
xRightTop = int(detections[0, 0, i, 5] * cols)
yRightTop = int(detections[0, 0, i, 6] * rows)
cv.rectangle(frame, (xLeftBottom, yLeftBottom), (xRightTop, yRightTop), (0, 0, 255))
cv.imshow("detections", frame)
cv.waitKey(0)
cv.destroyAllWindows()