Пример #1
0
def model_build(path=os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "res", "train"), feature=PCA(), dist_metric=EuclideanDistance(), k=1, sz=None):
    model_fn = os.path.join(path, "mdl.pkl")
    if not os.path.isfile(model_fn):
        [X,y] = read_images(path, sz=sz)
        classifier = NearestNeighbor(dist_metric=dist_metric, k=k)
        model = PredictableModel(feature=feature, classifier=classifier)
        model.compute(X, y)
        save_model(model_fn, model)
    return load_model(model_fn)
Пример #2
0
 def __init__(self, canvas,  model_path=None, num_elements = 10,  black_and_white = True):
     self.canvas = canvas
     self.blank_canvas = canvas
     self.elements = self.init_elements(num_elements, black_and_white)
     self.num = num_elements
     self.distance = None
     self.model = load_model(model_path)
     self.improve_count = 0
     self.tries_since_last_improvement = 0
     print getDimensionsOfModel(self.model)
Пример #3
0
def produce_prediction(model_path, image_path):
	# model_path = sys.argv[1]
	# image_path = sys.argv[2]

	model = load_model(model_path)
	im = Image.open(image_path)
	im = im.convert("L")
	# resize to given size (if given)
	sz = (300,300)
	if (sz is not None):
	    im = im.resize(sz, Image.ANTIALIAS)
	X = np.asarray(im, dtype=np.uint8)

	prediction = model.predict(X)[0]
	print("Prediction : %d") % (prediction)
	return prediction
Пример #4
0
def produce_prediction(model_path, image_path):
    # model_path = sys.argv[1]
    # image_path = sys.argv[2]

    model = load_model(model_path)
    im = Image.open(image_path)
    im = im.convert("L")
    # resize to given size (if given)
    sz = (300, 300)
    if (sz is not None):
        im = im.resize(sz, Image.ANTIALIAS)
    X = np.asarray(im, dtype=np.uint8)

    prediction = model.predict(X)[0]
    print("Prediction : %d") % (prediction)
    return prediction
Пример #5
0
def process(img):
    """ 0 female, 1 male"""
    import sys, os
    #sys.path.append("./facerec-master/py")
    from facerec.serialization import load_model
    from facerec.validation import MyValidation as MV
    model = load_model("/home/smant/snu/django_page/mysite/cv/myModel.pkl")

    cv = MV(model)
    gray, sangmoon = preprocess(img)
    result = cv.determine(gray)
    result_str = ""

    if result == 0:
        result_str = "Female!!"
    else:
        result_str = "Male!!"
    return result_str, sangmoon
def detailsOfRecognizedPeople(image):
    FACE_DETECTOR_PATH = "{base_path}/haarcascade_frontalface_alt2.xml".format(base_path=os.path.abspath(os.path.dirname(__file__)))
    MODEL_PATH = "{base_path}/robin_saurav_final.pkl".format(base_path=os.path.abspath(os.path.dirname(__file__)))
    class App(object):
        def __init__(self, model, cascade_filename):
            self.model = model
            self.cascade_filename = cascade_filename

        def run(self,frame):
            # Resize the frame to half the original size for speeding up the detection process:
            img = cv2.resize(frame, (frame.shape[1]/2, frame.shape[0]/2), interpolation = cv2.INTER_CUBIC)
            imgout = img.copy()
            
            img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            img = cv2.equalizeHist(img)
            faceCascade = cv2.CascadeClassifier(self.cascade_filename)
            rects = faceCascade.detectMultiScale(img,minNeighbors=5, scaleFactor=1.2,minSize=(30,30),flags=cv2.cv.CV_HAAR_SCALE_IMAGE)

            data_frame = {}
            person_names = []
            for i,r in enumerate(rects):
                x,y,w,h = r
                # (1) Get face, (2) Convert to grayscale & (3) resize to image_size:
                face = img[y:y+h, x:x+w]
                # face = cv2.cvtColor(face,cv2.COLOR_BGR2GRAY)
                face = cv2.resize(face, self.model.image_size, interpolation = cv2.INTER_CUBIC)
                # Get a prediction from the model:
                prediction = self.model.predict(face)[0]
                person_names.append(self.model.subject_names[prediction])

            data_frame.update({"num_faces":len(rects),"faces":rects.tolist(),"identities":person_names,"success":True})
            return data_frame

    model_filename = MODEL_PATH
    print "Loading the model..."
    model = load_model(model_filename)
    recognizer = App(model=model,cascade_filename=FACE_DETECTOR_PATH)
    return recognizer.run(image)
Пример #7
0
                '%(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=options.cascade_filename).run()
Пример #8
0
    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)
Пример #9
0
            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 predict(img_face):
    global model
    global class_names
    X = Image.fromarray(np.uint8(img_face))
    X = X.convert('L')
    X = np.asarray(X, dtype=np.uint8)
    res = model.predict(X)
    #for r in res:
    #    print res
    return class_names[res[0]]


if __name__ == "__main__":
    train("train")
else:
    [model, class_names] = load_model('model.pkl')
Пример #10
0
    # 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(args.size.split("x")[0]),
                      int(args.size.split("x")[1]))
    except:
        to_node(
            "error",
            "Unable to parse the given image size '%s'. Please pass it in the format [width]x[height]!"
            % args.size)
        sys.exit()
    # We have got a dataset to learn a new model from:

    model = load_model(args.model_filename)
    to_node("status", "Model '%s' loaded." % args.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):
        to_node(
            "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=args.camera_id,
        cascade_filename=args.cascade_filename).run()
Пример #11
0
    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()
Пример #12
0
def load_model_file(model_filename):
    load_model(model_filename)
Пример #13
0
    def cameraStack(self):
        model_filename = "model_gender_working.pkl"
        image_size = (200,200)
        [images, labels, subject_names] = read_images("gender/", image_size)
        list_of_labels = list(xrange(max(labels)+1))
        subject_dictionary = dict(zip(list_of_labels, subject_names))
        model = get_model(image_size=image_size, subject_names=subject_dictionary)
        model.compute(images, labels)
        print "save model"
        save_model(model_filename, model)

        self.model_gender = load_model(model_filename)

        model_filename = "model_emotion.pkl"
        image_size = (200, 200)
        [images, labels, subject_names] = read_images("emotion/", image_size)
        list_of_labels = list(xrange(max(labels) + 1))
        subject_dictionary = dict(zip(list_of_labels, subject_names))
        model = get_model(image_size=image_size, subject_names=subject_dictionary)
        model.compute(images, labels)
        print "save model"
        save_model(model_filename, model)

        self.model_emotion = load_model(model_filename)

        faceCascade = 'haarcascade_frontalface_alt2.xml'
        print self.model_gender.image_size
        print "Starting the face detection"

        self.detector = CascadedDetector(cascade_fn=faceCascade, minNeighbors=5, scaleFactor=1.1)
        self.video_capture = cv2.VideoCapture(0)

        while True:
            ret, frame = self.video_capture.read()
            img = cv2.resize(frame, (frame.shape[1] / 2, frame.shape[0] / 2), interpolation=cv2.INTER_CUBIC)
            imgout = img.copy()
            for i, r in enumerate(self.detector.detect(img)):
                x0, y0, x1, y1 = r
                self.x0 = x0
                self.y0 = y0
                self.x1 = x1
                self.y1 = y1
                # (1) Get face, (2) Convert to grayscale & (3) resize to image_size:
                face = img[y0:y1, x0:x1]
                face = cv2.cvtColor(face, cv2.COLOR_BGR2GRAY)
                face = cv2.resize(face, self.model_gender.image_size, interpolation=cv2.INTER_CUBIC)
                # Get a prediction from the model:
                prediction = self.model_gender.predict(face)[0]
                emotion = self.model_emotion.predict(face)[0]
                # Draw the face area in image:
                cv2.rectangle(imgout, (x0, y0), (x1, y1), (0, 255, 0), 2)
                # Draw the predicted name (folder name...):
                self.distance = str(np.asscalar(np.int16(self.y0)))
                draw_str(imgout, (x0 - 20, y0 - 5), self.model_emotion.subject_names[emotion])
                draw_str(imgout, (x0 - 20, y0 - 20), self.model_gender.subject_names[prediction])
                draw_str(imgout, (x0 - 20, y0 - 35), "distance: " + self.distance + "cm")
                self.gender = self.model_gender.subject_names[prediction]
                self.changeSetting(self.currently_playing_button)
                self.changeSetting(self.notifications_button)
                self.changeSetting(self.likes_button)
                self.changeSetting(self.collections_button)
            cv2.imshow('video', imgout)
            ch = cv2.waitKey(10)
            if ch == 27:
                break
Пример #14
0
    if not os.path.isfile(filename):
        return

    img = cv2.imread(filename)

    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    faces = face_cascade.detectMultiScale(gray, 1.3, 5)

    if len(faces):
        x, y, w, h = faces[0]
        cropped = gray[y:y + h, x:x + w]
        if outfile:
            cv2.imwrite(outfile, cropped)
        pil_img = Image.fromarray(cropped)
        return pil_img


if __name__ == "__main__":
    img_path = 'kim1.jpg'
    img = detect_face(img_path)
    img = img.convert("L")
    # dataset = read_from_folder("../faces/")
    # model = get_model(dataset)
    # save_model("model.pkl", model)
    model = load_model("model.pkl")
    p = model.predict(img)
    print "*******", p


Пример #15
0
def loadModel(path_to_model):
    print "\n[+] Loading model from:", path_to_model
    return load_model(path_to_model)
Пример #16
0
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()
Пример #17
0
    return [rated_person, result_average]


# retrieve here from the database if the picture has being liked or not
# do your magic here :)
# image_path is the relative path, i.e. photos/Hanna_54354278435y234v52hb34234nj34/0.jpg
def retrieve_rate(image_path):
    return 1


"""
USAGE
-----------------------------------------------------------------------------------
arg[1] = user_model         # without ".pkl"
arg[2] = <path/to/images>
-----------------------------------------------------------------------------------
"""
if __name__ == "__main__":
    if len(sys.argv) < 3:
        print "USAGE: test_prediction.py username </path/to/images> <feature> <classifier>"
        sys.exit()

    user_model = sys.argv[1]
    test_images_path = sys.argv[2]

    model = load_model(user_model + ".pkl")
    matches = read_images(test_images_path, model)

    # We should plot something and
    # create a folder with Liked people and Not Liked people
Пример #18
0
    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 predict(img_face):
    global model
    global class_names
    X = Image.fromarray(np.uint8(img_face))
    X = X.convert('L')
    X = np.asarray(X, dtype=np.uint8)
    res = model.predict(X)
    #for r in res:
    #    print res
    return class_names[res[0]]

if __name__ == "__main__":
    train("train")
else:
    [model,class_names] = load_model('model.pkl')
Пример #19
0
 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()
    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 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))
    # 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()
Пример #21
0
        while True:
            self.progress_attempt(outpath=new_path)
        # self.draw_all()




if __name__ == '__main__':
    print opts
    model_path = opts["model_path"]
    if not os.path.isfile(model_path) or not model_path.endswith(".plk"):
        print "[+] Not a valid model file:", output_path
        print "[X] Exiting."
        sys.exit()

    model = load_model(model_path)


    width = getDimensionsOfModel(model)[0]
    height = getDimensionsOfModel(model)[1]

    canvas = Image.new("RGBA", (width,height), (255,255,255,255))


    # p = PolygonElement(canvas.size)
    
    # im = p.draw(canvas)
    

    # for i in range(100):
    #     p2 = PolygonElement(canvas.size)    
Пример #22
0
    # 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):
#---------------------------------------------
#    print "Generating model"
    if(not os.path.exists("./temp/mymodel")):
      model.compute(X, y)
      save_model("./temp/mymodel", model)  #saving model here - CHANGE THIS
      exit()
    
#    print "loading model"
    model = load_model("./temp/mymodel")
#    print "loaded model"
    urlForImage = sys.argv[2]
    tmpfilename = "./temp/"+str(urlForImage.split('/')[-1])  #saving image here - CHANGE THIS
    urllib.urlretrieve(urlForImage, tmpfilename)
    im = Image.open(tmpfilename) #add rotate of 90? Don't think so.
    im = im.resize((648,486), Image.ANTIALIAS)
    im = im.convert("L")
#    print "hello",str(im.size)
    im.show()
    to_predict_x = np.asarray(im, dtype=np.uint8)
    li=model.predict(to_predict_x)
    if(int(li[1]['distances'])<10000):
#      print str(li)
#      print str(d)
      print str(d[li[0]])
Пример #23
0
    return [rated_person, result_average]


# retrieve here from the database if the picture has being liked or not
# do your magic here :)
# image_path is the relative path, i.e. photos/Hanna_54354278435y234v52hb34234nj34/0.jpg
def retrieve_rate(image_path):
    return 1


'''
USAGE
-----------------------------------------------------------------------------------
arg[1] = user_model         # without ".pkl"
arg[2] = <path/to/images>
-----------------------------------------------------------------------------------
'''
if __name__ == "__main__":
    if len(sys.argv) < 3:
        print "USAGE: test_prediction.py username </path/to/images> <feature> <classifier>"
        sys.exit()

    user_model = sys.argv[1]
    test_images_path = sys.argv[2]

    model = load_model(user_model + ".pkl")
    matches = read_images(test_images_path, model)

    # We should plot something and
    # create a folder with Liked people and Not Liked people
Пример #24
0
            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..."
    App(model=model,
        camera_id=options.camera_id,
        cascade_filename=options.cascade_filename).run()
Пример #25
0
def load_model_file(model_filename):
    load_model(model_filename)
                except:
                    print "Unexpected error:", sys.exc_info()[0]
                    raise
            c = c + 1
    return [y, folder_names]


pathdir = 'FaceDB_comp/FaceDB2/'
y, subject_names = read_images(pathdir)
list_of_labels = list(xrange(max(y) + 1))
subject_dictionary = dict(zip(list_of_labels, subject_names))
term_crit = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 0xff, 1)
keyPressed = -1
counter = -1
temp = None
model = load_model('Training data1')
#prev_image = np.zeros((256,256), np.uint8)
start = time.time()
#queue=Queue(maxsize=0)
while (keyPressed < 0):
    rval, frame = vc.read()
    img = frame
    counter = counter + 1
    if (counter % 15 == 0):
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        faces = face_cascade.detectMultiScale(gray,
                                              scaleFactor=1.3,
                                              minNeighbors=5,
                                              minSize=(30, 30),
                                              flags=cv2.CASCADE_SCALE_IMAGE)
        temp = faces
Пример #27
0
    if opts["visualize_model"] is True:
        output_path = opts["output"]
        input_path = opts["input"]

        if not os.path.isfile(input_path) or not input_path.endswith(".plk"):
                print "[+] Input seems to be not a model file:", input_path
                print "[X] Exiting."
                sys.exit()

        if not os.path.isdir(output_path):
                print "[+] Creating directories:", output_path
                os.makedirs(output_path)

        print "[+] Loading model", input_path 
        model = load_model(input_path)

        model_viz(model, output_path=output_path, colormap=cm.gray)



    # if len(sys.argv) > 1:
    #     path_to_database = sys.argv[1]
    #     # if not os.path.isdir(path_to_database):
    #     #     print "Wrong path to database provided / folder doesn't exist."
    #     #     sys.exit()

    #     size = 800

    #     computeAndSaveModel(path_to_database, 'model.pkl', size=(size,size), model_type="Eigenface", num_components=0, classifier_neighbours = 1)