-
Notifications
You must be signed in to change notification settings - Fork 1
/
helper.py
86 lines (68 loc) · 2.48 KB
/
helper.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
import numpy
from PIL import Image
from scipy import misc
from generate_file import generate_images
import theano
import theano.tensor as T
#const
SizeMnist = 28
def additional_database(train_set_x,train_set_y):
"""
concat all dataset generated by normalization
"""
print '... normalizing width digits'
train_set_x_gen = [train_set_x]
train_set_y_gen = [train_set_y]
return train_set_x_gen, train_set_y_gen
def normalize_dataset(dataset_x, digit_normalized_width, end_size):
"""
normalize all digit from dataset
"""
#new_dataset = [normalize_digit(x,digit_normalized_width,end_size) for x in dataset_x]
new_dataset = []
for x in dataset_x:
new_dataset.append(normalize_digit(x,digit_normalized_width,end_size))
return new_dataset
def normalize_digit(x, digit_normalized_width, end_size):
"""
normalize digit image
"""
# build the matrix image
x = x.reshape(SizeMnist, SizeMnist)
# non-zero col-sums
width_diff = digit_normalized_width - sum(sum(x)!=0)
if width_diff:
#dimension corresponding to new width
new_dim = SizeMnist + width_diff
#generate new image to resize
new_image = misc.toimage(x)
#resize image according to the new dim + end size
normalized_image = new_image.resize((new_dim,end_size))
normalized_array = numpy.array(normalized_image.getdata(), dtype=numpy.float32)
# new x with new dimensions Ex: (26,28) to W18
x = normalized_array.reshape(end_size,new_dim) / 255
return pad_image(x, end_size)
def pad_image(x, end_size):
"""
padding to complete the image Size
corresponding to SizeMnist ** 2 (28,28)
"""
#get the length of padding
# difference between total image size
# and the new normalized image with less width
padding = end_size - x.shape[1]
#quantity for passing on left
left_side = round(padding / 2)
#quantity for passing on right
right_side = padding - left_side
#total padding
pads = (left_side,right_side)
# padding
if pads > (0.,0.,0.,0.):
aa = numpy.pad(x,((0.,0.),pads),mode='constant',constant_values=0)
else:
aa = x[0:end_size , -left_side:(x.shape[1] + right_side)]
aareshape = aa.reshape(end_size**2)
#generate images for validation
generate_images(aareshape*255,end_size,end_size,'W'+str(20 - (padding)))
return aareshape