forked from MKFMIKU/PyTorchSRGAN
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
64 lines (48 loc) · 2.1 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# -*- coding: utf-8 -*-
"""Implements some utils
TODO:
"""
import random
import os
import torch
from torchvision import transforms
from torchvision.utils import make_grid
import matplotlib.pyplot as plt
def save_checkpoint(model, epoch, tag):
model_folder = "pretrained/"
model_out_path = model_folder + tag + "_model_epoch_{}.pth".format(epoch)
state = {"epoch": epoch, "model": model}
if not os.path.exists(model_folder):
os.makedirs(model_folder)
torch.save(state, model_out_path)
print("Checkpoint saved to {}".format(model_out_path))
class Visualizer:
def __init__(self, show_step=10, image_size=(30,30)):
self.transform = transforms.Compose([transforms.Normalize(mean = [-2.118, -2.036, -1.804], #Equivalent to un-normalizing ImageNet (for correct visualization)
std = [4.367, 4.464, 4.444]),
transforms.ToPILImage(),
transforms.Scale(image_size)])
self.show_step = show_step
self.step = 0
self.figure, (self.lr_plot, self.hr_plot, self.fake_plot) = plt.subplots(1,3)
self.figure.show()
self.lr_image_ph = None
self.hr_image_ph = None
self.fake_hr_image_ph = None
def show(self, inputsG, inputsD_real, inputsD_fake):
self.step += 1
if self.step == self.show_step:
self.step = 0
i = random.randint(0, inputsG.size(0) -1)
lr_image = self.transform(inputsG[i])
hr_image = self.transform(inputsD_real[i])
fake_hr_image = self.transform(inputsD_fake[i])
if self.lr_image_ph is None:
self.lr_image_ph = self.lr_plot.imshow(lr_image)
self.hr_image_ph = self.hr_plot.imshow(hr_image)
self.fake_hr_image_ph = self.fake_plot.imshow(fake_hr_image)
else:
self.lr_image_ph.set_data(lr_image)
self.hr_image_ph.set_data(hr_image)
self.fake_hr_image_ph.set_data(fake_hr_image)
self.figure.canvas.draw()