augment.py 5.46 KB
Newer Older
Alessia Marcolini's avatar
Alessia Marcolini committed
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
import numpy as np
from skimage import transform
from skimage import color
from skimage import draw

def rotate_img(img, masks=None, max_rotate = 90):
    angle = np.random.uniform(-1,1)
    angle = angle*max_rotate
    rotate_angle = np.pi*angle/180
    
    affine_tf = transform.AffineTransform(rotation=rotate_angle)
    
    img_ = transform.warp(img, inverse_map=affine_tf,mode='wrap', preserve_range=True)
    
    if masks is None:
        return(img_)
    else:
        masks_ = []
        for mask in masks:
            mask_ = transform.warp(mask, inverse_map=affine_tf, mode='wrap', preserve_range=True)
            masks_.append(mask_)
        return(img_, masks_)

def shear_img(img, masks=None, max_shear = 10):
    angle = np.random.uniform(-1,1)
    angle = angle*max_shear
    shear_angle = np.pi*angle/180
    
    affine_tf = transform.AffineTransform(shear=shear_angle)
    img_ = transform.warp(img, inverse_map=affine_tf, mode='wrap', preserve_range=True)
    
    if masks is None:
        return(img_)
    else:
        masks_ = []
        for mask in masks:
            mask_ = transform.warp(mask, inverse_map=affine_tf, mode='wrap', preserve_range=True)
#            mask_[mask_<255] = 0
            masks_.append(mask_)
        return(img_, masks_)

def rescale_img(img, masks=None, max_scale = [0.5, 2]):
    scale_h = np.random.uniform(max_scale[0], max_scale[1])
    scale_w = np.random.uniform(max_scale[0], max_scale[1])
    
    img_ = transform.rescale(img, (scale_h, scale_w), mode='wrap', preserve_range=True)
    
    if masks is None:
        return(img_)
    else:
        masks_ = []
        for mask in masks:
            mask_ = transform.rescale(mask, (scale_h, scale_w), mode='wrap', preserve_range=True)
#            mask_[mask_<255] = 0
            masks_.append(mask_)
        return(img_, masks_)

def crop_img(img, masks=None, max_crop = [0.5, 0.5]):
    img_ = np.copy(img)
    
    h,w = img_.shape[0], img_.shape[1]
    
    size_h = int(np.random.uniform(int((1-max_crop[0])*h), h))
    size_w = int(np.random.uniform(int((1-max_crop[1])*w), w))
    
    h0 = int(np.random.uniform(0, h - size_h))
    w0 = int(np.random.uniform(0, w - size_w))
    
    img_ = img_[h0 : h0+size_h, w0 : w0+size_w]
    
    if masks is None:
        return(img_)
    else:
        masks_ = []
        for mask in masks:
            mask_ = mask[h0 : h0+size_h, w0 : w0+size_w]
            masks_.append(mask_)
        return(img_, masks_)

def flip_img(img, masks=None, flip_probs = [0.5, 0.5]):
    img_ = np.copy(img)
    
    h_flip = np.random.uniform(0, 1)<flip_probs[0]
    v_flip = np.random.uniform(0, 1)<flip_probs[1]
    
    if h_flip:
        img_ = img_[:,::-1]
    if v_flip:
        img_ = img_[::-1,:]
    
    if masks is None:
        return(img_)
    else:
        masks_ = []
        for mask_ in masks:
            if h_flip:
                mask_ = mask_[:,::-1]
            if v_flip:
                mask_ = mask_[::-1,:]
            masks_.append(mask_)
        return(img_, masks_)

#%% greyscale augment
def bright_contrast(img, max_scale=0.01):
    img_ = np.copy(img)
    
    low = np.min(img_)
    high = np.max(img_)
    
    scale = np.random.uniform(max_scale, 1)
    shift = np.random.uniform(0, 1-scale)

    img_ = (img_ - low)/(high - low)
    img_ = img_*scale + shift
    
    img_[0,0] = 0
    img_[-1,-1] = 1
    
    return(img_)

def invert(img, inv_prob=0.5):
    img_ = np.copy(img)
    
    invert = np.random.random()<inv_prob
    if invert:
        img_ = -1*img_ + 1
    return(img_)
    
#%% morphological augment
def random_circle(img, max_radius = 0.5, alpha=0.25):
    img_ = np.copy(img)
    
    h,w = img_.shape[0], img_.shape[1]
    
    random_col = np.random.random()
    random_r = np.random.randint(0, h)
    random_c = np.random.randint(0, w)
    random_radius = np.random.randint(0.5, int(np.max([h,w])*max_radius))
    
    rr,cc = draw.circle(r = random_r, c = random_c, radius = random_radius, shape=(h, w))
    img_h = color.rgb2hsv(img_)
    
    img_h[rr,cc, 0] = random_col
    img_h[rr,cc, 1] = 0.1
    img_h[rr,cc, 2] = 1 - img_h[rr,cc, 2]*alpha
#    
    out = color.hsv2rgb(img_h)
    return(out)
    
#%% color augment
def generate_3d():
    """Generate a 3D random rotation matrix.
    Returns:
        np.matrix: A 3D rotation matrix.
    """
    x1, x2, x3 = np.random.rand(3)
    R = np.matrix([[np.cos(2 * np.pi * x1), np.sin(2 * np.pi * x1), 0],
                   [-np.sin(2 * np.pi * x1), np.cos(2 * np.pi * x1), 0],
                   [0, 0, 1]])
    v = np.matrix([[np.cos(2 * np.pi * x2) * np.sqrt(x3)],
                   [np.sin(2 * np.pi * x2) * np.sqrt(x3)],
                   [np.sqrt(1 - x3)]])
    H = np.eye(3) - 2 * v * v.T
    M = -H * R
    return M

def rotate_colors(img):
    rotation_matrix = np.array(generate_3d())
    img_rotated = np.dot(img, rotation_matrix)
    img_rotated = (img_rotated - np.min(img_rotated))/(np.max(img_rotated) - np.min(img_rotated))
    return(img_rotated)


#%% 
def data_augment(img, masks=None, 
                 max_rotate=30,
                 max_shear=5, 
                 max_scale = [0.8, 1.2],
                 max_crop=[0.2, 0.2],
                 flip_probs=[0.5, 0.5]):

    img_, masks_ = rotate_img(img, masks, max_rotate=max_rotate)
    img_, masks_ = shear_img(img_, masks_, max_shear=max_shear)
    img_, masks_ = rescale_img(img_, masks_, max_scale)
    img_, masks_ = flip_img(img_, masks_, flip_probs=flip_probs)
    img_, masks_ = crop_img(img_, masks_, max_crop=max_crop)
    return(img_, masks_)