import cv2
abs_path = cv2.__file__
xml_path = abs_path.rsplit("/",1)[0] + "/data/haarcascade_frontalface_default.xml"
# 加载人脸检测器
face_cascade = cv2.CascadeClassifier(xml_path)
# 加载图像
img = cv2.imread('/media/datasets/face/liuyigei_duo.png')
# 将图像转换为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 在灰度图像中检测人脸
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=6, flags=0, minSize=(100, 100))
# 在图像中绘制矩形框以标记人脸
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
cv2.imwrite("face_liuyifei.jpg", img)
结果图片
haarcascade_frontalface_default.xml 下载地址:
https://github.com/opencv/opencv/tree/master/data/haarcascades