OpenCV-Python 人脸检测

path

中文文档: https://www.cnblogs.com/Undo-self-blog/p/8423851.html

'''
@File        :   index.py
@CreateTime  :   2019/03/27 11:36:12
@Author      :   William
@Version     :   1.0
@Desc        :   人脸检测
'''
import cv2

# 共11张脸
imagePath = 'path.jpg'  # 待识别的图像

# 获取训练好的人脸的参数数据,这里直接从GitHub上使用默认值
# 训练数据参考地址:
# https://github.com/opencv/opencv/tree/master/data/haarcascades
face_cascade = cv2.CascadeClassifier('./haarcascade_frontalface_default.xml')
# 读取图片
img = cv2.imread(imagePath)
# 灰度转换的作用就是:转换成灰度的图片的计算强度得以降低。
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 探测人脸 根据训练的数据来对新图片进行识别的过程。
faces = face_cascade.detectMultiScale(
    gray,
    scaleFactor=1.15,
    minNeighbors=5,
    minSize=(5, 5),
    flags=cv2.CASCADE_SCALE_IMAGE
)
print('发现{0}个人脸!'.format(len(faces)))

for(x, y, w, h) in faces:
    # 画图
    # cv2.rectangle(img, (x, y), (x+w, y+w), (0, 255, 0), 2)
    cv2.circle(img, (int((x+x+w)/2), int((y+y+h)/2)), int(w/2), (0, 255, 0), 2)


def zh_ch(string):
    return string.encode("gbk").decode(errors="ignore")


# 编辑完的图像要么直接的被显示出来,要么就保存到物理的存储介质。
cv2.imshow(zh_ch('标题'), img)
# Image
cv2.waitKey(0)
cv2.destroyWindow('image')

效果如下:
微信图片_20190416104220

猜你喜欢

转载自blog.csdn.net/qq_24504591/article/details/89328879