1.安装opencv:
pip install opencv-python
xml文件下载:https://github.com/opencv/opencv/tree/master/data/haarcascades
2.代码
def face_detect_demo(self):
#读取
image = cv2.imread('E://pythonprogram//data//image3.jpg')
face_cascade = cv2.CascadeClassifier(r'E://pythonprogram//data//haarcascade_frontalface_default.xml')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 探测图片中的人脸
faces = face_cascade.detectMultiScale(
gray,
scaleFactor=1.15,
minNeighbors=5,
minSize=(5, 5),
flags=cv2.FONT_HERSHEY_SIMPLEX
)
print("发现{0}个人脸!".format(len(faces)))
for (x, y, w, h)in faces:
cv2.rectangle(image,(x,y),(x+w,y+w),(0,255,0),2)
cv2.imshow("Find Faces!", image)
cv2.waitKey(0)
结果