CV:利用cv2自带两步法haarcascade_frontalface_default.xml、_smile.xml实现对人脸、笑脸同时检测
看了这种方法就改成了 实时动态显示的。
效果就不展示,羞涩脸。
直接上代码
# CV:利用cv2.CascadeClassifier级联分类器的haarcascade_frontalface_default.xml、haarcascade_smile.xml实现对人脸、笑脸同时检测——Jason niu
# https://github.com/opencv/opencv
import cv2
cap=cv2.VideoCapture(0)
while True:
sucess, img = cap.read()
#img = cv2.imread(r"F:\USER\ghostimaging\sucai\ren.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
face_Cascade = cv2.CascadeClassifier(r"D:\python\Anaconda3\envs\tensorflow_gpu\Lib\site-packages\cv2\data/haarcascade_frontalface_alt.xml")
face_Cascade.load(r'D:\python\Anaconda3\envs\tensorflow_gpu\Lib\site-packages\cv2\data/haarcascade_frontalface_alt.xml')
#
smilePath = r"D:\python\Anaconda3\envs\tensorflow_gpu\Lib\site-packages\cv2\data\haarcascade_smile.xml"
smileCascade = cv2.CascadeClassifier(smilePath)
#
faces = face_Cascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=10,
minSize=(30, 30),
flags=cv2.CASCADE_SCALE_IMAGE
)
#
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 2)
roi_gray = gray[y:y + h, x:x + w]
roi_color = img[y:y + h, x:x + w]
#
smile = smileCascade.detectMultiScale(
roi_gray,
scaleFactor=1.16,
minNeighbors=50,
minSize=(10, 10),
flags=cv2.CASCADE_SCALE_IMAGE
)
for (x2, y2, w2, h2) in smile:
cv2.rectangle(roi_color, (x2, y2), (x2 + w2, y2 + h2), (255, 0, 0), 2)
cv2.putText(img, 'Smile', (x, y - 7), 3, 1.2, (0, 255, 0), 2, cv2.LINE_AA)
img=cv2.resize(img,(int(img.shape[1]),int(img.shape[0])))
cv2.imshow('Smile test', img)
# cv2.imwrite("smile.jpg",img)
# c = cv2.waitKey(0)
k = cv2.waitKey(1)
if k == 27:
#通过esc键退出摄像
cv2.destroyAllWindows()
break
elif k==ord("s"):
#通过s键保存图片,并退出。
cv2.imwrite("image2.jpg",img)
cv2.destroyAllWindows()
break
#关闭摄像头
cap.release()