检测代码
import cv2
import sys
imagePath = "timg.jpg" #包含人脸的图像文件
cascPath = "haarcascade_frontalface_default.xml" #参数配置文件
# 创建haar cascade
faceCascade = cv2.CascadeClassifier(cascPath)
# 读图像并转为灰度图像
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 检测图像中的人脸
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=8,
minSize=(30, 30) #移动窗口的大小
#flags = cv2.CV_HAAR_SCALE_IMAGE
)
print("Found {0} faces!".format(len(faces)))
# 根据上一步返回的值,画出矩形框
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)
cv2.imshow("Faces found", image)
cv2.waitKey(0)
配置文件参考
https://github.com/opencv/opencv/tree/master/data/haarcascades