python cv2的視頻檢測:睜眼閉眼

如題,想實現一個簡單的根據攝像頭的某一幀檢測睜眼閉眼的功能。ide

 

初步的想法是:spa

1. cv2調用計算機攝像頭,讀取某一幀的畫面.code

2. 將該畫面做爲 哈爾-人臉分類器的輸入接口,根據分類器結果返回分類的結果區域。xml

3. 對結果區域圖像裁剪,做爲哈爾-眼睛分類器的輸入接口。blog

4. 若在人臉分類器的輸出圖像上沒法檢測到眼睛的分類器即確認爲閉眼狀態並給予提示。接口

 

操做過程基本明瞭。ip

 

代碼放上:utf-8

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import cv2 as cv
#import time


# 哈爾級聯分類器
fd = cv.CascadeClassifier(r'C:\Users\wenzhe.tian\Desktop\閉眼識別\haarcascade_frontalface_alt.xml')
ed = cv.CascadeClassifier(r'C:\Users\wenzhe.tian\Desktop\閉眼識別\haarcascade_eye_tree_eyeglasses.xml')
#nd = cv.CascadeClassifier('../../data/haar/nose.xml')
vc = cv.VideoCapture(0)

while True:
    frame = vc.read()[1]
    faces = fd.detectMultiScale(frame, 1.3, 5)
    for l, t, w, h in faces:
        a, b = int(w / 2), int(h / 2) 
        cv.ellipse(frame, (l+a, t+b), (a, b), 0, 0, 360, (255, 0, 255), 2)
        face = frame[t:t+h, l:l+w] 
    
        eyes = ed.detectMultiScale(face, 1.3, 5)
    for l, t, w, h in eyes:
        a, b = int(w / 2), int(h / 2)
        cv.ellipse(face, (l+a, t+b), (a, b), 0,0, 360, (0, 255, 0), 2)
    
    # noses = nd.detectMultiScale(face, 1.3, 5)
    # for l, t, w, h in noses:
    # a, b = int(w / 2), int(h / 2)
    # cv.ellipse(face, (l a, t b), (a, b), 0,
    # 0, 360, (255, 0, 0), 2)
    # a = 'close eyes!!' 
    
    if len(eyes) != 0:
        cv.destroyWindow('close eyes!!')
        # cv.moveWindow('open eyes',300,300)
        cv.imshow('open eyes!!', frame)

    else:
        cv.destroyWindow('open eyes!!')
        # time.sleep(1)
        # cv.moveWindow('close eyes',300,300)
        cv.imshow('close eyes!!', frame)
    
    
    if cv.waitKey(1) == ord(' '):
        break 
vc.release()
cv.destroyAllWindows()
相關文章
相關標籤/搜索