-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimage_utils.py
More file actions
61 lines (48 loc) · 1.85 KB
/
Copy pathimage_utils.py
File metadata and controls
61 lines (48 loc) · 1.85 KB
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
import torch
from torchvision.utils import make_grid
from einops import rearrange
import numpy as np
from PIL import Image
from pathlib import Path
from torch_utils import denorm
def _to_pil(img):
if not isinstance(img, Image.Image):
img = Image.fromarray(img)
return img
def save_image(img, path):
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
_to_pil(img).save(str(path))
def _batched_image_to_grid(image, n_cols):
b, _, h, w = image.shape
assert b % n_cols == 0,\
"The batch size should be a multiple of `n_cols` argument"
pad = max(2, int(max(h, w) * 0.02))
grid = make_grid(tensor=image, nrow=n_cols, normalize=False, padding=pad)
grid = grid.clone().permute((1, 2, 0)).detach().cpu().numpy()
grid *= 255.0
grid = np.clip(a=grid, a_min=0, a_max=255).astype("uint8")
for k in range(n_cols + 1):
grid[:, (pad + h) * k: (pad + h) * k + pad, :] = 255
for k in range(b // n_cols + 1):
grid[(pad + h) * k: (pad + h) * k + pad, :, :] = 255
return grid
def image_to_grid(
input_image,
real_output_image,
fake_output_image,
input_img_mean,
input_img_std,
output_img_mean,
output_img_std,
):
input_image = input_image.detach().cpu()
real_output_image = real_output_image.detach().cpu()
fake_output_image = fake_output_image.detach().cpu()
input_image = denorm(input_image, mean=input_img_mean, std=input_img_std)
real_output_image = denorm(real_output_image, mean=output_img_mean, std=output_img_std)
fake_output_image = denorm(fake_output_image, mean=output_img_mean, std=output_img_std)
concat = torch.cat([input_image, real_output_image, fake_output_image], dim=0)
gen_image = rearrange(concat, pattern="(n m) c h w -> (m n) c h w", n=3)
grid = _batched_image_to_grid(gen_image, n_cols=3)
return grid