系列文章目录
前言
在我们的人脸采集 的文章中我们将人脸数据采集,到后我么是不可可以直接运用到人脸识别训练里面的要经过过通的数据训练生成数据文件看。,也就是yml文件才可以被人脸数据所识别。
一、主要思路
- 引入我们的第三方库
import os
import cv2 as cv
import numpy as np
from PIL import Image
- 建立一个列表
# 存储人脸数据
face_data = []
# 存储姓名:
face_ids = []
- 遍历上个文件采集的图片
# 存储的图片信息
imaegPaths = [os.path.join(path, f) for f in os.listdir(path)]
- 加载分类器
# 加载分类器
face_d = cv.CascadeClassifier(r"C:\Users\HONOR\AppData\Local\Programs\Python\Python37\Lib\site-packages\cv2\data\haarcascade_frontalface_default.xml")
和上一个分类器的位置一致
- 写入数据以及id
for imagePath in imaegPaths:
PIL_Img = Image.open(imagePath).convert("L")
img_np = np.array(PIL_Img, "uint8")
if os.path.split(imagePath)[-1].split(".")[-1] != 'jpg':
continue
id = int(os.path.split(imagePath)[-1].split(".")[1])
faces = face_d.detectMultiScale(img_np)
for x, y, w, h in faces:
face_ids.append(id)
face_data.append(img_np[y:y + h, x:x + w])
# 打印脸部特征
print("id:", id)
print("fs:", face_data)
完整的代码
# -*- coding = utf-8 -*-
# -*-@Time : 2022/8/18 17:33
# -*-@Author : 于金龙
# -*-@File : 数据训练.py
# -*-@software : PyCharm
import os
import cv2 as cv
import numpy as np
from PIL import Image
def getxunlainshuju(path):
# 存储人脸数据
face_data = []
# 存储姓名:
face_ids = []
# 存储的图片信息
imaegPaths = [os.path.join(path, f) for f in os.listdir(path)]
# 加载分类器
face_d = cv.CascadeClassifier(r"C:\Users\HONOR\AppData\Local\Programs\Python\Python37\Lib\site-packages\cv2\data\haarcascade_frontalface_default.xml")
for imagePath in imaegPaths:
PIL_Img = Image.open(imagePath).convert("L")
img_np = np.array(PIL_Img, "uint8")
if os.path.split(imagePath)[-1].split(".")[-1] != 'jpg':
continue
id = int(os.path.split(imagePath)[-1].split(".")[1])
faces = face_d.detectMultiScale(img_np)
for x, y, w, h in faces:
face_ids.append(id)
face_data.append(img_np[y:y + h, x:x + w])
# 打印脸部特征
print("id:", id)
print("fs:", face_data)
return face_data, face_ids
if __name__ == '__main__':
faces, ids = getxunlainshuju(r'facedata/')
recognzer = cv.face.LBPHFaceRecognizer_create()
recognzer.train(faces, np.array(ids))
recognzer.write("yujinlong232.yml")
总结
以上内容我对人脸采集部分的理解,希望对大家有用,下面是我写的一个python文件
数据训练的完整代码文件(大家有兴趣可以去下载玩一下)