✨博客主页:米开朗琪罗~
✨博主爱好:羽毛球
✨年轻人要:Living for the moment(活在当下)!
推荐专栏:【图像处理】【千锤百炼Python】【深度学习】【排序算法】
OpenCV中有专门用来做人脸检测、人眼检测和微笑检测的工具。
在作者这个目录下:D:\anaconda\envs\keras21\Lib\site-packages\cv2\data
,(注:keras21是作者的虚拟环境,如果没创建虚拟环境,在anaconda下寻找Lib就可以)存在很多.xml文件,这些文件是预训练好的各器官的Haar特征。
从名字中就可以看出哪个文件是做什么的!
级联分类器:cv2.CascadeClassifier
检测函数:detectMultiScale
import cv2
# 定义人脸检测器、眼部检测器、微笑检测器
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') # 人脸检测
# eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascades_eye.xml') # 这个检测器不知道为啥用不了
lefteye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_lefteye_2splits.xml') # 左眼检测
righteye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_righteye_2splits.xml') # 右眼检测
smile_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascades_smile.xml') # 微笑检测
cap = cv2.VideoCapture(0)
while(True):
ret, frame = cap.read()
# 人脸检测
faces = face_cascade.detectMultiScale(frame, minNeighbors=12)
img = frame
# 绘制人脸(蓝色框)
for(facex, facey, facew, faceh) in faces:
img = cv2.rectangle(img, (facex, facey), (facex + facew, facey + faceh), (255, 0, 0), 1)
face_area = img[facey: facey + faceh, facex: facex + facew] # 人脸区域
# 左眼检测(红色框)
lefteye = lefteye_cascade.detectMultiScale(face_area, minNeighbors=12)
# 绘制左眼(红色框)
for(lefteyex, lefteyey, lefteyew, lefteyeh) in lefteye:
cv2.rectangle(face_area, (lefteyex, lefteyey), (lefteyex + lefteyew, lefteyey + lefteyeh), (0, 0, 255), 1)
# 右眼检测
righteye = righteye_cascade.detectMultiScale(face_area, minNeighbors=12)
# 绘制右眼(红色框)
for (righteyex, righteyey, righteyew, righteyeh) in righteye:
cv2.rectangle(face_area, (righteyex, righteyey), (righteyex + righteyew, righteyey + righteyeh), (0, 0, 255), 1)
# 微笑检测
smiles = smile_cascade.detectMultiScale(face_area, scaleFactor=1.16, minNeighbors=3, minSize=(1, 1), flags=cv2.CASCADE_SCALE_IMAGE)
# 绘制微笑(绿色框)
for (smilex, smiley, smilew, smileh) in smiles:
cv2.rectangle(face_area, (smilex, smiley), (smilex + smilew, smiley + smileh), (0, 255, 0), 1)
cv2.putText(img, 'smile', (smilex, smiley-7), 3, 1.2, (0, 255, 0), 2, cv2.LINE_AA) # 字体
cv2.imshow('detect', img)
if cv2.waitKey(5) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
haarcascades_eye.xml
和haarcascades_smile.xml
这两个分类器不知道为什么有时候好使有时候不好使!眼部检测用不了可以用左右眼分别检测,但微笑检测有时候也用不了,同样的程序昨天能用,今天就用不了了!摄像头也没有被占用!不知道是什么原因!