Haar级联分类器:
opencv提供了训练好的模型,xml类型,下载地址:
https://github.com/Itseez/opencv/tree/master/data/haarcascades
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 14 17:43:10 2019
@author: zfjuan
"""
import numpy as np
import cv2
# multiple cascades: https://github.com/Itseez/opencv/tree/master/data/haarcascades
face_cascade = cv2.CascadeClassifier('.\\data\\haarcascades\\haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('.\\data\\haarcascades\\haarcascade_eye.xml')
img = cv2.imread('.\\image\\keliamoniz1.jpg');
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY);
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
#人脸区域框
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
#在检测到的人脸区域内检测眼睛
eyes = eye_cascade.detectMultiScale(roi_gray)
for (ex,ey,ew,eh) in eyes:
#眼睛区域框
cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img,'Eye',(ex+x,ey+y), font, 0.5, (11,255,255), 1, cv2.LINE_AA)
#eyeglasses = eyeglasses_cascade.detectMultiScale(roi_gray)
#for (e_gx,e_gy,e_gw,e_gh) in eyeglasses:
# cv2.rectangle(roi_color,(e_gx,e_gy),(e_gx+e_gw,e_gy+e_gh),(0,0,255),2)
#roi_gray = gray[ey:ey+eh, ex:ex+ew]#
#roi_color = img[ey:ey+eh, ex:ex+ew]#
cv2.namedWindow('img', 1)
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()