简体   繁体   中英

OpenCV3, Python 3 How to train FisherFaceRecognizer dataset?

I user openCV 3 and Python 3 to train face recognize. I can train LBPHFace and EigenFace with no error but it show error when train FisherFace.

This is my code.

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()

It show error like this.

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

How to train FisherFaceRecognizer dataset ?

My code works perfect.

# 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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM