OpenCV 面部识别代码

# Author:Winter Liu is coming!
import cv2 as cv
import numpy as np


def face_dect(image):
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
    # opencv在GitHub上共享出来的具有普适的训练好的数据
    face_detector = cv.CascadeClassifier(r"C:\PycharmProjects\OpenCV\haarcascade_frontalface_default.xml")
    # 第二个参数是尺度变换,就是向上或者向下每次是原来的多少倍
    # 第三个参数是人脸检测次数,设置越高,误检率越低
    faces = face_detector.detectMultiScale(gray, 1.1, 3)
    # print(len(faces))
    # print(faces.shape)
    for x, y, w, h in faces:
        cv.rectangle(image, (x, y), (x+w, y+h), (0, 0, 255), 2)
    cv.imshow("face_detect", image)


def video_face_detect():
    capture = cv.VideoCapture(0)
    while 1:
        ret, frame = capture.read()
        # 图像水平翻转
        frame = cv.flip(frame, 1)
        # 检测视频结束
        if ret == False:
            break
        face_dect(frame)
        c = cv.waitKey(10)
        if c == 27:
            break


# src = cv.imread(r"C:\PycharmProjects\OpenCV\pic\family2.jpg")
# cv.imshow("original_pic", src)
video_face_detect()
cv.waitKey(0)
cv.destroyAllWindows()

相关推荐