大神论坛

找回密码
快速注册
查看: 186 | 回复: 0

[源码] 分享个使用OpenCV的人脸采集与训练程序源码

主题

帖子

0

积分

初入江湖

UID
643
积分
0
精华
威望
0 点
违规
大神币
68 枚
注册时间
2023-10-14 10:40
发表于 2023-11-18 17:27
本帖最后由 fuming2023 于 2023-11-18 17:27 编辑

人脸采集与训练

文件结构

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()


注:若转载请注明大神论坛来源(本贴地址)与作者信息。

返回顶部