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