forked from hanzhanggit/StackGAN
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
75 lines (62 loc) · 2.07 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
65
66
67
68
69
70
71
72
73
74
75
"""
Some codes from
https://github.com/openai/improved-gan/blob/master/imagenet/utils.py
"""
from __future__ import division
from __future__ import print_function
import numpy as np
import scipy.misc
import os
import errno
def get_image(image_path, image_size, is_crop=False, bbox=None):
global index
out = transform(imread(image_path), image_size, is_crop, bbox)
return out
def custom_crop(img, bbox):
# bbox = [x-left, y-top, width, height]
imsiz = img.shape # [height, width, channel]
# if box[0] + box[2] >= imsiz[1] or\
# box[1] + box[3] >= imsiz[0] or\
# box[0] <= 0 or\
# box[1] <= 0:
# box[0] = np.maximum(0, box[0])
# box[1] = np.maximum(0, box[1])
# box[2] = np.minimum(imsiz[1] - box[0] - 1, box[2])
# box[3] = np.minimum(imsiz[0] - box[1] - 1, box[3])
center_x = int((2 * bbox[0] + bbox[2]) / 2)
center_y = int((2 * bbox[1] + bbox[3]) / 2)
R = int(np.maximum(bbox[2], bbox[3]) * 0.75)
y1 = np.maximum(0, center_y - R)
y2 = np.minimum(imsiz[0], center_y + R)
x1 = np.maximum(0, center_x - R)
x2 = np.minimum(imsiz[1], center_x + R)
img_cropped = img[y1:y2, x1:x2, :]
return img_cropped
def transform(image, image_size, is_crop, bbox):
image = colorize(image)
if is_crop:
image = custom_crop(image, bbox)
#
transformed_image =\
scipy.misc.imresize(image, [image_size, image_size], 'bicubic')
return np.array(transformed_image)
def imread(path):
img = scipy.misc.imread(path)
if len(img.shape) == 0:
raise ValueError(path + " got loaded as a dimensionless array!")
return img.astype(np.float)
def colorize(img):
if img.ndim == 2:
img = img.reshape(img.shape[0], img.shape[1], 1)
img = np.concatenate([img, img, img], axis=2)
if img.shape[2] == 4:
img = img[:, :, 0:3]
return img
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise