今天在学习深度学习知识时,发现python在安装完成后会自带几个已经训练好的xml文件,其中就有人脸识别和眼睛识别。然后我把这俩文件放到了我之前学习的打开摄像头的代码里,发现可以使用。使用结果和代码如下:

# -*- coding: utf-8 -*-
import cv2


def detect():
    face_cascade = cv2.CascadeClassifier(
        r'haarcascade_frontalface_alt2.xml')
    eye_cascade = cv2.CascadeClassifier(
        r'haarcascade_eye.xml')

    camera = cv2.VideoCapture(0)
    while (True):
        ret, frame = camera.read()
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        # 检测人脸
       
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
        for (x, y, w, h) in faces:
            cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)
        # 检测眼睛
       
eyes = eye_cascade.detectMultiScale(gray, 1.3, 5)
        for (ex, ey, ew, eh) in eyes:
            cv2.rectangle(frame, (ex, ey), (ex + ew, ey + eh), (0, 255, 0), 2)

        cv2.imshow('camera', frame)

        if cv2.waitKey(1000 // 12) & 0xff == ord('q'):
            break
   
camera.release()
    cv2.destroyAllWindows()


if __name__ == '__main__':
    detect()