comparison data_generation/transformations/slant.py @ 167:1f5937e9e530

More moves - transformations into data_generation, added "deep" folder
author Dumitru Erhan <dumitru.erhan@gmail.com>
date Fri, 26 Feb 2010 14:15:38 -0500
parents transformations/slant.py@0f1337994716
children
comparison
equal deleted inserted replaced
166:17ae5a1a4dd1 167:1f5937e9e530
1 #!/usr/bin/python
2 # coding: utf-8
3
4 '''
5 Author: Youssouf
6
7 this module add a slant effect to the image.
8
9 To obtain the slant effect, each row of the array is shifted proportionately by a step controlled by the complexity.
10
11 '''
12
13 import numpy
14
15
16 class Slant():
17 def __init__(self, complexity=1):
18 #---------- private attributes
19 self.direction = 1
20 self.angle = 0
21
22 #---------- generation parameters
23 self.regenerate_parameters(complexity)
24 #------------------------------------------------
25
26 def _get_current_parameters(self):
27 return [self.angle, self.direction]
28
29 def get_settings_names(self):
30 return ['angle', 'direction']
31
32 def regenerate_parameters(self, complexity):
33 self.angle = numpy.random.uniform(0.0, complexity)
34 P = numpy.random.uniform()
35 self.direction = 1;
36 if P < 0.5:
37 self.direction = -1;
38 return self._get_current_parameters()
39
40
41 def transform_image(self,image):
42 if self.angle == 0:
43 return image
44
45 ysize, xsize = image.shape
46 slant = self.direction*self.angle
47
48 output = image.copy()
49
50 # shift all the rows
51 for i in range(ysize):
52 line = image[i]
53 delta = round((i*slant)) % xsize
54 line1 = line[:xsize-delta]
55 line2 = line[xsize-delta:xsize]
56
57 output[i][delta:xsize] = line1
58 output[i][0:delta] = line2
59
60
61 #correction to center the image
62 correction = (self.direction)*round(self.angle*ysize/2)
63 correction = (xsize - correction) % xsize
64
65 # center the region
66 line1 = output[0:ysize,0:xsize-correction].copy()
67 line2 = output[0:ysize,xsize-correction:xsize].copy()
68 output[0:ysize,correction:xsize] = line1
69 output[0:ysize,0:correction] = line2
70
71
72 return output
73
74
75 # Test function
76 # Load an image in local and create several samples of the effect on the
77 # original image with different parameter. All the samples are saved in a single image, the 1st image being the original.
78
79 def test_slant():
80 import scipy
81 img_name = "test_img/mnist_0.png"
82 dest_img_name = "test_img/slanted.png"
83 nb_samples = 10
84 im = Image.open(img_name)
85 im = im.convert("L")
86 image = numpy.asarray(im)
87
88 image_final = image
89 slant = Slant()
90 for i in range(nb_samples):
91 slant.regenerate_parameters(1)
92 image_slant = slant.transform_image(image)
93 image_final = scipy.hstack((image_final,image_slant))
94
95 im = Image.fromarray(image_final.astype('uint8'), "L")
96 im.save(dest_img_name)
97
98 # Test
99 if __name__ == '__main__':
100 import sys, os, fnmatch
101 import Image
102
103 test_slant()
104