comparison transformations/affine_transform.py @ 39:17caecc92544

affine transformation using PIL
author Razvan Pascanu <r.pascanu@gmail.com>
date Tue, 02 Feb 2010 21:17:11 -0500
parents
children 81b9567ec4ae
comparison
equal deleted inserted replaced
38:349d8dc9504c 39:17caecc92544
1 #!/usr/bin/python
2 # coding: utf-8
3
4 '''
5 Simple implementation of random affine transformations based on the Python
6 Imaging Module affine transformations.
7
8
9 Author: Razvan Pascanu
10 '''
11
12 import numpy, Image
13
14
15
16 class AffineTransformation():
17 def __init__( self, shape = (32,32), seed = None):
18 self.shape = shape
19 self.rng = numpy.random.RandomState(seed)
20
21 def transform(self,NIST_image):
22
23 im = Image.fromarray( \
24 numpy.asarray(\
25 NIST_image.reshape(self.shape), dtype='uint8'))
26 # generate random affine transformation
27 # a point (x',y') of the new image corresponds to (x,y) of the old
28 # image where :
29 # x' = params[0]*x + params[1]*y + params[2]
30 # y' = params[3]*x + params[4]*y _ params[5]
31
32 # the ranges are set manually as to look acceptable
33 params = self.rng.uniform(size = 6) -.5
34 params[2] *= 8.
35 params[5] *= 8.
36 params[0] = 1. + params[0]*0.4
37 params[3] = 0. + params[3]*0.4
38 params[1] = 0 + params[1]*0.4
39 params[4] = 1 + params[4]*0.4
40
41 print params
42 nwim = im.transform( (32,32), Image.AFFINE, params)
43 return numpy.asarray(nwim)
44
45
46
47 if __name__ =='__main__':
48 print 'random test'
49
50 from pylearn.io import filetensor as ft
51 import pylab
52
53 datapath = '/data/lisa/data/nist/by_class/'
54
55 f = open(datapath+'digits/digits_train_data.ft')
56 d = ft.read(f)
57 f.close()
58
59
60 transformer = AffineTransformation()
61 id = numpy.random.randint(30)
62
63 pylab.figure()
64 pylab.imshow(d[id].reshape((32,32)))
65 pylab.figure()
66 pylab.imshow(transformer.transform(d[id]).reshape((32,32)))
67
68 pylab.show()
69