-
Notifications
You must be signed in to change notification settings - Fork 0
/
transformation_ops.py
376 lines (284 loc) · 11.7 KB
/
transformation_ops.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
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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
'''
MIT License
Copyright (c) 2019 Riccardo Volpi
Permission is hereby granted, free of charge, to any person obtaining a copy of this
software and associated documentation files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
'''
import os
import numpy as np
import numpy.random as npr
try:
import cPickle
except:
pass
import PIL
import PIL.ImageOps
import PIL.ImageEnhance
import PIL.ImageFilter
import PIL.Image
import matplotlib
import noise_utils
class TransfOps(object):
'''
Class to handle data transformations.
'''
def __init__(self, transformation_list):
'''
Init object to deal with image transformations')
'''
self.transformation_list = transformation_list
#self.transformation_list = ['identity', 'rotate', 'brightness', 'color', 'contrast', 'RGB_rand', 'solarize']
self.define_code_correspondances()
def decode_string(self, transf_string):
'''
Code to decode the string used by the genetic algorithm
String example: 't1,l1_3,t4,l4_0,t0,l0_1'. First transformation is the one
associated with index '1', with level set to '3', and so on.
'random_N' with N integer gives N rnd transformations with rnd levels.
'''
if 'random' in transf_string:
transformations = npr.choice(self.transformation_list, int(transf_string.split('_')[-1])) # the string is 'random_N'
levels = [npr.choice(list(self.code_to_level_dict[t].values()), 1)[0] for t in transformations] # list() to make it compatible with Python3
else:
transformation_codes = transf_string.split(',')[0::2]
level_codes = transf_string.split(',')[1::2]
transformations = [self.code_to_transf(code) for code in transformation_codes]
levels = [self.code_to_level(transf,level) for transf,level in zip(transformations, level_codes)]
return transformations, levels
def transform_dataset(self, dataset, transf_string = 't0,l0_0', transformations=None, levels=None):
'''
dataset: set of images, shape should be N x width x height x #channels
transf_string: transformations and levels encoded in a string
'''
dataset = np.copy(dataset)
#print('Dataset size:{}'.format(dataset.shape))
if len(dataset.shape) == 3: # if 'dataset' is a single image
dataset = np.expand_dims(dataset, 0)
if dataset.shape[-1] != 3:
print('Input shape:', str(dataset.shape))
raise Exception('The images must be in RGB format')
tr_dataset = np.zeros((dataset.shape))
if transformations is None:
# decoding transformation string
transformations, levels = self.decode_string(transf_string)
for n,img in enumerate(dataset):
pil_img = PIL.Image.fromarray(img.astype('uint8'), 'RGB')
for transf,level in zip(transformations, levels):
pil_img = self.apply_transformation(pil_img, transf, level)
tr_dataset[n] = np.array(pil_img)
return tr_dataset, transformations, levels
def apply_transformation(self, image, transformation, level):
'''
image: image to be tranformed, shape should be 1 x width x height x #channels
transformation: type of transformation to be applied
level: level of the perturbation to be applied
'''
if transformation == 'identity':
return image
elif transformation == 'brightness':
return PIL.ImageEnhance.Brightness(image).enhance(level)
elif transformation == 'invert':
image = np.array(image).astype(int)
image = np.abs(255-image)
image = PIL.Image.fromarray(image.astype('uint8'), 'RGB')
return image
elif transformation == 'black_and_white':
image = np.array(image).astype(int)
gray_image = 0.3*image[:,:,0]+ 0.50*image[:,:,1] + 0.11*image[:,:,2]
image = np.stack((gray_image, gray_image, gray_image), axis=2)
image = PIL.Image.fromarray(image.astype('uint8'), 'RGB')
return image
elif transformation == 'color':
return PIL.ImageEnhance.Color(image).enhance(level)
elif transformation == 'contrast':
return PIL.ImageEnhance.Contrast(image).enhance(level)
elif transformation == 'rotate_upside_down':
image = image.rotate(level, resample=PIL.Image.BILINEAR)
return image
elif transformation == 'rotate':
image = image.rotate(level, resample=PIL.Image.BILINEAR)
return image
elif transformation == 'rotate_90':
image = image.rotate(90, resample=PIL.Image.BILINEAR)
return image
elif transformation == 'rotate_180':
image = image.rotate(180, resample=PIL.Image.BILINEAR)
return image
elif transformation == 'rotate_270':
image = image.rotate(270, resample=PIL.Image.BILINEAR)
return image
elif transformation == 'solarize':
return PIL.ImageOps.solarize(image, threshold=level)
elif transformation == 'RGB_rand':
image = np.array(image).astype(int)
image[:,:,0] += npr.randint(low=-level,high=level)
image[:,:,1] += npr.randint(low=-level,high=level)
image[:,:,2] += npr.randint(low=-level,high=level)
image[image>255] = 255
image[image<0] = 0
image = PIL.Image.fromarray(image.astype('uint8'), 'RGB')
return image
elif transformation == 'gaussian_noise':
image = np.array(image).astype(int)
image = noise_utils.noisy('gauss', np.expand_dims(image,0), level)
image = PIL.Image.fromarray(np.squeeze(image).astype('uint8'), 'RGB')
return image
elif transformation == 'blur':
image = image.filter(PIL.ImageFilter.BLUR)
return image
#elif transformation == 'hue':
# image = np.array(image).astype(int)
# print 'Before: ', image.min(), image.max()
# image = matplotlib.colors.rgb_to_hsv(image/255.)
# image[:,:,0] += level
# image = matplotlib.colors.hsv_to_rgb(image)
# print 'After: ', image.min(), image.max()
# return(image * 255.)
#elif transformation == 'saturation':
# image = np.array(image).astype(int)
# print 'Before: ', image.min(), image.max()
# image = matplotlib.colors.rgb_to_hsv(image/255.)
# image[:,:,1] += level
# image = matplotlib.colors.hsv_to_rgb(image)
# print 'After: ', image.min(), image.max()
# return(image * 255.)
else:
raise Exception('Unknown transformation!')
def code_to_transf(self, code):
'''
Takes in input a code (e.g., 't0', 't1', ...) and gives in output
the related transformation.
'''
return self.code_to_transf_dict[code]
def code_to_level(self, transformation, code):
'''
Takes in input a transfotmation (e.g., 'invert', 'colorize', ...) and
a level code (e.g., 'l0_1', 'l1_3', ...) and gives in output the related level.
'''
return self.code_to_level_dict[transformation][code]
def define_code_correspondances(self):
'''
Define the correpondances between transformation/level codes
and the actual types and values.
'''
self.code_to_transf_dict = dict()
self.code_to_transf_dict['t0'] = 'identity'
# color
self.code_to_transf_dict['t1'] = 'brightness'
self.code_to_transf_dict['t2'] = 'color'
self.code_to_transf_dict['t3'] = 'contrast'
self.code_to_transf_dict['t4'] = 'solarize'
self.code_to_transf_dict['t5'] = 'RGB_rand'
self.code_to_transf_dict['t6'] = 'black_and_white'
self.code_to_transf_dict['t7'] = 'invert'
# geometric
self.code_to_transf_dict['t8'] = 'rotate'
self.code_to_transf_dict['t9'] = 'rotate_90'
self.code_to_transf_dict['t10'] = 'rotate_180'
self.code_to_transf_dict['t11'] = 'rotate_270'
self.code_to_transf_dict['t12'] = 'rotate_upside_down'
# noise
self.code_to_transf_dict['t13'] = 'gaussian_noise'
self.code_to_transf_dict['t14'] = 'blur'
self.code_to_level_dict = dict()
for k in self.transformation_list:
self.code_to_level_dict[k] = dict()
RGB_factor_range = np.linspace(1,120,90)
factor_range = np.linspace(0.2,1.8,90)
degree_range = np.linspace(-60,60,90).astype(int)
solarize_factor_range = np.linspace(255,75,90)
noise_variance_range = np.linspace(0.0,30.,20)
# no levels
self.code_to_level_dict['identity'] = dict()
self.code_to_level_dict['identity'][str(0)] = None
self.code_to_level_dict['invert'] = dict()
self.code_to_level_dict['invert'][str(0)] = None
self.code_to_level_dict['rotate_90'] = dict()
self.code_to_level_dict['rotate_90'][str(0)] = None
self.code_to_level_dict['rotate_180'] = dict()
self.code_to_level_dict['rotate_180'][str(0)] = None
self.code_to_level_dict['rotate_270'] = dict()
self.code_to_level_dict['rotate_270'][str(0)] = None
self.code_to_level_dict['black_and_white'] = dict()
self.code_to_level_dict['black_and_white'][str(0)] = None
self.code_to_level_dict['blur'] = dict()
self.code_to_level_dict['blur'][str(0)] = None
# factors
self.code_to_level_dict['brightness'] = dict()
for n,l in enumerate(factor_range):
self.code_to_level_dict['brightness'][str(n)] = l
self.code_to_level_dict['contrast'] = dict()
for n,l in enumerate(factor_range):
self.code_to_level_dict['contrast'][str(n)] = l
self.code_to_level_dict['color'] = dict()
for n,l in enumerate(factor_range):
self.code_to_level_dict['color'][str(n)] = l
# degrees clockwise
self.code_to_level_dict['rotate'] = dict()
for n,l in enumerate(degree_range):
self.code_to_level_dict['rotate'][str(n)] = l
self.code_to_level_dict['rotate_upside_down'] = dict()
for n,l in enumerate(degree_range):
self.code_to_level_dict['rotate_upside_down'][str(n)] = l + 180
self.code_to_level_dict['solarize'] = dict()
for n,l in enumerate(solarize_factor_range):
self.code_to_level_dict['solarize'][str(n)] = l
# rgb factors
self.code_to_level_dict['RGB_rand'] = dict()
for n,l in enumerate(RGB_factor_range.astype(int)):
self.code_to_level_dict['RGB_rand'][str(n)] = l
# variance
self.code_to_level_dict['gaussian_noise'] = dict()
for n,l in enumerate(noise_variance_range):
self.code_to_level_dict['gaussian_noise'][str(n)] = l
if __name__=='__main__':
data_dir = '../data'
# loading 32x32 MNIST
image_dir = os.path.join(data_dir, 'mnist', 'train.pkl')
with open(image_dir, 'rb') as f:
mnist = cPickle.load(f)
print('Loaded MNIST')
images = mnist['X']
labels = mnist['y']
import scipy.io
from load_ops import LoadOps
load_ops = LoadOps(data_dir)
images, _ = load_ops.load_mnist()
images = images[:10] * 255.
import matplotlib.pyplot as plt
#plt.imshow(images[0])
#plt.show()
# grayscale to rgb
# images = np.squeeze(np.stack((images,images,images), axis=3))
# object to handle dataset transformations
tr_ops = TransfOps()
print('Created TransfOps object')
# defining a transformation string
#tr_string = 't0,l0_0' #identity function
#tr_string = 't0,l0_0,t1,l1_2'
trs=['RGB_rand']
lvls=[50]
print(images.min(), images.max())
# transforming MNIST dataset
print('Applying transformations...')
tr_images, transformations, levels = tr_ops.transform_dataset(images, transformations=trs, levels=lvls)
print('Done!')
print('Saving images')
PIL.Image.fromarray(images[0].astype('uint8')).save('img_original.png')
PIL.Image.fromarray(tr_images[0].astype('uint8')).save('img_modified.png')
# print('Saving transformations')
# ofile = open('used_transformations.txt','w')
# ofile.write('_'.join(transformations))
# ofile.write('\n')
# ofile.write('_'.join([str(l) for l in levels]))
# ofile.close()