python版opencv人脸训练与人脸识别

1.人脸识别准备

使用的两个opencv包

powershell 复制代码
D:\python2023>pip list |findstr opencv
opencv-contrib-python     4.8.1.78
opencv-python             4.8.1.78

数据集使用前一篇Javacv的数据集,网上随便找的60张图片,只是都挪到了D:\face目录下方便遍历

D:\face\1 30张刘德华图片

D:\face\2 30张刘亦菲图片

2.人脸识别模型训练

python 复制代码
# -*- coding: utf-8 -*-
import os

import cv2
import numpy as np

recognizer = cv2.face.LBPHFaceRecognizer().create() # Fisher需要reshape
classifier = cv2.CascadeClassifier('E:\opencv\sources\data\haarcascades\haarcascade_frontalface_default.xml')
def load_dataset(dataset_path):
    images=[]
    labels=[]
    for root,dirs,files in os.walk(dataset_path):
        for file in files:
            images.append(cv2.imread(os.path.join(root, file),cv2.IMREAD_GRAYSCALE))
            labels.append(int(os.path.basename(root)))
    return images,labels
if __name__ == '__main__':
    images,labels = load_dataset('D:\\face')
    recognizer.train(images,np.array(labels))
    recognizer.save('face_model.xml')

3.人脸识别推理预测

python 复制代码
# -*- coding: utf-8 -*-
import os

import cv2


def face_detect(image):
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    classifier = cv2.CascadeClassifier('E:\opencv\sources\data\haarcascades\haarcascade_frontalface_default.xml')
    faces = classifier.detectMultiScale(gray, 1.2, 5)
    if (len(faces) == 0):
        return None, None
    (x, y, w, h) = faces[0]
    return gray[y:y + w, x:x + h], faces[0]


def draw_rectangle(img, rect):
    (x, y, w, h) = rect
    cv2.rectangle(img, (x, y), (x + w, y + h), (255, 255, 0), 2)


def draw_text(img, text, x, y):
    cv2.putText(img, text, (x, y), cv2.FONT_HERSHEY_COMPLEX, 1, (128, 128, 0), 2)


def predict(image):
    image_copy = image.copy()
    face, rect = face_detect(image_copy)
    tuple = recognizer.predict(face)
    print(tuple)
    draw_rectangle(image_copy, rect)
    draw_text(image_copy, str(tuple[0]), rect[0], rect[1])
    return image_copy


if __name__ == '__main__':
    recognizer = cv2.face.LBPHFaceRecognizer().create()  # Fisher需要reshape
    recognizer.read("face_model.xml")
    for root, dirs, files in os.walk('D:\\face\\2'):
        for file in files:
            file_path = os.path.join(root, file)
            predict_image = predict(cv2.imread(file_path))
            cv2.imshow('result', predict_image)
            cv2.waitKey(1000)

总结

代码逻辑基本同Javacv,但更简洁,这里训练出来模型准确度也高于Javacv (可能是参数不一致导致的)

相关推荐
不是万能的豆学长21 小时前
filetidy 文件整理助手:一键归类 + 规范重命名(Python 零依赖单文件工具)
大数据·开发语言·python·技术美术
gCode Teacher 格码致知1 天前
Pandas教学-18:number与numeric的区别
python·pandas
梦想不只是梦与想1 天前
Python 中subprocess 模块:执行外部命令
python·subprocess·调用外部命令
懂点Tech1 天前
ctfshow MISC入门图片篇(信息附加):misc41解题思路
开发语言·python
爱上纯净的蓝天1 天前
不用云做 RAG:一个本地笔记问答工具的取舍与坑
python·开源·大模型·rag·本地部署
杜哥无敌1 天前
MaxKB 容器跨平台迁移与发布完整技术手册
ai
m0_682906531 天前
工作台后端编排链路自检 10-17 11:45:56
ai·大模型·seo·geo·结构化数据·indexnow
cspttty1 天前
2027风险管理岗准备路线:数学与应用数学如何补齐金融、SQL与Python
开发语言·python·金融