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
65
66
67
68
69
70
71
72
73
74
75
76
|
from __future__ import print_function
import torch
import numpy as np
from PIL import Image
import os
# Converts a Tensor into a Numpy array
# |imtype|: the desired type of the converted numpy array
def tensor2im(image_tensor, imtype=np.uint8):
image_numpy = image_tensor[0].cpu().float().numpy()
if image_numpy.shape[0] == 1:
image_numpy = np.tile(image_numpy, (3, 1, 1))
image_numpy = (np.transpose(image_numpy, (1, 2, 0)) + 1) / 2.0 * 255.0
return image_numpy.astype(imtype)
def diagnose_network(net, name='network'):
mean = 0.0
count = 0
for param in net.parameters():
if param.grad is not None:
mean += torch.mean(torch.abs(param.grad.data))
count += 1
if count > 0:
mean = mean / count
print(name)
print(mean)
def save_image(image_numpy, image_path):
image_pil = Image.fromarray(image_numpy)
image_pil.save(image_path)
def print_numpy(x, val=True, shp=False):
x = x.astype(np.float64)
if shp:
print('shape,', x.shape)
if val:
x = x.flatten()
print('mean = %3.3f, min = %3.3f, max = %3.3f, median = %3.3f, std=%3.3f' % (
np.mean(x), np.min(x), np.max(x), np.median(x), np.std(x)))
def mkdirs(paths):
if isinstance(paths, list) and not isinstance(paths, str):
for path in paths:
mkdir(path)
else:
mkdir(paths)
def mkdir(path):
if not os.path.exists(path):
os.makedirs(path)
def crop_image(img, xy, scale_factor):
'''Crop the image around the tuple xy
Inputs:
-------
img: Image opened with PIL.Image
xy: tuple with relative (x,y) position of the center of the cropped image
x and y shall be between 0 and 1
scale_factor: the ratio between the original image's size and the cropped image's size
'''
center = (img.size[0] * xy[0], img.size[1] * xy[1])
new_size = (img.size[0] / scale_factor, img.size[1] / scale_factor)
left = max (0, (int) (center[0] - new_size[0] / 2))
right = min (img.size[0], (int) (center[0] + new_size[0] / 2))
upper = max (0, (int) (center[1] - new_size[1] / 2))
lower = min (img.size[1], (int) (center[1] + new_size[1] / 2))
cropped_img = img.crop((left, upper, right, lower))
return cropped_img
|