Python OpenCV的SSD人脸检测器

SSD算法是一种基于深度学习的目标检测方法,可以应用在人脸检测上。OpenCV在3.3版本后开始引入基于深度学习的人脸检测器,目前实现的方式是在SSD算法的基础上实现的。OpenCV实现的SSD人脸检测器的骨干网络是ResNet-10,当前它提供了两个训练好的模型,一种是基于深度学习框架Caffe训练的模型,另一种是基于Tensorflow训练的模型。

可以在GitHub的OpenCV项目中获取训练好的模型。

opencv/samples/dnn/face_detector

model_file = "caffe/res10_300x300_ssd_iter_140000_fp16.caffemodel"
config_file = "caffe/deploy.prototxt"

拿到模型文件和配置文件

以使用Caffe训练后的模型文件为例,代码如下,使用笔记本电脑的摄像头,效果很不错。

import cv2

# opencv-python 3.4.8
# python 3.7
# OpenCV的SSD人脸检测器

# 设置参数同时载入模型
model_file = "caffe/res10_300x300_ssd_iter_140000_fp16.caffemodel"
config_file = "caffe/deploy.prototxt"
net = cv2.dnn.readNetFromCaffe(config_file, model_file)
# 阈值
threshold = 0.9

# 加载摄像头
cap = cv2.VideoCapture(0)

while (True):
    ret, frame = cap.read()
    img = frame
    frameHeight = img.shape[0]
    frameWidth = img.shape[1]

    # 预处理
    # To achieve the best accuracy run the model on BGR images
    # resized to 300x300 applying mean subtraction of values
    # (104, 177, 123) for each blue, green and red channels correspondingly.
    blob = cv2.dnn.blobFromImage(img, 1.0, (300, 300), [104, 177, 123], False, False)
    # 网络输入
    net.setInput(blob)
    detections = net.forward()

    for i in range(detections.shape[2]):
        detections_score = detections[0, 0, i, 2]
        # 与阈值做对比,同一个人脸该过程会进行多次
        if detections_score > 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)
            # 绘制矩形
            cv2.rectangle(img, (x1, y1), (x2, y2), (255, 0, 0), 2)

    cv2.imshow('frame_2', img)
    # 键盘q按下后会中止程序
    if cv2.waitKey(5) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

 

 

你可能感兴趣的:(opencv)