示例#1
0
            def closure():
                # correct the values of updated input image
                input_img.data.clamp_(0, 1)

                optimizer.zero_grad()
                model(input_img)
                style_score = 0
                content_score = 0

                for sl in style_losses:
                    style_score += sl.loss
                for cl in content_losses:
                    content_score += cl.loss

                style_score *= style_weight
                content_score *= content_weight

                loss = style_score + content_score
                loss.backward()

                run[0] += 1
                if run[0] % 5 == 0:
                    print("run {}:".format(run))
                    print('Style Loss : {:4f} Content Loss: {:4f}'.format(
                        style_score.item(), content_score.item()))
                    print()
                    if prev:
                        img_handler.imshow(input_img,
                                           unloader,
                                           title='Run {}'.format(run))
                    if runs:
                        run_save = os.path.join(run_path, f'run{run}.jpg')
                        img_handler.imsave(run_save, unloader, input_img)
                return style_score + content_score
示例#2
0
    while not os.path.isfile(content_path):
        content_path = input('E: Image not found. Path to Content: ')

    style_img = img_handler.image_loader(device, loader, style_path)
    content_img = img_handler.image_loader(device, loader, content_path)

    # TODO remove once image size class is implemented
    assert style_img.size() == content_img.size(), \
        "we need to import style and content imsages of the same size"

    unloader = transforms.ToPILImage()  # reconvert into PIL image

    if plt_prvs:
        plt.ion()
        plt.figure()
        img_handler.imshow(style_img, unloader, title='Style Image')

        plt.figure()
        img_handler.imshow(content_img, unloader, title='Content Image')

    # --- IMPORTING THE MODEL ---
    cnn = models.vgg19(pretrained=True).features.to(device).eval()

    cnn_normalization_mean = torch.tensor([0.485, 0.456, 0.406]).to(device)
    cnn_normalization_std = torch.tensor([0.229, 0.224, 0.225]).to(device)

    # desired depth layers to compute style/content losses :
    content_layers_default = ['conv_4']
    style_layers_default = ['conv_1', 'conv_2', 'conv_3', 'conv_4', 'conv_5']

    input_path = input("Input Image Path or 'noise': ")