OpenCV3,Python 3如何训练FisherFaceRecognizer数据集?

时间:2017-10-27 06:06:26

标签: python opencv image-processing

我用openCV 3和Python 3来训练人脸识别。我可以训练LBPHFace和EigenFace没有错误,但是当火车FisherFace时它显示错误。

这是我的代码。

import os
import cv2
import numpy as np
from PIL import Image

LBPHFace=cv2.face.LBPHFaceRecognizer_create()
EigenFace=cv2.face.EigenFaceRecognizer_create()
FisherFace=cv2.face.FisherFaceRecognizer_create()
path='dataSet'

def getImagesWithID(path):
    imagePaths=[os.path.join(path,f) for f in os.listdir(path)]
    #print imagePaths

    faces=[]
    IDs=[]
    for imagePath in imagePaths:
        faceImg=Image.open(imagePath).convert('L')
        faceNp=np.array(faceImg,'uint8')
        ID=int(os.path.split(imagePath)[-1].split('.')[1])
        faces.append(faceNp)
        IDs.append(ID)
        cv2.imshow("training" , faceNp)
        cv2.waitKey(10)
    return np.array(IDs), faces

Ids,faces=getImagesWithID(path)
LBPHFace.train(faces, Ids)    
LBPHFace.write('recognizer/LBPHData.xml')
EigenFace.train(faces, Ids)
EigenFace.write('recognizer/EigenData.xml')

FisherFace.train(faces, Ids)
FisherFace.write('recognizer/FisherData.xml')
cv2.destroyAllWindows()

它显示错误。

Traceback (most recent call last):
  File "C:\Users\lenovoITC\AppData\Local\Programs\Python\Python36-32\training.py", line 33, in <module>
    FisherFace.train(faces, Ids)
cv2.error: C:\projects\opencv-python\opencv\modules\core\src\lda.cpp:1019: 
    error: (-5) At least two classes are needed to perform a LDA. Reason: Only one class was given! in function cv::LDA::lda

如何训练FisherFaceRecognizer数据集?

1 个答案:

答案 0 :(得分:0)

我的代码运行完美。

# face_trainer.py
import cv2, numpy, os
fn_haar = 'haarcascade_frontalface_default.xml'
fn_dir = 'database'

# Part 1: Create fisherRecognizer
print('Training...')
# Create a list of images and a list of corresponding names
(images, labels, names, id) = ([], [], {}, 0)
for (subdirs, dirs, files) in os.walk(fn_dir):
    for subdir in dirs:
        names[id] = subdir
        subjectpath = os.path.join(fn_dir, subdir)
        for filename in os.listdir(subjectpath):
            path = subjectpath + '/' + filename
        images.append(cv2.imread(path, 0))
            #labels.append(int(id))
        labels.append(subdir)
        id += 1
(im_width, im_height) = (112, 92)

# Create a Numpy array from the two lists above
(images, labels) = [numpy.array(lis) for lis in [images, labels]]

# OpenCV trains a model from the images

model = cv2.face.FisherFaceRecognizer_create()
model.train(images, labels)
model.write('trainer/trainer.yml')