调用WosTrain模块
注:为更清楚的讲解,没有对方法进行封装,在生产环境中请按策略进行封装
import WosTrain
# 2-训练人脸库
ifTrainer = WosTrain.main(1308002****)
print(ifTrainer)
WosTrain.py
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import numpy as np
from PIL import Image
import os
import cv2
import config
# 脸部模型训练
# userId 用户的Id
# images 用户头像数组
def main(userId):
# 参数校正
if userId == '':
print("ERR: userId is null", userId)
return False
path = config.__FaceStore__path + '/' + str(userId) + '/'
isExists = os.path.exists(path)
if not isExists:
print("ERR: user store is null, Please use GetFace modules upload faces.", userId)
return False
images = getFaces(path)
# 不存在训练图片
if len(images) == 0:
print("ERR: user face image is null", userId)
return False
# 开始训练
src = cv2.__file__
src = src.replace('__init__.py', '', 1) + 'data/'
recognizer = cv2.face.LBPHFaceRecognizer_create()
detector = cv2.CascadeClassifier(src + "haarcascade_frontalface_default.xml")
faces, ids = getImagesAndLabels(images, detector, userId)
# 保存训练yml
recognizer.train(faces, np.array(ids))
trainerURI = config.__trainer__path + '/' + str(userId) + '.yml'
recognizer.write(r'' + trainerURI)
return True
# 遍历人脸 并进行训练
def getImagesAndLabels(images, detector, userId):
imagePaths = images
faceSamples = []
ids = []
for imagePath in imagePaths:
PIL_img = Image.open(imagePath).convert('L')
img_numpy = np.array(PIL_img, 'uint8')
faces = detector.detectMultiScale(img_numpy)
for (x, y, w, h) in faces:
faceSamples.append(img_numpy[y:y + h, x: x + w])
ids.append(userId)
return faceSamples, ids
# 这个方法应该封装,为了能更直观讲解并没有封装,请生产环境中自吸星封装
# 遍历文件夹下的jpg文件
def getFaces(file):
result = []
for root, dirs, files in os.walk(file):
for f in files:
file = os.path.join(root, f)
suffix = file.split(".")
if suffix[len(suffix) - 1] == 'jpg':
result.append(file)
return result