Beispiel #1
0
def main():
    images_transformed_path = get_config('images_transformed_path')
    with open(images_transformed_path, 'w') as output_file:
        writer = csv.writer(output_file, delimiter=',')

        training_images_labels_path = get_config('training_images_labels_path')
        with open(training_images_labels_path, 'r') as file:
            lines = file.readlines()

        for line in lines:
            print("\n\n" + line.strip())
            image_path, image_label = line.split()

            # Read the input image.
            frame = cv2.imread(image_path)
            # `frame` is a HxW numpy ndarray of triplets (pixels), where H and W are
            # the dimensions of the input image.
            # cv2.imshow("Original", frame)
            try:
                frame = apply_image_transformation(frame)
                write_frame_to_file(frame, image_label, writer)
            except Exception:
                exception_traceback = traceback.format_exc()
                print(
                    "Error while applying image transformation on image path '{}' with the following exception trace:\n{}"
                    .format(image_path, exception_traceback))
                continue
            # cv2.waitKey(1000)
    cv2.destroyAllWindows()
    print "The program completed successfully !!"
def main():
    model_name = sys.argv[1]
    if model_name not in ['svm', 'logistic', 'knn']:
        logger.error("Invalid model-name '{}'!".format(model_name))
        return

    logger.info("Using model '{}'...".format(model_name))

    model_serialized_path = get_config(
        'model_{}_serialized_path'.format(model_name))
    logger.info(
        "Model deserialized from path '{}'".format(model_serialized_path))

    for root, dir, filex in os.walk("C:/xampp/htdocs/file_upload_api/files/",
                                    topdown=True):
        image_path = "C:/xampp/htdocs/file_upload_api/files/" + filex[0]
        break
    frame = cv2.imread(image_path)
    try:
        frame = apply_image_transformation(frame)
        frame_flattened = frame.flatten()
        classifier_model = joblib.load(model_serialized_path)
        predicted_labels = classifier_model.predict(
            frame_flattened.reshape(1, -1))
        predicted_label = predicted_labels[0]
        print("Predicted labelx={}".format(predicted_label))
    except Exception:
        exception_traceback = traceback.format_exc()
        print(
            "Error while applying image transformation on image path '{}' with the following exception trace:\n{}"
            .format(image_path, exception_traceback))
    os.remove(image_path)
    cv2.destroyAllWindows()
    logger.info("The program completed successfully !!")
Beispiel #3
0
def main():
    model_name = sys.argv[1]
    if model_name not in ['svm', 'logistic', 'knn']:
        print("Invalid model-name '{}'!".format(model_name))
        return

    print("Using model '{}'...".format(model_name))

    model_serialized_path = get_config(
        "model_{}_serialized_path".format(model_name))
    print("Model deserialized from path '{}'".format(model_serialized_path))

    camera = cv2.VideoCapture(0)

    while True:

        ret, frame = camera.read()
        cv2.imshow("Recording", frame)
        key = cv2.waitKey(1)
        if key == ord('q'):
            break
        elif key == ord('c'):
            if not ret:
                print("Failed to capture image!")
                continue
            frame = resize_image(frame, 400)
            r = cv2.selectROI(frame)
            imCrop = frame[int(r[1]):int(r[1] + r[3]),
                           int(r[0]):int(r[0] + r[2])]
            cv2.imshow("Image", imCrop)
            #cv2.imshow("Webcam recording", frame)
            frame = imCrop
            try:
                frame = apply_image_transformation(frame)
                frame_flattened = frame.flatten()
                classifier_model = joblib.load(model_serialized_path)
                predicted_labels = classifier_model.predict(frame_flattened)
                predicted_label = predicted_labels[0]
                print("Predicted label = {}".format(predicted_label))
                predicted_image = get_image_from_label(predicted_label)
                predicted_image = resize_image(predicted_image, 200)
                cv2.imshow("Prediction = '{}'".format(predicted_label),
                           predicted_image)
                engine = pyttsx.init()
                engine.say("The predicted text is " + str(predicted_label))
                engine.runAndWait()
                engine.stop()
            except Exception:
                exception_traceback = traceback.format_exc()
                print(
                    "Error while applying image transformation with the following exception trace:\n{}"
                    .format(exception_traceback))

    cv2.destroyAllWindows()
    print "The program completed successfully !!"
def mainimage():
    font = cv2.FONT_HERSHEY_SIMPLEX
    bottomLeftCornerOfText = (10, 50)
    fontScale = 1
    fontColor = (255, 255, 255)
    lineType = 2
    model_name = "svm"
    if model_name not in ['svm']:
        print("Invalid model-name '{}'!".format(model_name))
        return

    print("Using model '{}'...".format(model_name))

    model_serialized_path = get_config(
        "model_{}_serialized_path".format(model_name))
    print("Model deserialized from path '{}'".format(model_serialized_path))
    classifier_model = joblib.load(model_serialized_path)
    import tkFileDialog
    tk.Tk().withdraw()
    path = tkFileDialog.askopenfile()
    img = cv2.imread(path.name)
    frame = resize_image(img, 400)
    image = frame
    frame = cv2.resize(img, (50, 50))

    try:
        frame = apply_image_transformation(frame)
        frame_flattened = frame.flatten()

        print classifier_model
        predicted_labels = classifier_model.predict(frame_flattened)
        print("Predicted label = {}".format(predicted_labels))
        cv2.putText(image, str(predicted_labels), bottomLeftCornerOfText, font,
                    fontScale, fontColor, lineType)
        cv2.imshow("frame", image)
        key = cv2.waitKey(2)
        if key == 27:
            cv2.destroyAllWindows()
    except Exception:
        exception_traceback = traceback.format_exc()
        print(
            "Error while applying image transformation with the following exception trace:\n{}"
            .format(exception_traceback))
    cv2.waitKey(0)
    print "The program completed successfully !!"
def main():
    model_name = "svm"
    if model_name not in ['svm', 'logistic', 'knn']:
        print("Invalid model-name '{}'!".format(model_name))
        return

    print("Using model '{}'...".format(model_name))

    model_serialized_path = get_config(
        "model_{}_serialized_path".format(model_name))
    print("Model deserialized from path '{}'".format(model_serialized_path))

    camera = cv2.VideoCapture(0)

    while True:
        ret, frame = camera.read()
        if not ret:
            print("Failed to capture image!")
            continue
        frame = resize_image(frame, 400)
        cv2.imshow("Webcam recording", frame)
        try:
            frame = apply_image_transformation(frame)
            frame_flattened = frame.flatten()
            #print(model_serialized_path)
            #model_serialized_path = "C:\\Users\\AanikaRahman\\Documents\\GitHub\\ASL1\\Sign-Language-Recognition\\data\\generated\\output\\svm\\model-serialized-svm.pkl"
            classifier_model = joblib.load(model_serialized_path)
            #classifier_model = pickle.load(open(model_serialized_path),encoding='latin1')
            predicted_labels = classifier_model.predict(frame_flattened)
            predicted_label = predicted_labels[0]
            print("Predicted label = {}".format(predicted_label))
            predicted_image = get_image_from_label(predicted_label)
            predicted_image = resize_image(predicted_image, 200)
            cv2.imshow("Prediction = '{}'".format(predicted_label),
                       predicted_image)
        except Exception:
            exception_traceback = traceback.format_exc()
            print(
                "Error while applying image transformation with the following exception trace:\n{}"
                .format(exception_traceback))
        cv2.waitKey(2000)
        cv2.destroyAllWindows()
    cv2.destroyAllWindows()
    print("The program completed successfully !!")
Beispiel #6
0
def main():
    model_name = sys.argv[1]
    if model_name not in ['svm', 'logistic', 'knn']:
        logger.error("Invalid model-name '{}'!".format(model_name))
        return

    logger.info("Using model '{}'...".format(model_name))

    model_serialized_path = get_config(
        'model_{}_serialized_path'.format(model_name))
    logger.info(
        "Model deserialized from path '{}'".format(model_serialized_path))

    testing_images_labels_path = get_config('testing_images_labels_path')
    with open(testing_images_labels_path, 'r') as file:
        lines = file.readlines()
        for line in lines:
            if not line:
                continue
            image_path, image_label = line.split()
            frame = cv2.imread(image_path)
            try:
                frame = apply_image_transformation(frame)
                frame_flattened = frame.flatten()
                classifier_model = joblib.load(model_serialized_path)
                predicted_labels = classifier_model.predict(
                    frame_flattened.reshape(1, -1))
                predicted_label = predicted_labels[0]
                logger.info('"{}" {} ---> {}'.format(image_path, image_label,
                                                     predicted_label))
                if image_label != predicted_label:
                    log_msg = "Incorrect prediction '{}' instead of '{}'\n)"
                    logger.error(log_msg.format(predicted_label, image_label))
                    cv2.waitKey(5000)
            except Exception:
                exception_traceback = traceback.format_exc()
                logger.error("Error applying image transformation to image "
                             "'{}'".format(image_path))
                logger.debug(exception_traceback)
                continue
    cv2.destroyAllWindows()
    logger.info("The program completed successfully !!")
def main():
    model_name = sys.argv[1]
    if model_name not in ['svm', 'logistic', 'knn']:
        print("Invalid model-name '{}'!".format(model_name))
        return

    print("Using model '{}'...".format(model_name))

    model_serialized_path = get_config(
        "model_{}_serialized_path".format(model_name))
    print("Model deserialized from path '{}'".format(model_serialized_path))

    camera = cv2.VideoCapture(0)

    while True:
        ret, frame = camera.read()
        if not ret:
            print("Failed to capture image!")
            continue
        frame = resize_image(frame, 400)
        cv2.imshow("Webcam recording", frame)
        try:
            frame = apply_image_transformation(frame)
            frame_flattened = frame.flatten()
            classifier_model = joblib.load(model_serialized_path)
            predicted_labels = classifier_model.predict(frame_flattened)
            predicted_label = predicted_labels[0]
            print("Predicted label = {}".format(predicted_label))
            predicted_image = get_image_from_label(predicted_label)
            predicted_image = resize_image(predicted_image, 200)
            cv2.imshow("Prediction = '{}'".format(predicted_label),
                       predicted_image)
        except Exception:
            exception_traceback = traceback.format_exc()
            print(
                "Error while applying image transformation with the following exception trace:\n{}"
                .format(exception_traceback))
        cv2.waitKey(10000)
        cv2.destroyAllWindows()
    cv2.destroyAllWindows()
    print "The program completed successfully !!"
def main():
    model_name = sys.argv[1]
    if model_name not in ['svm', 'logistic', 'knn']:
        print("Invalid model-name '{}'!".format(model_name))
        return

    print("Using model '{}'...".format(model_name))

    model_serialized_path = get_config(
        'model_{}_serialized_path'.format(model_name))
    print("Model deserialized from path '{}'".format(model_serialized_path))

    testing_images_labels_path = get_config('testing_images_labels_path')
    with open(testing_images_labels_path, 'r') as file:
        lines = file.readlines()
        for line in lines:
            print("\n\n" + line.strip())
            image_path, image_label = line.split()
            frame = cv2.imread(image_path)
            try:
                frame = apply_image_transformation(frame)
                frame_flattened = frame.flatten()
                classifier_model = joblib.load(model_serialized_path)
                predicted_labels = classifier_model.predict(frame_flattened)
                predicted_label = predicted_labels[0]
                print("Predicted label = {}".format(predicted_label))
                engine = pyttsx.init()
                engine.say("The predicted text is " + str(predicted_label))
                engine.runAndWait()
                engine.stop()
                if image_label != predicted_label:
                    print("Incorrect prediction!!")
                    cv2.waitKey(5000)
            except Exception:
                exception_traceback = traceback.format_exc()
                print("Error while applying image transformation on image path '{}' with the following exception trace:\n{}".format(
                    image_path, exception_traceback))
                continue
    cv2.waitKey()
    cv2.destroyAllWindows()
    print "The program completed successfully !!"
Beispiel #9
0
def main():
    images_transformed_path = get_config('images_transformed_path')
    images_transformed_path = get_config('images_transformed_path')
    with open(images_transformed_path, 'w') as output_file:
        writer = csv.writer(output_file, delimiter=',')

        training_images_labels_path = get_config('training_images_labels_path')
        with open(training_images_labels_path, 'r') as file:
            lines = file.readlines()
        images = []
        labels = []
        for line in lines:
            #print("\n\n" + line.strip())
            image_path, image_label = line.split()

            # Read the input image.
            frame = cv2.imread(image_path)
            # `frame` is a HxW numpy ndarray of triplets (pixels), where H and W are
            # the dimensions of the input image.
            # cv2.imshow("Original", frame)
            frame = apply_image_transformation(frame)
            images.append(frame)
            labels.append(image_label)

        X_train, X_test, Y_train, Y_test = divide_data_train_test(
            images, labels, 0.2)
        X_train = np.array(X_train)
        Y_train = np.array(Y_train)
        Y_train = vec_translate(Y_train)
        X_test = np.array(X_test)
        Y_test = vec_translate(Y_test)
        Y_test = np.array(Y_test)
        X_train = X_train / 255.
        X_test = X_test / 255.

        Y_train = convert_to_one_hot(Y_train, 20).T
        Y_test = convert_to_one_hot(Y_test, 20).T
        #print(X_train.shape)
    _, _, parameters = model(X_train, Y_train, X_test, Y_test)

    print("Done!\n")
def main():
    transformed_images_path = get_config('transformed_images_path')
    os.makedirs(os.path.dirname(transformed_images_path), exist_ok=True)
    with open(transformed_images_path, 'w') as output_file:
        writer = csv.writer(output_file, delimiter=',')
        training_images_labels_path = get_config('training_images_labels_path')
        with open(training_images_labels_path, 'r') as file:
            lines = file.readlines()
        if show_progress_bar:
            progress_bar = tqdm(total=len(lines),
                                desc='Transforming images',
                                unit=' pics')
        for line in lines:
            logger.debug("\n\n" + line.strip())
            image_path, image_label = line.split()
            # Read the input image.
            frame = cv2.imread(image_path)
            # `frame` is a HxW numpy ndarray of triplets (pixels),
            # where H and W are the dimensions of the input image.
            # cv2.imshow("Original", frame)
            try:
                if show_progress_bar:
                    progress_bar.update()
                frame = apply_image_transformation(frame)
                write_frame_to_file(frame, image_label, writer)
            except Exception:
                # Its normal to get errors on some images!!
                exception_traceback = traceback.format_exc()
                logger.error("Error applying image transformation to image "
                             "'{}'".format(image_path))
                logger.debug(exception_traceback)
                continue
            # cv2.waitKey(1000)
    cv2.destroyAllWindows()
    if show_progress_bar:
        progress_bar.close()
    logger.info("The program completed successfully !!")