只用22行代码完成对照片的人脸检测

可以从一张照片中检测出多张脸部,并保存在photos文件夹下。

代码如下:

import cv2
name = "test"
number = 0
image_path = './1.jpg'
casc_path = './haarcascades/haarcascade_frontalface_alt.xml'
face_cascade = cv2.CascadeClassifier(casc_path)
# 加载图片
image = cv2.imread(image_path)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 从图片上检测人脸数
faces = face_cascade.detectMultiScale(
gray,
scaleFactor=1.25,
minNeighbors=2,
minSize=(30, 30),
)
print('找到 {0} 张脸!'.format(len(faces)))
# 在图片上标示人脸并保存到photos
for (x, y, w, h) in faces:
number+=1
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.imwrite("photos/{}.{}.jpg".format(name, number), gray[y:y + h, x:x + w])
cv2.imshow("Faces have found", image)
cv2.imwrite("./face_detection.jpg", image)
cv2.waitKey(0)
cv2.destroyAllWindows()

注意:

  本代码在ipython notebook下调试成功,使用python 3 版本,需要安装cv2 类库(3.4)

  pip install opency_python 

  可以使用修改haarcascades过滤器调整识别参数,会有不同的识别结果,

       haarcascades各种xml过滤器文件可以在opencv 的/data/haarcascades/文件下

  opencv下载地址:

  https://github.com/opencv/opencv/releases/tag/3.4.0

  如将代码中gray[y:y + h, x:x + w]的gray替换成image即可获得彩色图片。

原文地址:https://www.cnblogs.com/windel/p/8371399.html