zl程序教程

您现在的位置是:首页 >  后端

当前栏目

python 人脸识别 基于openCV

PythonOpencv 基于 人脸识别
2023-09-14 09:02:29 时间

1、库

opencv-python
opencv-contrib-python
numpy
Pillow

openCV可以到官网下载release包,https://opencv.org/releases/

通过pip3也可以安装

 

2、训练

import numpy as np
from PIL import Image
import os
import cv2 as cv


def getImagesAndLabels(path):
    imagePaths = [os.path.join(path, f) for f in os.listdir(path)]
    faceSamples = []
    ids = []
    for imagePath in imagePaths:
        img_gray = Image.open(imagePath).convert('L')
        img_numpy = np.array(img_gray, 'uint8')
        # 图片的命名方式 xx.id.num.ext(xx为任意英文标识,id是标签,同类人脸相同,num一般为该类图片的计数,ext为图片后缀)
        # 文件名中关键就是id,作为有监督学习,id就是用于分类
        id = int(os.path.split(imagePath)[-1].split(".")[1])
        print(id, " ", imagePath)
        faces = face_detector.detectMultiScale(img_numpy)
        for x, y, w, h in faces:
            faceSamples.append(img_numpy[y:y + h, x:x + w])
            ids.append(id)
    return faceSamples, ids


if __name__ == '__main__':
    print("Training faces. It will take a few seconds. Wait ...")
    # 人脸图片路径
    face_path = '../face_data/'
    # opencv-contrib-python包中的函数
    recognizer = cv.face.LBPHFaceRecognizer_create()
    # 载入人脸分类器
    face_detector = cv.CascadeClassifier(
        r"E:\BaiduYunDownload\opencv\sources\data\haarcascades\haarcascade_frontalface_default.xml")
    faces, ids = getImagesAndLabels(face_path)
    recognizer.train(faces, np.array(ids))
    # 保存训练信息
    recognizer.write('../face_trainer/trainer.yml')
    print("{0} faces trained. Exiting Program".format(len(np.unique(ids))))

 

2、人脸识别

import cv2 as cv
import os


def recognizeImage(imagePath):
    recognizer = cv.face.LBPHFaceRecognizer_create()
    recognizer.read('../face_trainer/trainer.yml')
    haar_path = r"E:\BaiduYunDownload\opencv\sources\data\haarcascades\haarcascade_frontalface_default.xml"
    face_detector = cv.CascadeClassifier(haar_path)
    font = cv.FONT_HERSHEY_SIMPLEX

    idnum = None
    # 以训练的时候,按人脸id进行排序
    names = ['chen', 'peter', 'hu', 'lin']

    print(imagePath)
    img = cv.imread(imagePath)
    img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    faces = face_detector.detectMultiScale(img_gray)
    for x, y, w, h in faces:
        cv.rectangle(img, (x, y), (x + w, y + h), color=(0, 255, 0), thickness=1)
        idnum, confidence = recognizer.predict(img_gray[y:y + h, x:x + w])
    if confidence < 100:
        idnum = names[idnum]
        confidence = "{0}%".format(round(100 - confidence))
    else:
        idnum = "unknown"
        confidence = "{0}%".format(round(100 - confidence))
    cv.putText(img, str(idnum), (x + 5, y - 5), font, 1, (0, 0, 255), 1)
    cv.putText(img, str(confidence), (x + 5, y + h - 5), font, 1, (0, 255, 0), 1)
    cv.imshow("result", img)
    while True:
        if ord('q') == cv.waitKey(0):
            break
    cv.destroyAllWindows()


if __name__ == '__main__':
    face_dir = '../face_test/'
    imagePaths = [os.path.join(face_dir, f) for f in os.listdir(face_dir)]
    for imagePath in imagePaths:
        recognizeImage(imagePath)