Python20行代码进行人脸识别

功能介绍

使用OpenCV进行人脸识别

代码

import cv2

filename = "images/human.jpg"

def detect(filename):
    # haarcascade_frontalface_default.xml存储在package安装的位置
    face_cascade = cv2.CascadeClassifier("data/haarcascade_frontalface_default.xml")
    img = cv2.imread(filename)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    #传递参数是scaleFactor和minNeighbors,分别表示人脸检测过程中每次迭代时图像的压缩率以及每个人脸矩形保留近邻数目的最小值
    #检测结果返回人脸矩形数组
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    for (x, y, w, h) in faces:
        img = cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
    cv2.namedWindow("Face Detected!")
    cv2.imshow("Face Detected!", img)
    cv2.imwrite("images/Face.jpg", img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

detect(filename)

识别结果

Python20行代码进行人脸识别_第1张图片

摄像头实时识别

import cv2


def detect():
    face_cascade = cv2.CascadeClassifier("data/haarcascade_frontalface_default.xml")
    eye_cascade = cv2.CascadeClassifier("data/haarcascade_eye.xml")
    camera = cv2.VideoCapture(0)
    while True and cv2.waitKey(1) == -1:
        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:
            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.03, 5, 0, (40, 40))
            for (ex, ey, ew, eh) in eyes:
                # 由于是在原图片上修改,所以需要加上原来坐标
                cv2.rectangle(img, (x + ex, y + ey), (x + ex + ew, y + ey + eh), (0, 255, 0), 2)
        cv2.imshow("camera", frame)
    camera.release()
    cv2.destroyAllWindows()


detect()

你可能感兴趣的:(OpenCV)