忘了哪里看到的了,保存一个,亲测可用,简单有效,有时间改进一下。
import cv2
img = cv2.imread(r"C:\Users\lbship\Desktop\cc.jpg")
color = (0, 255, 0)
grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
classfier = cv2.CascadeClassifier(r"C:\Users\lbship\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\cv2\data\haarcascade_frontalface_alt2.xml")
faceRects = classfier.detectMultiScale(grey, scaleFactor=1.2, minNeighbors=3, minSize=(32, 32))
#scaleFactor 是 图像的缩放因子minNeighbors 为每一个级联矩形应该保留的邻近个数,可以理解为一个人周边有几个人脸
if len(faceRects) > 0: # 大于0则检测到人脸
for faceRect in faceRects: # 单独框出每一张人脸
x, y, w, h = faceRect
cv2.rectangle(img, (x - 10, y - 10), (x + w + 10, y + h + 10), color, 3) # 控制绿色框的粗细
# 写入图像
cv2.imwrite('./a1aa.jpg', img)