吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 1928|回复: 21
上一主题 下一主题
收起左侧

[Python 原创] 分享一个简易的Python OpenCV人脸识别程序

[复制链接]
跳转到指定楼层
楼主
Murphy16666 发表于 2023-11-15 20:10 回帖奖励

人脸采集与训练

文件结构

文件结构图

face_train.py     人脸识别和训练

import os
import cv2
import numpy as np
import pickle

current_id = 0
label_ids = {}
x_train = []
y_labels = []

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
image_dir = os.path.join(BASE_DIR, "images")
cap = cv2.VideoCapture(0)
recognizer = cv2.face_LBPHFaceRecognizer.create()
classifier = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")

count = 0

while True:
    ret, frame = cap.read()
    if ret:
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        faces = classifier.detectMultiScale(gray, 1.3, 5)
        # 画一个脸部矩形
        for (x, y, w, h) in faces:
            cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 255), 2)
            count += 1
            cv2.imwrite("./images/XXX/face" + str(count) + ".jpg", gray[y - 25:y + h + 25, x - 50:x + w + 50])
        cv2.imshow('frame', frame)
        cv2.imshow('freame_with_gray', gray)
    if cv2.waitKey(1) & 0xFF == ord('q') or count == 100:
        break
cap.release()
cv2.destroyAllWindows()
# 开始训练
for root, dirs, files in os.walk(image_dir):
    for file in files:
        path = os.path.join(root, file)
        # print(path)
        image = cv2.imread(path)
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        image_arr = np.array(gray, "uint8")

        label = os.path.basename(root)

        if label not in label_ids:
            label_ids[label] = current_id
            current_id += 1
        id_ = label_ids[label]
        faces = classifier.detectMultiScale(image_arr,1.5,5)
        for x,y,w,h in faces:
            rol = image_arr[y:y+h, x:x+w]
            x_train.append(rol)
            y_labels.append(id_)
with open("label.pickle", "wb") as file:
    pickle.dump(label_ids, file)
print(label_ids)
recognizer.train(x_train, np.array(y_labels))
recognizer.save("trainner.xml")

face_recognition.py 人脸识别程序

import cv2
import numpy as np
import pickle

cap = cv2.VideoCapture(0)
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_alt2.xml')
recognizer = cv2.face_LBPHFaceRecognizer.create()
recognizer.read("trainner.xml")
labels = {}
with open('label.pickle', 'rb') as file:
    origin_labels = pickle.load(file)
    labels = {v: k for k, v in origin_labels.items()}

while True:
    ret, frame = cap.read()
    if ret:
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        faces = face_cascade.detectMultiScale(gray, 1.3, 5)
        # 画一个脸部矩形
        for (x, y, w, h) in faces:
            gray_roi = gray[y:y + h, x:x + w]
            id_,conf = recognizer.predict(gray_roi)
            if conf>=50:
                print(labels[id_])
                cv2.putText(frame, labels[id_], (x, y), cv2.FONT_HERSHEY_PLAIN,1.0, (0, 255, 0), 2)
            cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 255), 2)
        cv2.namedWindow('result', cv2.WINDOW_FULLSCREEN)
        cv2.imshow('result', frame)
        # cv2.imshow('freame_with_gray', gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cap.release()
cv2.destroyAllWindows()

免费评分

参与人数 2吾爱币 +10 热心值 +2 收起 理由
苏紫方璇 + 10 + 1 欢迎分析讨论交流,吾爱破解论坛有你更精彩!
LonelyLemon + 1 我很赞同!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

推荐
xcsg 发表于 2024-3-22 18:33
    recognizer.train(x_train, np.array(y_labels))
cv2.error: OpenCV(4.9.0) D:\a\opencv-python\opencv-python\opencv_contrib\modules\face\src\lbph_faces.cpp:362: error: (-210:Unsupported format or combination of formats) Empty training data was given. You'll need more than one sample to learn a model. in function 'cv::face::LBPH::train'

报错,请问您用的Python及opencv版本是
沙发
wsxb 发表于 2023-11-15 22:06
3#
mishuai 发表于 2023-11-15 22:51
python菜鸟看懵逼了 这个是一张一张添加代码?
4#
aigc 发表于 2023-11-15 23:10
打包成GUI运行就更好了
5#
netpeng 发表于 2023-11-15 23:51
有没有带UI的版本?
6#
 楼主| Murphy16666 发表于 2023-11-16 01:12 |楼主
netpeng 发表于 2023-11-15 23:51
有没有带UI的版本?

暂时还没有
7#
 楼主| Murphy16666 发表于 2023-11-16 01:13 |楼主

不是哦,暂时还没有打包成gui
8#
 楼主| Murphy16666 发表于 2023-11-16 01:14 |楼主
aigc 发表于 2023-11-15 23:10
打包成GUI运行就更好了

感谢支持,我继续努力🙏
9#
zxcnew 发表于 2023-11-16 01:16
感谢分享
10#
risingsun 发表于 2023-11-16 08:19
学习下,测试下看看。感谢分享。
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止灌水或回复与主题无关内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-5-3 18:03

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表