Python + OpenCV 实现脸部和眼睛的检测

import cv2

def detect():
    face_cascade = cv2.CascadeClassifier('../test5/cascades/haarcascade_frontalface_default.xml')
    eye_cascade = cv2.CascadeClassifier('../test5/cascades/haarcascade_eye.xml')

    camera = cv2.VideoCapture('../image/dsp.mp4') #括号中的值设为‘0’表示调用摄像头

    while(True):
        ret, frame = camera.read()
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        faces = face_cascade.detectMultiScale(gray, 1.3, 5,0) #把灰度图片传给haar进行灰度处理,返回值是人脸左上角坐标,宽度和高度
        for(x, y, w, h) in faces:
            img = cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)

            roi_gray = gray[y:y+h, x:x+w]

            eyes = eye_cascade.detectMultiScale(roi_gray, 1.8, 5,)

            roi_color = img[y:y + h, x:x + w]

            for(ex, ey, ew, eh) in eyes:
                cv2.rectangle(roi_color, (ex, ey), (ex+ew, ey+eh), (0, 255, 0), 2)

        cv2.imshow("camera", frame)
        if cv2.waitKey(1) == ord('q'):
            break

    camera.release()
    cv2.destroyAllWindows()

if __name__ == "__main__":
    detect()

你可能感兴趣的:(Python + OpenCV 实现脸部和眼睛的检测)