import cv2
import numpy as np
# load xml
face_xml = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_xml = cv2.CascadeClassifier('haarcascade_eye.xml')
# load image
img = cv2.imread('face.jpg')
cv2.imshow('src', img)
# haar gray
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# detect faces: data, scale, size(>=5 pixels)
faces = face_xml.detectMultiScale(gray, 1.3, 5)
print('len(faces) = ', len(faces))
# draw
for (x, y, w, h) in faces:
# 框出蓝色的人脸
cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
# 高度:行(横坐标)
roi_face = gray[y : y + h, x : x + w]
roi_color = img[y : y + h, x : x + w]
# gray
eyes = eye_xml.detectMultiScale(roi_face)
print('len(eyes) = ', len(eyes))
for (ex, ey, ew, eh) in eyes:
# 框出绿色的眼睛
cv2.rectangle(roi_color, (ex, ey), (ex + ew, ey + eh), (0, 255, 0), 2)
cv2.imshow('dst', img)
cv2.waitKey(0)
检测出人脸与眼睛数目如下:
image.png
检测出的人脸与眼睛如下图所标示:
image.png
网友评论