Об утверждении алгоритма распознавания лиц opencv (собственное лицо, fisherface, локальный двоичный шаблон) - PullRequest
0 голосов
/ 27 августа 2018

Я пытаюсь запустить проверочный тест алгоритма распознавания лиц, предоставляемого 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.

Я не уверен, что мне делать.Буду благодарен, если кто-то предоставит ценные решения.*** Я пытался изменить некоторые API-интерфейсы проверки sklearn, но это показывает другой вид ошибки.Чтобы сделать этот пост коротким, я не ставлю все эти проб и ошибок.Я просто предоставляю код.Заранее спасибо.

...