基于OpenCV4的人脸检测

近期在研究人脸识别相关的技术方案,由于小企业没有那么大的成本去训练自己的模型,目前选用了OpenCV4,基于Caffe的模型,之所以选择Caffe,是因为参考了业界的大佬们对比后的结论,Caffe的模型更加精准,以下为步骤

  1. 首先这里使用的anaconda3进行的环境配置,操作系统使用的Ubuntu20.04,如果环境不一致出现了问题,请自行搜索排查
  2. 安装好anaconda之后,需要安装Python 3.7,太高版本可能会导致一些不兼容的问题
  3. 安装opencv的依赖库 sudo apt-get install libopencv-*
  4. 安装caffe conda install caffe
  5. 安装opencv4 conda install -c conda-forge opencv=4.1.0
  6. 下载模型 首先需要把openCV大代码clone下来, git clone https://github.com/opencv/opencv.git 因为这里需要用到example中下载模型文件, 然后去目录 opencv/samples/dnn/face_detector中,运行 download_weights.py,会自动下载模型文件
  7. 示例代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#coding=utf-8
import numpy as np
import cv2,os,time

def show_detections(image,detections):
h,w,c=image.shape
for i in range(0, detections.shape[2]):
confidence = detections[0, 0, i, 2]
if confidence >0.6:
box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
(startX, startY, endX, endY) = box.astype("int")

text = "{:.2f}%".format(confidence * 100)
y = startY - 10 if startY - 10 > 10 else startY + 10
cv2.rectangle(image, (startX, startY), (endX, endY),
(0, 255,0), 1)
cv2.putText(image, text, (startX, y),
cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 255, 0), 2)
return image

def detect_img(net,image):
blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 1.0,
(300, 300), (104.0, 177.0, 123.0))
net.setInput(blob)
start=time.time()
detections = net.forward()
end=time.time()
print(end-start)
return show_detections(image,detections)

def test_dir(net,dir="images"):
files=os.listdir(dir)
for file in files:
filepath=dir+"/"+file
img=cv2.imread(filepath)
showimg=detect_img(net,img)
cv2.imshow("img",showimg)
cv2.waitKey()

def test_camera(net):
cap=cv2.VideoCapture(0)
while True:
ret,img=cap.read()
if not ret:
break
showimg=detect_img(net,img)
cv2.imshow("img",showimg)
cv2.waitKey(1)

if __name__=="__main__":
net = cv2.dnn.readNetFromCaffe("deploy.prototxt","res10_300x300_ssd_iter_140000_fp16.caffemodel")
#net =cv2.dnn.readNetFromTensorflow("opencv_face_detector_uint8.pb","opencv_face_detector.pbtxt")
#test_dir(net)
test_camera(net)
Author: Gavin Zhao
Link: https://www.gavinz.xyz/2020/12/04/基于opencv4的人脸检测/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.