This repository has been archived by the owner on Nov 7, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
visualize_vae.py
55 lines (42 loc) · 1.7 KB
/
visualize_vae.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
import argparse
import matplotlib.pyplot as plt
import os
import torch
import torchvision.transforms as transforms
from PIL import Image
from torch.utils.data import DataLoader
from torchvision.datasets import ImageFolder
from utils.hyperparameters import DIM_LATENT, NORMALIZE_MEAN, NORMALIZE_STDEV
from utils.img_transforms import transform, transform_back
from utils.plots import grid_add_img
from models.vae import VAE
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--vae', type=str, nargs='+', required=True,\
help="path to vae")
parser.add_argument('--imgdir', type=str, required=True,\
help="path to image folder")
args = parser.parse_args()
img_names = os.listdir(args.imgdir)
n_imgs = len(img_names)
rows = len(args.vae) + 1
fig = plt.figure()
with torch.no_grad():
for k in range(len(args.vae)):
vae = VAE(DIM_LATENT)
vae.load_state_dict(torch.load(args.vae[k]))
for i in range(n_imgs):
path = os.path.join(args.imgdir, img_names[i])
img = Image.open(path)
x_true = transform(img)
x_true = x_true.unsqueeze(0)
x_true = x_true.view(1, 3, 64, 64)
x_rec, mu, logvar = vae(x_true)
x_true = x_true.squeeze(0)
x_rec = x_rec.squeeze(0)
img_true = transform_back(x_true)
img_rec = transform_back(x_rec)
if k == 0: grid_add_img(img_true, fig, rows, n_imgs, i+1)
grid_add_img(img_rec, fig, rows, n_imgs, (k+1)*n_imgs+i+1)
fig.subplots_adjust(wspace=0, hspace=0)
plt.show()