4 OpenCV根据userId生成训练模型

调用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

专栏文章目录

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wos.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值