在OpenCV中,人脸检测使用的是cv2.CascadeClassifier.detectMultiScale()函数,它可以检测出图片中所有的人脸。该函数由分类器对象调用,其语法格式为:
objects = cv2.CascadeClassifier.detectMultiScale(image[, scaleFactor[, minNeighbors[, flags[, minSize[, maxSize]]]]])
各个参数及返回值的含义为:
import cv2
# 读取待检测的图像
image = cv2.imread('dface3.jpg')
# 获取XML文件,加载人脸检测器
faceCascade = cv2.CascadeClassifier('D:\Software\Anaconda\Lib\site-packages\cv2\data\haarcascade_frontalface_default.xml')
# 转为灰度图像
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 调用函数 detectMultiScale
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.15,
minNeighbors=5,
minSize=(5,5)
)
print(faces)
# 逐个标注人脸
for(x,y,w,h) in faces:
# 矩形标注
#cv2.rectangle(image, (x,y), (x+w,y+h), (0,255,0), 2)
# 圆形标注
cv2.circle(image, (int((x+x+w)/2), int((y+y+h)/2)), int(w/2), (0, 255, 0), 2)
# 显示结果
cv2.imshow("Face Detection", image)
# 保存检测结果
cv2.imwrite("re.jpg", image)
cv2.waitKey(0)
cv2.destroyAllWindows()