1. 程式人生 > >OpenCV訓練人臉模型並生成XML檔案

OpenCV訓練人臉模型並生成XML檔案

程式碼位置: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