OpenCV训练人脸模型并生成XML文件

本文是《OpenCV系列教程》的一部分,介绍如何利用OpenCV训练人脸识别模型,重点是将图片转为灰度图,并提供训练所需资源,特别是针对周润发图片的训练。最终会生成包含模型数据的XML文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

《OpenCV系列教程》
项目位置:OpenCV-Sample
代码位置:23-LearnEigenFace.py
同时所需要的资源也都在项目里面

import  cv2
import os
import numpy as np

imgs = []
cl = []
imgPath = './Actor/zxc/'
model = cv2.face.EigenFaceRecognizer_create()
dirs = os.listdir(imgPath)
for f in dirs:
    file = imgPath + f
    img = cv2.imread(file, 0)
    imgs.append(img)
    cl.append(101)

array = np.array(cl)
model.train(imgs, array)
model.save('./XML/actor_zxc.xml')
cv2.destroyAllWindows()

需要注意的一点是必须转成灰度图。
训练资源也都在项目里面。
训练的是周润发的图片。
在这里插入图片描述

生成好的数据都类似这样的:

<?xml version="1.0"?>
<opencv_storage>
<opencv_eigenfaces>
  <threshold>1.7976931348623157e+308</threshold>
  <num_components>11</num_components>
  <mean type_id="opencv-matrix">
    <rows>1</rows>
    <cols>40000</cols>
    <dt>d</dt>
    <data>
      1.4918181818181819e+02 1.4790909090909091e+02
      1.4709090909090909e+02 1.4836363636363637e+02
      1.4809090909090909e+02 1.4672727272727272e+02
      1.4654545454545456e+02 147. 147. 1.4627272727272728e+02
      1.4690909090909091e+02 1.4745454545454547e+02
      1.4672727272727272e+02 1.4654545454545456e+02
      1.4681818181818181e+02 1.4690909090909091e+02
      1.4709090909090909e+02 1.4681818181818181e+02
      1.4654545454545456e+02 147. 1.4645454545454547e+02
      1.4663636363636365e+02 1.4690909090909091e+02
      1.4654545454545456e+02 1.4663636363636365e+02
      1.4572727272727272e+02 1.4690909090909091e+02
      1.4636363636363637e+02 1.4636363636363637e+02
      1.4636363636363637e+02 1.4672727272727272e+02
      1.4645454545454547e+02 1.4663636363636365e+02
      1.4727272727272728e+02 1.4690909090909091e+02
      1.4672727272727272e+02 1.4718181818181819e+02
      1.4736363636363637e+02 1.4663636363636365e+02
      1.4718181818181819e+02 1.4745454545454547e+02 147.
      1.4763636363636365e+02 148. 1.4763636363636365e+02
      1.4790909090909091e+02 1.4763636363636365e+02
      1.4827272727272728e+02 1.4781818181818181e+02
      1.4772727272727272e+02 1.4845454545454547e+02 148.
      1.4790909090909091e+02 1.4818181818181819e+02
评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值