使用現有視頻文件,練習一下面部以及眼睛判斷,將符合條件的區域進行保存,就是誤判較多。
import cv2
#面部識別與眼睛識別加載
faceCascade = cv2.CascadeClassifier(“./venv/Lib/site-packages/cv2/data/haarcascade_frontalface_default.xml”)
faceCascade_eye = cv2.CascadeClassifier(“./venv/Lib/site-packages/cv2/data/haarcascade_eye.xml”)
#讀取視頻文件
video = cv2.VideoCapture(‘./image/dl10.mp4’)
#視頻速率
V_FPS = video.get(cv2.CAP_PROP_FPS)
V_COUNT = video.get(cv2.CAP_PROP_FRAME_COUNT)
#視頻寬度高度
V_WIDTH = video.get(cv2.CAP_PROP_FRAME_WIDTH)
V_HEIGHT = video.get(cv2.CAP_PROP_FRAME_HEIGHT)
print(‘V_FPS:’,V_FPS,‘V_COUNT:’,V_COUNT,‘V_WIDTH’,V_WIDTH,‘V_HEIGHT’,V_HEIGHT,‘時長秒:’,str(round(V_COUNT/V_FPS)))
num = 0 #定義變量,用於文件名標記
while (video.isOpened()):
retval,image = video.read()
MSEC = video.get(cv2.CAP_PROP_POS_MSEC)
if round(MSEC/1000,2)%10 ==1:
print(‘時長秒:’,str(round(V_COUNT/V_FPS)),‘MSEC’,str(round(MSEC/1000,2)))
#cv2.namedWindow('video',0)
#cv2.resizeWindow('video',1280,720)
if retval == True:
#cv2.imshow('video',image)
faces = faceCascade.detectMultiScale(image, 1.15)
#print('faces個數:',len(faces),faces)
faces_num = 0
for (x, y, w, h) in faces:
#print('xywh', (x, y, w, h))
if w >= 50: #圖像寬超過50才保存,因為太小的誤判可能性更大
cropped = image[y:y + w, x:x + h] # 裁剪坐標為[y0:y1, x0:x1]
#加入眼睛識別,如果存在眼睛在保存
eye = faceCascade_eye.detectMultiScale(cropped, 1.15)
if len(eye) > 0:
print('眼睛:',len(eye))
cv2.imwrite("./image/weimi_meinv/meinv_" + str(num)+'_'+str(faces_num) + '.jpeg', cropped)
faces_num += 1
num += 1
else:
break
key = cv2.waitKey(1)
if key == 27:
break
video.release()
cv2.destroyAllWindows()