Haar级联分类器
正常人的脸一定具备眼睛、鼻子、嘴巴等特征,每个特征都做成一个专门的检测分类器,所有分类器串起来,全部检测通过则判定为人脸。
分类器下载地址:
https://github.com/opencv/opencv/tree/master/data/haarcascades
import cv2 #读取待检测的图像 image = cv2.imread("./111.jpg") cv2.imshow("image",image) # 转灰度图 gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) # 获取级联分类器对象 faceCascade = cv2.CascadeClassifier('./haarcascades/haarcascade_frontalface_default.xml') # 检测 faces = faceCascade.detectMultiScale(gray,1.3,3) print("发现{}个人脸!".format(len(faces))) #绘制人脸框 for(x,y,w,h) in faces: cv2.rectangle(image,(x,y),(x+w,y+w),(0,0,255),2) #显示 cv2.imshow("result",image) cv2.waitKey(0)
运行结果:
SSD检测器
SSD检测器是基于深度学习一种检测方式,通过卷积神经网络对图像特征进行检测。
模型下载地址:
https://github.com/opencv/opencv/blob/master/samples/dnn/face_detector/weights.meta4
配置文件下载地址:
https://github.com/opencv/opencv/tree/master/samples/dnn/face_detector
import cv2 #载入模型 model_file = "res10_300x300_ssd_iter_140000_fp16.caffemodel" config_file = "deploy.prototxt" net = cv2.dnn.readNetFromCaffe(config_file,model_file) threshold = 0.9 #读取待检测的图像 img = cv2.imread("./112.jpg") cv2.imshow('img',img) frameHeight = img.shape[0] frameWidth = img.shape[1] #预处理 blob = cv2.dnn.blobFromImage(img,0.8,(505,505),[104,117,123],False,False) #检测 net.setInput(blob) detections = net.forward() #标记人脸区域 for i in range(detections.shape[2]): detection_score = detections[0,0,i,2] if detection_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),(0,0,255),2) cv2.imshow('result',img) cv2.waitKey(0)
运行结果:
Dlib检测器
dlib依赖于cmake和scikit-image,先把依赖装了再装dlib.
import cv2 import dlib #读取待检测的图像 img = cv2.imread("./timg.jpg") cv2.imshow('img',img) #获取检测器 detector = dlib.get_frontal_face_detector() #检测 faceRects = detector(img,1) #标记人脸区域 for faceRect in faceRects: x1 = faceRect.left() y1 = faceRect.top() x2 = faceRect.right() y2 = faceRect.bottom() cv2.rectangle(img, (x1, y1), (x2, y2), (0, 0, 255), 2) cv2.imshow('result',img) cv2.waitKey(0)
运行结果: