环境:opencv2.4,matplotlib2.02
OpenCV支持的目标检测的方法是利用样本的Haar特征进行的分类器训练,得到的级联分类器(Cascade Classification)
#coding:utf-8
import numpy as np
import cv2
import matplotlib.pyplot as plt
#级联分类器路径
cascpath = 'detect/haarcascade_frontalface_alt.xml'
facecascade = cv2.CascadeClassifier(cascpath)
img = cv2.imread('images/ioi2.jpg')
#plt.imshow(cv2.cvtColor(img,cv2.COLOR_BGR2RGB))
#plt.show()
def detect_faces_show(path):
img = cv2.imread(path)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
faces = facecascade.detectMultiScale(gray,scaleFactor=1.2,minNeighbors=5,minSize=(30,30),flags=cv2.CASCADE_SCALE_IMAGE)
print('fond faces:',len(faces))
for(x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(114,120,2),4)
plt.imshow(cv2.cvtColor(img,cv2.COLOR_BGR2RGB))
plt.show()
detect_faces_show('images/telangpu.jpg')
结果:
检测到14张人脸,检测效果还是不错的,但更多实验发现还是存在缺陷的,不同图片可能检测效果不同