def entrenarModelo(dirImagenes = None, arcModelo = arcModelo): if dirImagenes is None: print dirImagenes return 0 [X,y,clases] = read_images(sys.argv[2]) modelo = PredictableModel(feature=Fisherfaces(), classifier=NearestNeighbor(dist_metric=EuclideanDistance(), k=1)) #configuración del modelo modelo.compute(X, y) pkl = open(arcModelo, 'wb') cPickle.dump([modelo,clases,tamanioCara],pkl) #se usa cPickle directamente en vez de save_model para poder insertar metadata pkl.close() validacion = KFoldCrossValidation(modelo, k=10) validacion.validate(X, y) validacion.print_results()
def train(train_path): # Now read in the image data. This must be a valid path! [X, y, class_names] = read_images(train_path) print X, y, class_names # Then set up a handler for logging: handler = logging.StreamHandler(sys.stdout) formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) # Add handler to facerec modules, so we see what's going on inside: logger = logging.getLogger("facerec") logger.addHandler(handler) logger.setLevel(logging.DEBUG) # Define the Fisherfaces as Feature Extraction method: feature = Fisherfaces() # Define a 1-NN classifier with Euclidean Distance: classifier = NearestNeighbor(dist_metric=EuclideanDistance(), k=1) # Define the model as the combination model = PredictableModel(feature=feature, classifier=classifier) # Compute the Fisherfaces on the given data (in X) and labels (in y): model.compute(X, y) # Then turn the first (at most) 16 eigenvectors into grayscale # images (note: eigenvectors are stored by column!) E = [] for i in xrange(min(model.feature.eigenvectors.shape[1], 16)): e = model.feature.eigenvectors[:, i].reshape(X[0].shape) E.append(minmax_normalize(e, 0, 255, dtype=np.uint8)) # Plot them and store the plot to "python_fisherfaces_fisherfaces.pdf" subplot(title="Fisherfaces", images=E, rows=4, cols=4, sptitle="Fisherface", colormap=cm.jet, filename="fisherfaces.png") # Perform a 10-fold cross validation cv = KFoldCrossValidation(model, k=10) cv.validate(X, y) # And print the result: cv.print_results() save_model('model.pkl', model, class_names) return [model, class_names]
def train(train_path): # Now read in the image data. This must be a valid path! [X,y,class_names] = read_images(train_path) print X,y,class_names # Then set up a handler for logging: handler = logging.StreamHandler(sys.stdout) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) # Add handler to facerec modules, so we see what's going on inside: logger = logging.getLogger("facerec") logger.addHandler(handler) logger.setLevel(logging.DEBUG) # Define the Fisherfaces as Feature Extraction method: feature = Fisherfaces() # Define a 1-NN classifier with Euclidean Distance: classifier = NearestNeighbor(dist_metric=EuclideanDistance(), k=1) # Define the model as the combination model = PredictableModel(feature=feature, classifier=classifier) # Compute the Fisherfaces on the given data (in X) and labels (in y): model.compute(X, y) # Then turn the first (at most) 16 eigenvectors into grayscale # images (note: eigenvectors are stored by column!) E = [] for i in xrange(min(model.feature.eigenvectors.shape[1], 16)): e = model.feature.eigenvectors[:,i].reshape(X[0].shape) E.append(minmax_normalize(e,0,255, dtype=np.uint8)) # Plot them and store the plot to "python_fisherfaces_fisherfaces.pdf" subplot(title="Fisherfaces", images=E, rows=4, cols=4, sptitle="Fisherface", colormap=cm.jet, filename="fisherfaces.png") # Perform a 10-fold cross validation cv = KFoldCrossValidation(model, k=10) cv.validate(X, y) # And print the result: cv.print_results() save_model('model.pkl', model, class_names) return [model,class_names]
# Add handler to facerec modules, so we see what's going on inside: logger = logging.getLogger("facerec") logger.addHandler(handler) logger.setLevel(logging.DEBUG) # Define the Fisherfaces as Feature Extraction method: feature = Fisherfaces() # Define a 1-NN classifier with Euclidean Distance: classifier = SVM() # Define the model as the combination model = PredictableModel(feature=feature, classifier=classifier) # Compute a model: model.compute(X, y) # Save the Model using joblib: save_model('model.pkl', model) # Perform a Grid Search for the Set of Parameters: tuned_parameters = [{ 'kernel': ['rbf'], 'gamma': [1e-3, 1e-4], 'C': [1, 10, 100, 1000] }, { 'kernel': ['linear'], 'C': [1, 10, 100, 1000] }] # Find a good set of parameters: grid_search(model, X, y, tuned_parameters) # Perform a 10-fold cross validation cv = KFoldCrossValidation(model, k=10) cv.validate(X, y) # And print the result: cv.print_results()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) # Add handler to facerec modules, so we see what's going on inside: logger = logging.getLogger("facerec") logger.addHandler(handler) logger.setLevel(logging.DEBUG) # Define the Fisherfaces as Feature Extraction method: feature = Fisherfaces() # Define a 1-NN classifier with Euclidean Distance: classifier = NearestNeighbor(dist_metric=EuclideanDistance(), k=1) # Define the model as the combination my_model = PredictableModel(feature=feature, classifier=classifier) # Compute the Fisherfaces on the given data (in X) and labels (in y): my_model.compute(X, y) # We then save the model, which uses Pythons pickle module: save_model('model.pkl', my_model) model = load_model('model.pkl') # Then turn the first (at most) 16 eigenvectors into grayscale # images (note: eigenvectors are stored by column!) E = [] for i in xrange(min(model.feature.eigenvectors.shape[1], 16)): e = model.feature.eigenvectors[:,i].reshape(X[0].shape) E.append(minmax_normalize(e,0,255, dtype=np.uint8)) # Plot them and store the plot to "python_fisherfaces_fisherfaces.pdf" subplot(title="Fisherfaces", images=E, rows=4, cols=4, sptitle="Fisherface", colormap=cm.jet, filename="fisherfaces.png") # Perform a 10-fold cross validation cv = KFoldCrossValidation(model, k=10) cv.validate(X, y) # And print the result: cv.print_results()
if options.numfolds: print "Validating model with %s folds..." % options.numfolds handler = logging.StreamHandler(sys.stdout) formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logger = logging.getLogger("facerec") logger.addHandler(handler) logger.setLevel(logging.DEBUG) crossval = KFoldCrossValidation(model, k=options.numfolds) crossval.validate(images, labels) crossval.print_results() print "Computing the model..." model.compute(images, labels) print "Saving the model..." save_model(model_filename, model) else: print "Loading the model..." model = load_model(model_filename) if not isinstance(model, ExtendedPredictableModel): print "[Error] The given model is not of type '%s'." % "ExtendedPredictableModel" sys.exit() print "Starting application..."
if options.numfolds: print "Validating model with %s folds..." % options.numfolds # We want to have some log output, so set up a new logging handler # and point it to stdout: handler = logging.StreamHandler(sys.stdout) formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) # Add a handler to facerec modules, so we see what's going on inside: logger = logging.getLogger("facerec") logger.addHandler(handler) logger.setLevel(logging.DEBUG) # Perform the validation & print results: crossval = KFoldCrossValidation(model, k=options.numfolds) crossval.validate(images, labels) crossval.print_results() # Compute the model: print "Computing the model..." model.compute(images, labels) # And save the model, which uses Pythons pickle module: print "Saving the model..." save_model(model_filename, model) else: print "Loading the model..." model = load_model(model_filename) # We operate on an ExtendedPredictableModel. Quit the application if this # isn't what we expect it to be: if not isinstance(model, ExtendedPredictableModel): print "[Error] The given model is not of type '%s'." % "ExtendedPredictableModel" sys.exit() # Now it's time to finally start the Application! It simply get's the model
def Init(self): from optparse import OptionParser # model.pkl is a pickled (hopefully trained) PredictableModel, which is # used to make predictions. You can learn a model yourself by passing the # parameter -d (or --dataset) to learn the model from a given dataset. usage = "usage: %prog [options] model_filename" # Add options for training, resizing, validation and setting the camera id: parser = OptionParser(usage=usage) parser.add_option( "-r", "--resize", action="store", type="string", dest="size", default="100x100", help= "Resizes the given dataset to a given size in format [width]x[height] (default: 100x100)." ) parser.add_option( "-v", "--validate", action="store", dest="numfolds", type="int", default=None, help= "Performs a k-fold cross validation on the dataset, if given (default: None)." ) parser.add_option("-t", "--train", action="store", dest="dataset", type="string", default=None, help="Trains the model on the given dataset.") parser.add_option("-i", "--id", action="store", dest="camera_id", type="int", default=0, help="Sets the Camera Id to be used (default: 0).") parser.add_option( "-c", "--cascade", action="store", dest="cascade_filename", default="haarcascade_frontalface_default.xml", help= "Sets the path to the Haar Cascade used for the face detection part (default: haarcascade_frontalface_alt2.xml)." ) # Show the options to the user: parser.print_help() print "Press [ESC] to exit the program!" print "Script output:" # Parse arguments: (options, args) = parser.parse_args() print(options, args) # Check if a model name was passed: my_model = 'my_model.pk' ''' if len(args) == 0: print "[Error] No prediction model was given." sys.exit() ''' # This model will be used (or created if the training parameter (-t, --train) exists: #model_filename = args[0] model_filename = my_model options.dataset = 'faces' # Check if the given model exists, if no dataset was passed: if (options.dataset is None) and (not os.path.exists(model_filename)): print "[Error] No prediction model found at '%s'." % model_filename sys.exit() # Check if the given (or default) cascade file exists: if not os.path.exists(options.cascade_filename): print "[Error] No Cascade File found at '%s'." % options.cascade_filename sys.exit() # We are resizing the images to a fixed size, as this is neccessary for some of # the algorithms, some algorithms like LBPH don't have this requirement. To # prevent problems from popping up, we resize them with a default value if none # was given: try: image_size = (int(options.size.split("x")[0]), int(options.size.split("x")[1])) except: print "[Error] Unable to parse the given image size '%s'. Please pass it in the format [width]x[height]!" % options.size sys.exit() # We have got a dataset to learn a new model from: if options.dataset: print('data set') print(options.dataset) # Check if the given dataset exists: if not os.path.exists(options.dataset): print "[Error] No dataset found at '%s'." % dataset_path sys.exit() # Reads the images, labels and folder_names from a given dataset. Images # are resized to given size on the fly: print "Loading dataset..." [images, labels, subject_names] = read_images(options.dataset, image_size) # Zip us a {label, name} dict from the given data: list_of_labels = list(xrange(max(labels) + 1)) subject_dictionary = dict(zip(list_of_labels, subject_names)) # Get the model we want to compute: model = get_model(image_size=image_size, subject_names=subject_dictionary) # Sometimes you want to know how good the model may perform on the data # given, the script allows you to perform a k-fold Cross Validation before # the Detection & Recognition part starts: if options.numfolds: print "Validating model with %s folds..." % options.numfolds # We want to have some log output, so set up a new logging handler # and point it to stdout: handler = logging.StreamHandler(sys.stdout) formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) # Add a handler to facerec modules, so we see what's going on inside: logger = logging.getLogger("facerec") logger.addHandler(handler) logger.setLevel(logging.DEBUG) # Perform the validation & print results: crossval = KFoldCrossValidation(model, k=options.numfolds) crossval.validate(images, labels) crossval.print_results() # Compute the model: print "Computing the model..." model.compute(images, labels) # And save the model, which uses Pythons pickle module: print "Saving the model..." save_model(model_filename, model) else: print "Loading the model..." model = load_model(model_filename) # We operate on an ExtendedPredictableModel. Quit the application if this # isn't what we expect it to be: if not isinstance(model, ExtendedPredictableModel): print "[Error] The given model is not of type '%s'." % "ExtendedPredictableModel" sys.exit() # Now it's time to finally start the Application! It simply get's the model # and the image size the incoming webcam or video images are resized to: print "Starting application..." self.__faceRecognizer = recognizer( model=model, camera_id=options.camera_id, cascade_filename=options.cascade_filename)
def start(): from optparse import OptionParser # model.pkl is a pickled (hopefully trained) PredictableModel, which is # used to make predictions. You can learn a model yourself by passing the # parameter -d (or --dataset) to learn the model from a given dataset. usage = "usage: %prog [options] model_filename" # Add options for training, resizing, validation and setting the camera id: parser = OptionParser(usage=usage) parser.add_option("-r", "--resize", action="store", type="string", dest="size", default="100x100", help="Resizes the given dataset to a given size in format [width]x[height] (default: 100x100).") parser.add_option("-v", "--validate", action="store", dest="numfolds", type="int", default=None, help="Performs a k-fold cross validation on the dataset, if given (default: None).") parser.add_option("-t", "--train", action="store", dest="dataset", type="string", default=None, help="Trains the model on the given dataset.") parser.add_option("-i", "--id", action="store", dest="camera_id", type="int", default=0, help="Sets the Camera Id to be used (default: 0).") parser.add_option("-c", "--cascade", action="store", dest="cascade_filename", default="haarcascade_frontalface_alt2.xml", help="Sets the path to the Haar Cascade used for the face detection part (default: haarcascade_frontalface_alt2.xml).") # Show the options to the user: parser.print_help() print "Press [ESC] to exit the program!" print "Script output:" # Parse arguments: (options, args) = parser.parse_args() # Check if a model name was passed: dataset = "C:\\Users\\newbie\\PycharmProjects\\duinobot\\scripts\\test" cascade_filename = "C:\\Users\\newbie\\PycharmProjects\\duinobot\\scripts\\haarcascade_frontalface_alt2.xml" if len(args) == 0: print "[Error] No prediction model was given." sys.exit() # This model will be used (or created if the training parameter (-t, --train) exists: model_filename = args[0] # Check if the given model exists, if no dataset was passed: if (dataset is None) and (not os.path.exists(model_filename)): print "[Error] No prediction model found at '%s'." % model_filename sys.exit() # Check if the given (or default) cascade file exists: if not os.path.exists(cascade_filename): print "[Error] No Cascade File found at '%s'." % cascade_filename sys.exit() # We are resizing the images to a fixed size, as this is neccessary for some of # the algorithms, some algorithms like LBPH don't have this requirement. To # prevent problems from popping up, we resize them with a default value if none # was given: try: image_size = (int(options.size.split("x")[0]), int(options.size.split("x")[1])) except: print "[Error] Unable to parse the given image size '%s'. Please pass it in the format [width]x[height]!" % options.size sys.exit() # We have got a dataset to learn a new model from: if dataset: # Check if the given dataset exists: if not os.path.exists(dataset): print "[Error] No dataset found at '%s'." % dataset_path sys.exit() # Reads the images, labels and folder_names from a given dataset. Images # are resized to given size on the fly: print "Loading dataset..." [images, labels, subject_names] = read_images(dataset, image_size) # Zip us a {label, name} dict from the given data: list_of_labels = list(xrange(max(labels) + 1)) subject_dictionary = dict(zip(list_of_labels, subject_names)) # Get the model we want to compute: model = get_model(image_size=image_size, subject_names=subject_dictionary) # Sometimes you want to know how good the model may perform on the data # given, the script allows you to perform a k-fold Cross Validation before # the Detection & Recognition part starts: if options.numfolds: print "Validating model with %s folds..." % options.numfolds # We want to have some log output, so set up a new logging handler # and point it to stdout: handler = logging.StreamHandler(sys.stdout) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) # Add a handler to facerec modules, so we see what's going on inside: logger = logging.getLogger("facerec") logger.addHandler(handler) logger.setLevel(logging.DEBUG) # Perform the validation & print results: crossval = KFoldCrossValidation(model, k=options.numfolds) crossval.validate(images, labels) crossval.print_results() # Compute the model: print "Computing the model..." model.compute(images, labels) # And save the model, which uses Pythons pickle module: print "Saving the model..." save_model(model_filename, model) else: print "Loading the model..." model = load_model(model_filename) # We operate on an ExtendedPredictableModel. Quit the application if this # isn't what we expect it to be: if not isinstance(model, ExtendedPredictableModel): print "[Error] The given model is not of type '%s'." % "ExtendedPredictableModel" sys.exit() # Now it's time to finally start the Application! It simply get's the model # and the image size the incoming webcam or video images are resized to: print "Starting application..." App(model=model, camera_id=options.camera_id, cascade_filename=cascade_filename).run()
def run(): # This is where we write the images, if an output_dir is given # in command line: # out_dir = None # You'll need at least a path to your image data, please see # the tutorial coming with this source code on how to prepare # your image data: # if len(sys.argv) < 2: # print ("USAGE: facerec_demo.py </path/to/images>") # sys.exit() # Now read in the image data. This must be a valid path! # [X,y] = read_images(sys.argv[1]) [X, y] = read_images('../data/trainset/') # dataset = FilesystemReader(sys.argv[1]) # Then set up a handler for logging: handler = logging.StreamHandler(sys.stdout) formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) # Add handler to facerec modules, so we see what's going on inside: logger = logging.getLogger("facerec") logger.addHandler(handler) logger.setLevel(logging.DEBUG) # Define the Fisherfaces as Feature Extraction method: feature = Fisherfaces() # Define a 1-NN classifier with Euclidean Distance: svm = SVM(C=0.1, kernel='rbf', degree=4, gamma='auto', coef0=0.0) knn = NearestNeighbor(dist_metric=EuclideanDistance(), k=1) # # Define the model as the combination model_svm = PredictableModel(feature=feature, classifier=svm) model_knn = PredictableModel(feature=feature, classifier=knn) # # Compute the Fisherfaces on the given data (in X) and labels (in y): model_svm.compute(X, y) model_knn.compute(X, y) # E = [] # for i in range(min(model.feature.eigenvectors.shape[1], 16)): # e = model.feature.eigenvectors[:,i].reshape(X[0].shape) # E.append(minmax_normalize(e,0,255, dtype=np.uint8)) # subplot(title="Fisherfaces", images=E, rows=4, cols=4, sptitle="Fisherface", colormap=cm.jet, filename="fisherfaces.png") # cv = LeaveOneOutCrossValidation(model) # print(cv0) # cv0.validate(dataset.data,dataset.classes,print_debug=True) cv_svm = KFoldCrossValidation(model_svm, k=10) cv_knn = KFoldCrossValidation(model_knn, k=10) param_grid = [ { 'C': [0.05, 0.1, 0.3, 0.5, 1, 2, 5], 'gamma': [0.001, 0.0001], 'kernel': ['rbf'] }, ] [tX, tY] = read_images('../data/testset/') # cv_svm.validate(X, y) # cv_knn.validate(X, y) gs(model_svm, X, y, param_grid) count1 = 0 count2 = 0 for i in range(len(tY)): r1 = model_svm.predict(tX[i]) r2 = model_knn.predict(tX[i]) if r1[0] == tY[i]: count1 += 1 if r2[0] == tY[i]: count2 += 1 print('SVM ACC:{0}'.format(count1 / len(tY))) print('KNN ACC:{0}'.format(count2 / len(tY))) print(cv_knn.print_results()) print(cv_svm.print_results())