代码
import cv2 as cv
img = cv.imread("./lena.jpg")
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
face_cascade = cv.CascadeClassifier('/usr/local/share/opencv4/haarcascades/haarcascade_frontalface_default.xml')
eye_cascade = cv.CascadeClassifier('/usr/local/share/opencv4/haarcascades/haarcascade_eye.xml')
face = face_cascade.detectMultiScale(img, 1.3, 5)
for (x, y, w, h) in face:
cv.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
roi_gray = gray[y:y+h, x:x+w]
roi_img = img[y:y+h, x:x+w]
eyes = eye_cascade.detectMultiScale(roi_gray)
for (ex, ey, ew, wh) in eyes:
cv.rectangle(roi_img, (ex, ey), (ex+ew, ey+wh), (0, 255,0), 2)
cv.imwrite('res.jpg', img)
效果