关于OpenCV人脸识别算法的验证(特征脸,鱼脸,局部二进制模式)

时间:2018-08-27 00:38:33

标签: scikit-learn python-3.6 face-recognition opencv3.1

我正在尝试在特定数据库上运行由opencv提供的面部识别算法的验证测试,例如eigenface,fisherface和LBPH。 但是,我正在遵循此网站提供的步骤: https://bytefish.de/blog/validating_algorithms/。我将代码转换为python 3版本,还更改了一些sklearn模块,该模块将在以后折旧。但是我仍然无法执行验证测试。这是经过转换和稍作修改的代码:

import os
import sys
import cv2
import numpy as np

from sklearn import cross_validation as cval
from sklearn.base import BaseEstimator
from sklearn.metrics import precision_score
def read_images(path, sz=None):
"""Reads the images in a given folder, resizes images on the fly if size is given.

Args:
    path: Path to a folder with subfolders representing the subjects (persons).
    sz: A tuple with the size Resizes

Returns:
    A list [X,y]

        X: The images, which is a Python list of numpy arrays.
        y: The corresponding labels (the unique number of the subject, person) in a Python list.
"""
c = 0
X,y = [], []
for dirname, dirnames, filenames in os.walk(path):
    for subdirname in dirnames:
        subject_path = os.path.join(dirname, subdirname)
        for filename in os.listdir(subject_path):
            try:
                im = cv2.imread(os.path.join(subject_path, filename), cv2.IMREAD_GRAYSCALE)
                # resize to given size (if given)
                if (sz is not None):
                    im = cv2.resize(im, sz)
                X.append(np.asarray(im, dtype=np.uint8))
                y.append(c)
            except IOError as xxx_todo_changeme:
                (errno, strerror) = xxx_todo_changeme.args
                print("I/O error({0}): {1}".format(errno, strerror))
            except:
                print("Unexpected error:", sys.exc_info()[0])
                raise
        c = c+1
return [X,y]
class FaceRecognizerModel(BaseEstimator):

def __init__(self):
    self.model = cv2.face.FisherFaceRecognizer_create()

def fit(self, X, y):
    self.model.train(X,y)

def predict(self, T):
    return [self.model.predict(T[i]) for i in range(0, T.shape[0])]
if __name__ == "__main__":
# You'll need at least some images to perform the validation on:
if len(sys.argv) < 2:
    print("USAGE: facerec_demo.py </path/to/images> [</path/to/store/images/at>]")
    sys.exit()
# Read the images and corresponding labels into X and y.
[X,y] = read_images(sys.argv[1])
# Convert labels to 32bit integers. This is a workaround for 64bit machines,
# because the labels will truncated else. This is fixed in recent OpenCV
# revisions already, I just leave it here for people on older revisions.
#
# Thanks to Leo Dirac for reporting:
y = np.asarray(y, dtype=np.int32)
# Then we create a 10-fold cross validation iterator:
cv = cval.StratifiedKFold(y, 10)
# Now we'll create a classifier, note we wrap it up in the
# FaceRecognizerModel we have defined in this file. This is
# done, so we can use it in the awesome scikit-learn library:
estimator = FaceRecognizerModel()
# And getting the precision_scores is then as easy as writing:
precision_scores = cval.cross_val_score(estimator, X, y, score_func=precision_score, cv=cv)
# Let's print them:
print(precision_scores)

运行此代码时。我收到以下错误:

   Traceback (most recent call last):
   File "yale.py", line 70, in <module>
   cv = cval.StratifiedKFold(y, 10)
  File "C:\Users\mahsan2\PycharmProjects\untitled1\venv\lib\site- 
packages\sklearn\cross_validation.py", line 538, in __init__
len(y), n_folds, shuffle, random_state)
File "C:\Users\mahsan2\PycharmProjects\untitled1\venv\lib\site- 
 packages\sklearn\cross_validation.py", line 262, in __init__

" than the number of samples: {1}.").format(n_folds, n))
ValueError: Cannot have number of folds n_folds=10 greater than the number 
of samples: 0.

我不确定该怎么办。如果有人提供有价值的解决方案,我将不胜感激。 ***我试图更改sklearn的一些验证api,但显示出不同类型的错误。为了简短起见,我没有进行所有反复试验。我只是提供代码。提前致谢。

0 个答案:

没有答案