-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathutils.py
70 lines (54 loc) · 1.93 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
import numpy as np
import cv2
def border_pad(image, cfg):
h, w, c = image.shape
if cfg.border_pad == 'zero':
image = np.pad(image, ((0, cfg.long_side - h),
(0, cfg.long_side - w), (0, 0)),
mode='constant',
constant_values=0.0)
elif cfg.border_pad == 'pixel_mean':
image = np.pad(image, ((0, cfg.long_side - h),
(0, cfg.long_side - w), (0, 0)),
mode='constant',
constant_values=cfg.pixel_mean)
else:
image = np.pad(image, ((0, cfg.long_side - h),
(0, cfg.long_side - w), (0, 0)),
mode=cfg.border_pad)
return image
def fix_ratio(image, cfg):
h, w, c = image.shape
if h >= w:
ratio = h * 1.0 / w
h_ = cfg.long_side
w_ = round(h_ / ratio)
else:
ratio = w * 1.0 / h
w_ = cfg.long_side
h_ = round(w_ / ratio)
image = cv2.resize(image, dsize=(w_, h_), interpolation=cv2.INTER_LINEAR)
image = border_pad(image, cfg)
return image
def transform(image, cfg):
print(image.ndim)
if image.ndim == 3: image = image[:,:,0]
assert image.ndim == 2, "image must be gray image"
if cfg.use_equalizeHist:
image = cv2.equalizeHist(image)
if cfg.gaussian_blur > 0:
image = cv2.GaussianBlur(
image,
(cfg.gaussian_blur, cfg.gaussian_blur), 0)
image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)
image = fix_ratio(image, cfg)
# augmentation for train or co_train
# normalization
image = image.astype(np.float32) - cfg.pixel_mean
# vgg and resnet do not use pixel_std, densenet and inception use.
if cfg.pixel_std:
image /= cfg.pixel_std
# normal image tensor : H x W x C
# torch image tensor : C X H X W
image = image.transpose((2, 0, 1))
return image