コード例 #1
0
def main_test(image: str,
              use_abs_path=False,
              do_output_drawing=False,
              do_solving=False,
              show_detected_board=False,
              main_enable_debug=False):
    start_time = time.time()

    if use_abs_path:
        original_img = load_img(image, useAbsPath=True)
    else:
        original_img = load_img(image, useAbsPath=False)
    if original_img is None:
        raise ValueError("Image loading error!")

    # process original img
    sudoku_field_img_array = cut_image(original_img,
                                       enable_debug=main_enable_debug)
    if sudoku_field_img_array is None:
        raise ValueError("Board not found")

    detected_array = process_fields(sudoku_field_img_array)
    if show_detected_board:
        draw_detected(detected_array, None)

    print(np.array(detected_array))
    # sudoku solving
    solved_array = None
    if do_solving:
        alg = backtracking.Possible(np.array(detected_array))
        if not alg.solve():
            raise ValueError("Cannot solve sudoku")
        else:
            solved_array = alg.grid
    print(np.array(solved_array))

    # draw the output to the original image
    if do_output_drawing:
        if solved_array is None:
            solved_array = np.ones((9, 9), dtype="uint8")

        draw_output(detected_array, solved_array)
        show_imgs_for_nn()
        wait_for_window_close_or_keypress()

    print('Time spent: {}'.format(time.time() - start_time))
コード例 #2
0
def test_save_img() -> None:
    import os
    try:
        os.mkdir('test_img/')
    except FileExistsError:
        pass
    for name in os.listdir('test_img/'):
        os.remove('test_img/' + name)
    for photo in os.listdir('img/'):
        print(photo)
        original_img = load_img(photo)
        sudoku_field_img_array = cut_image(original_img,
                                           enable_debug=False,
                                           enable_save=True,
                                           saveName=photo)
        if sudoku_field_img_array is not None:
            detected_array = process_fields(sudoku_field_img_array,
                                            enable_save=True,
                                            saveName=photo)
            solved_array = np.ones((9, 9), dtype="uint8")
            draw_output(detected_array, solved_array, save_name=photo)

    exit(0)
コード例 #3
0
def pre_process_image(path):
    img = load_img(path)
    img = tf.keras.applications.vgg19.preprocess_input(img)
    return img
コード例 #4
0
]


def pre_process_image(path):
    img = load_img(path)
    img = tf.keras.applications.vgg19.preprocess_input(img)
    return img


# Content Loss
def content_loss_f(content, generated):
    return tf.losses.mean_squared_error(content, generated)


##
content_img = load_img(config.CONTENT_IMG)
style_img = load_img(config.STYLE_IMG)

model = StyleTransferModel(CONTENT_L, STYLE_L)

style_targets = model(style_img)['style']
content_target = model(content_img)['content']

num_style_layers = len(STYLE_L)
num_content_layers = len(CONTENT_L)


# Style Loss
def loss_f(outputs):
    style_outputs = outputs['style']
    content_outputs = outputs['content']
コード例 #5
0
 def __getitem__(self, idx):
     return hlp.load_img(hlp.jn(self._path_root_imgs, self._files[idx]))
コード例 #6
0
    files = os.listdir(TRAINED_MODELS_PATH)
    for file in files:
        if os.path.isdir(TRAINED_MODELS_PATH + file):
            print(file)


parse_args()
with tf.Session() as sess:
    # Check if there is a model trained on the given style
    if not os.path.isdir(TRAINED_MODELS_PATH + STYLE):
        print("No trained model with the style '%s' was found." % STYLE)
        list_styles()
        exit(1)

    # Load and initialize the image to be stlylized
    input_img, _ = helpers.load_img(INPUT_PATH)
    input_img = tf.convert_to_tensor(input_img, dtype=tf.float32)
    input_img = tf.expand_dims(input_img, axis=0)

    # Initialize new generative net
    with tf.variable_scope('generator'):
        gen = generator.Generator()
        gen.build(tf.convert_to_tensor(input_img))
        sess.run(tf.global_variables_initializer())

    # Restore previously trained model
    ckpt_dir = TRAINED_MODELS_PATH + STYLE
    saved_path = ckpt_dir + "/{}".format(STYLE)
    saver = tf.train.Saver()
    saver.restore(sess, saved_path)
コード例 #7
0
    model.parameters(),
    lr=LEARNING_RATE,
    momentum=MOMENTUM,
)

# training loop
for epoch in range(EPOCHS):
    running_loss = 0  # sum losses in each batch

    # batches
    for i in range(0, len(x_train), BATCH_SIZE):
        optimizer.zero_grad()  # clear gradients

        # load X
        batch_x = [
            helpers.load_img(os.path.join(TRAIN_PATH, img))
            for img in x_train[i:BATCH_SIZE + i]
        ]
        batch_x = torch.from_numpy(np.array(batch_x))
        batch_x = batch_x.float()
        batch_x = batch_x.cuda()

        # load Y
        batch_y = [[y] for y in y_train[i:BATCH_SIZE + i]]
        batch_y = torch.from_numpy(np.array(batch_y))
        batch_y = batch_y.float()
        batch_y = batch_y.cuda()

        # forward pass
        y_pred = model(batch_x)
        loss = loss_fn(y_pred, batch_y)
コード例 #8
0
# local files
from helpers import load_img
from models import VGG1


def predict(img):

    img = np.array([img])
    img = torch.from_numpy(img)
    img = img.float()

    with torch.no_grad():
        y = model(img)

    if y.item() > 0.5:
        category = "DOG"
    else:
        category = "CAT"

    return (y.item(), category)


# load model
model = VGG1()
model.load_state_dict(torch.load("./weights/vgg1-weights.pt"))

# predict
img = load_img("./data/test1/1001.jpg")
pred = predict(img)
print("Confidence: {:0.7f}\nClass: {:s}".format(pred[0], pred[1]))