forked from lisa-lab/DeepLearningTutorials
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetex_image.py
More file actions
1530 lines (1195 loc) · 49.9 KB
/
fetex_image.py
File metadata and controls
1530 lines (1195 loc) · 49.9 KB
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
#from __future__ import division
import math
from PIL import Image
from os import listdir
from os.path import isfile, join
import sys
import numpy as np
import random
from sklearn import preprocessing
import cPickle
import theano
from PIL import ImageFilter
import os
from sklearn.decomposition import PCA
from sklearn.decomposition import RandomizedPCA
from sklearn import decomposition
from numpy import linalg as LA
#import matplotlib.pyplot as plt
from scipy.spatial import distance as dist
import random
import timeit
import csv
import pandas as pd
import urllib
#from skimage import data, io, filters
import scipy as sp
from scipy.misc import imread
from scipy.signal.signaltools import correlate2d as c2d
import math
from slugify import slugify
from multiprocessing import Process, Pool, Lock, Manager,Queue
import multiprocessing
import copy_reg
import types
def _pickle_method(method):
func_name = method.im_func.__name__
obj = method.im_self
cls = method.im_class
return _unpickle_method, (func_name, obj, cls)
def _unpickle_method(func_name, obj, cls):
for cls in cls.mro():
try:
func = cls.__dict__[func_name]
except KeyError:
pass
else:
break
return func.__get__(obj, cls)
copy_reg.pickle(types.MethodType, _pickle_method, _unpickle_method)
class FetexImage(object):
verbose = None
width = 128
height = 128
model_name = 'images'
support_per_class = None
data_path = None
mode = 'RGB'
im_index = []
dataset = None
df = None
classes = []
images = []
imlist = []
items_list = {}
lock = None
"""docstring for FetexImage"""
def __init__(self,images=[],verbose = False,support_per_class = None, data_path = None,mode = None,dataset = None, classes = []):
super(FetexImage, self).__init__()
self.verbose = verbose
self.support_per_class = support_per_class
self.data_path = data_path
self.mode = mode
self.dataset = dataset
self.classes = classes
self.images = images
self.lock = Lock()
self.items_list = []
def load_images(self,im_paths,imlist,im_index):
"""Loads all the images paths into a PIL Image object. If an image is in RGBA, then it converts it into a RGB.
It return a list of PIL Image Objects"""
imlist_arr = []
j = 0
for im_path in im_paths:
im = None
try:
im = Image.open(im_path)
#im = imread(im_path)
#print im.shape
except Exception, e:
print e
if im != None:
try:
im_aux = np.array(im,dtype=theano.config.floatX)
im_converted = True
except TypeError, e:
im_converted = False
print e
if im_converted == True:
try:
if im_aux.shape[2] == 4:
background = Image.new("RGB", im.size, (255, 255, 255))
background.paste(im, mask=im.split()[3]) # 3 is the alpha channel
im = background
im_aux = np.array(background,dtype=theano.config.floatX)
except Exception, e:
print e
try:
if im_aux.shape[2] == 3:
bn_parsed = os.path.basename(im_path).split("_")
im_id = int(bn_parsed[0])
#print im_id
#Ignore potential duplicates
#if im_id not in self.im_index:
if im_id not in im_index:
im_aux = self.scale_and_crop_img(im)
# This is for multiprocessing
im_index.append(im_id)
imlist.append(np.asarray(im_aux))
# Uncomment this if you are not using multiprocessing
# self.im_index.append(im_id)
# self.imlist.append(np.asarray(im_aux))
#self.imlist.append(im_aux)
else:
print "invalid image: {} size:{}".format(im.filename, im_aux.shape)
except Exception, e:
#raise e
print e
# if self.verbose:
# sys.stdout.write("\r Process: {0}/{1}".format(j, len(im_paths)))
# sys.stdout.flush()
j += 1
def stop_position_per_cpu(self,num_items):
#Evently distribute the workload of finding similar image amongst all the CPU's
num_cpus = multiprocessing.cpu_count()
num_iter = 0
for i in range(0,num_items):
num_iter = num_iter + (num_items - i)
iter_per_cpu = int(math.ceil(num_iter / num_cpus)) + 1
stop_push = []
num_iter_i = 0
for i in range(0,num_items):
num_iter_i = num_iter_i + (num_items - i)
if num_iter_i > iter_per_cpu:
stop_push.append(i)
num_iter_i = 0
if stop_push[-1] != num_items:
stop_push.append(num_items)
if self.verbose:
print "num_cpus: {} num_items:{} iter_per_cpu:{}".format(num_cpus,num_items,iter_per_cpu)
return stop_push
def load_images_parallel(self,im_paths):
# Load the image in parallel using as many cpus as possible
spcpu = self.stop_position_per_cpu(len(im_paths)) # get number of cpu available
start_time = timeit.default_timer()
manager = Manager()
imlist = manager.list()
im_index = manager.list()
# Start all the processes with evently distributed load
p = []
for i in xrange(0,len(spcpu)):
stop_i = spcpu[i]
start_i = 0 if i == 0 else spcpu[i-1] + 1
print "start_i:{} stop_i:{}".format(start_i,stop_i)
batch = im_paths[start_i:stop_i]
p.append(Process(target=self.load_images, args=(batch,imlist,im_index)))
p[i].start()
for i in xrange(0,len(spcpu)):
p[i].join()
imlist = list(imlist)
im_index = list(im_index)
if self.verbose:
end_time = timeit.default_timer()
elapsed_time = ((end_time - start_time))
print "Elapsed time {}s loading images".format(elapsed_time)
return imlist,im_index
def calculate_average_image(self,imlist):
"""Calculates the average image given PIL Image list"""
N=len(imlist)
if self.mode == 'RGB':
w,h,c=imlist[0].shape
arr=np.zeros((h,w,3),theano.config.floatX)
else:
w,h=imlist[0].shape
arr=np.zeros((h,w),theano.config.floatX)
for im in imlist:
imarr=np.array(im,dtype=theano.config.floatX)
try:
arr=arr+imarr/N
except Exception, e:
print e
arr=np.array(np.round(arr),dtype=np.uint8)
#arr=np.array(np.round(arr),dtype=theano.config.floatX)
#average_image=Image.fromarray(arr,mode="RGB")
average_image=Image.fromarray(arr,mode=self.mode)
return average_image
def substract_average_image(self, im, average_image):
""" Normalise an image by substracting the average image of the dataset. """
im_minus_avg = np.array(np.round(im),dtype=np.uint8) - np.array(np.round(average_image),dtype=np.uint8)
#im_minus_avg=Image.fromarray(im_minus_avg,mode="RGB")
im_minus_avg=Image.fromarray(im_minus_avg,mode=self.mode)
return im_minus_avg
def scale_and_crop_img(self,img):
""" Scale the image to width and height. If the image ratio is not 1:1, then we need the smaller side to be width/height and then crop the center of the image.
You can uncomment the commented code to transfor the images to Black and White"""
if img.size[0] < img.size[1]:
basewidth = self.width
wpercent = (basewidth/float(img.size[0]))
hsize = int(float(img.size[1])*float(wpercent))
img = img.resize((basewidth,hsize), Image.ANTIALIAS)
else:
baseheight = self.height
hpercent = (baseheight/float(img.size[1]))
wsize = int(float(img.size[0])*float(hpercent))
img = img.resize((wsize,baseheight), Image.ANTIALIAS)
if self.mode == 'L':
img = img.convert('L')
half_the_width = int(img.size[0] / 2)
half_the_height = int(img.size[1] / 2)
img = img.crop(
(
half_the_width - (self.width / 2),
half_the_height - (self.height / 2),
half_the_width + (self.width / 2),
half_the_height + (self.height / 2)
)
)
return img
def load_paths_and_labels(self,classes):
""" The classes parameter has the names of all the classes the images belong to.
Each class name is also the name of the folder where the images for that class are stored.
Therefore this function loads all the image paths and their class into lists and returns them."""
im_paths , im_labels = [], []
for image_type in classes:
mypath = self.data_path + self.dataset + '/' + image_type
onlyfiles = [ f for f in listdir(mypath) if isfile(join(mypath,f)) ]
class_support = 0
for file_name in onlyfiles:
#print file_name
if file_name != '.DS_Store':
im_path = mypath = self.data_path + self.dataset + '/' + image_type + '/' + file_name
im_paths.append(im_path)
im_labels.append(image_type)
class_support += 1
if self.support_per_class != None and class_support == self.support_per_class:
break
combined = zip(im_paths, im_labels)
random.shuffle(combined)
im_paths[:], im_labels[:] = zip(*combined)
return im_paths,im_labels
def data_augmentation_and_vectorization(self,imlist, lb,im_labels, average_image = None):
""" This function applies data augmentation to the images in order to reduce overfitting.
Potential transformations: rotation, filtering and normalisation (Norm is not data autmentation).
Then it converts the images into numpy arrays and binarizes the labels into numeric classes.
Finally we store the arrays and labels into X and Y and return them."""
X,Y,X_original = [] ,[], []
i = 0
for im in imlist:
im=Image.fromarray(im,mode=self.mode)
#try:
#im_ini = im
im_original = np.asarray(im, dtype=theano.config.floatX) / 256.
#im = self.substract_average_image(im, average_image)
#print 'i:{} is a: {}' .format(i,im_labels[i])
#im.show()
X_original.append(im_original)
#Rotations
#im_r = im.rotate(15)
# im_r_2 = im.rotate(-15)
# im_r_3 = im.rotate(180)
#im_r.show()
#im_r_2.show()
#Filters
#im_f = im_ini.filter(ImageFilter.DETAIL)
#im_f = im.filter(ImageFilter.FIND_EDGES)
if self.mode == 'RGB':
im = np.asarray(im, dtype=theano.config.floatX) / 256.
#Uncomment this if you want to use cross-correlate for 2D arrays http://docs.scipy.org/doc/scipy-0.16.0/reference/generated/scipy.signal.correlate2d.html
# im = np.asarray(im, dtype=theano.config.floatX)
# im = sp.inner(im, [299, 587, 114]) / 1000.0
# im = np.asarray(im, dtype=theano.config.floatX)
# # normalize per http://en.wikipedia.org/wiki/Cross-correlation
# im = (im - im.mean()) / im.std()
if self.mode == 'L':
# im = np.asarray(im, dtype='float64')
# im = filters.sobel(im)
#im = filters.roberts(im)
im = np.asarray(im, dtype=theano.config.floatX) / 256.
#im = np.asarray(im, dtype=theano.config.floatX)
#im = np.asarray(im, dtype=theano.config.floatX)
#im = np.asarray(im, dtype=np.uint8)
#print im.shape
#print im.shape
#im = np.asarray(im, dtype=theano.config.floatX)
#im = self.flaten_aux(im)
#print im.shape
#im = data.coins() # or any NumPy arr
#print im.shape
#image = data.coins() # or any NumPy array!
#print im
#im = filter.sobel(im)
#im = filter.roberts(im)
# im_original = sp.inner(im, [299, 587, 114]) / 1000.0
# im_original = np.asarray(im_original, dtype=theano.config.floatX)
# # normalize per http://en.wikipedia.org/wiki/Cross-correlation
# im = (im_original - im_original.mean()) / im_original.std()
#print im.shape
#print edges
# edges = np.asarray(edges, dtype=np.uint8)
#Image.fromarray(edges,mode=self.mode).show()
#print edges
#im = np.asarray(im, dtype=theano.config.floatX) / 256.
#print edges.shape
# io.imshow(im)
# io.show()
#im = np.asarray(im, dtype=theano.config.floatX)
# plt.suptitle(im_labels[i], size=16)
# plt.imshow(im, cmap=plt.cm.gray, interpolation='nearest')
# plt.show()
#im = np.asarray(im, dtype=theano.config.floatX)
#print im.shape
#self.reconstructImage(im).show()
#im_r = np.asarray(im_r, dtype=theano.config.floatX) / 256.
# im_r_2 = np.asarray(im_r_2, dtype=theano.config.floatX) / 256.
# im_r_3 = np.asarray(im_r_3, dtype=theano.config.floatX) / 256.
#im_f = np.asarray(im_f, dtype=theano.config.floatX) / 256.
#im = im.transpose(2, 0, 1)
#X.append(np.array(im, dtype=theano.config.floatX))
#X.append(np.array(im_raw, dtype=theano.config.floatX))
#X.append(im)
X.append(im)
# if i % 100 == 0:
# X.append(im)
#X.append(im_r)
# X.append(im_r_2)
# X.append(im_r_3)
#X.append(im_f)
#X_original.append(im)
# X.append(np.array(im_r, dtype=theano.config.floatX))
# X.append(np.array(im_r_2, dtype=theano.config.floatX))
#Uncomment this if you want to work with monochrome
# im = im.convert('L')
# pixels_monochrome = np.array(list(im.getdata()), dtype=np.float)
# # scale between 0-1 to speed up computations
# min_max_scaler = preprocessing.MinMaxScaler(feature_range=(0,1), copy=True)
# pixels_monochrome = min_max_scaler.fit_transform(pixels_monochrome)
# X.append(pixels_monochrome)
#Y.append(lb.transform([im_labels[i]])[0][0])
#print lb.transform([im_labels[i]])
label = lb.transform([im_labels[i]])[0][0]
#print lb.transform([im_labels[i]])
# label_vector = lb.transform([im_labels[i]])[0]
# label = np.where( label_vector == 1 )[0][0]
# print "Label: {}".format(label)
#print label
#Y.append(label)
Y.append(label)
#Y.append(im_labels[i])
#Y.append(label)
# Y.append(label)
# except Exception, e:
# print e
# #raise e
# if i == 30:
# break
i += 1
if self.verbose:
sys.stdout.write("\r Process: {0}/{1}".format(i, len(imlist)))
sys.stdout.flush()
# output = open(self.data_path + 'X_original.pkl', 'wb')
# cPickle.dump(X_original, output,protocol=-1)
# output.close()
return X,Y
def binarize_classes(self):
lb = preprocessing.LabelBinarizer()
#classes = ['n07730207-carrot','n04222210-single-bed', 'n00015388-animal','n00017222-flower','n00523513-sport','n01503061-bird','n12992868-fungus']
#classes = ['n00015388-animal','n00017222-flower','n00523513-sport','n03131574-craddle','n07730207-carrot','n02960352-car', 'n04146614-bus' , 'n09217230-beach' , 'n09238926-cave' ,'n11851578-cactus' , 'n14977504-floor' , 'n04231693-skilift','n03724870-mask']
#classes = ['n00015388-animal','n09217230-beach','n00017222-flower','n00523513-sport']
#classes = ['n00015388-animal','n09217230-beach']
#classes = ["windows-accessories","doors-and-doorways","rooflights-roof-windows","building-areas-systems","ground-substructure","floors-accessories","stairs","ceilings","wall-finishes","roof-structures-finishes","hvac-cooling-systems","insulation","lighting","furniture-fittings","external-works","building-materials","bathroom-sanitary-fittings","structural-frames-walls","drainage-water-supply","communications-transport-security","green-building-products"]
#classes = ["windows-accessories","doors-and-doorways","rooflights-roof-windows","building-areas-systems","ground-substructure","floors-accessories","stairs","ceilings","wall-finishes","roof-structures-finishes","hvac-cooling-systems","insulation"]
#classes = ["windows-accessories","doors-and-doorways","rooflights-roof-windows","building-areas-systems","ground-substructure","floors-accessories","stairs","ceilings","wall-finishes","roof-structures-finishes","hvac-cooling-systems","insulation","lighting"]
#classes = ["windows-accessories","doors-and-doorways","rooflights-roof-windows","building-areas-systems","ground-substructure","floors-accessories"]
#classes = ["windows-accessories","doors-and-doorways","rooflights-roof-windows"]
#classes = ["building-areas-systems","ground-substructure","floors-accessories"]
#class
#classes = ["stairs","ceilings","wall-finishes","roof-structures-finishes","hvac-cooling-systems","insulation"]
#classes = ["lighting","furniture-fittings","external-works","building-materials","bathroom-sanitary-fittings"]
#classes = ["structural-frames-walls","drainage-water-supply","communications-transport-security","green-building-products"]
#classes = ["windows-accessories","doors-and-doorways","rooflights-roof-windows"]
#classes = ["windows-accessories","doors-and-doorways","lighting"]
#classes = ["windows-accessories","doors-and-doorways"]
#classes = ["windows","drainage-water-supply"]
#classes = ["ceilings","stairs"]
#classes = ["drainage-water-supply"]
if self.verbose:
print "Num classes:{}".format(len(self.classes))
#lb.fit_transform(classes)
lb.fit(self.classes)
output = open(self.data_path + 'lb.pkl', 'wb')
cPickle.dump(lb, output,protocol=-1)
output.close()
return self.classes,lb
def flaten_aux(self,V):
return V.flatten(order='C')
#return V.flatten(order='F')
def create_train_validate_test_sets(self,X,Y):
""" Create Train, validation and test set"""
print "Size of the original images"
X = np.asarray(X, dtype=theano.config.floatX)
train_length = int(round(len(X) * 0.60))
valid_length = int(round(len(X) * 0.20))
test_length = int(round(len(X) * 0.20))
X_train = X[0:train_length]
X_valid = X[train_length: (train_length + valid_length)]
X_test = X[-test_length:]
# sample = X_train[0].reshape(64,64)
# X_train = X_train.transpose(0, 3, 1, 2)
# X_valid = X_valid.transpose(0, 3, 1, 2)
# X_test = X_test.transpose(0, 3, 1, 2)
# X = X.transpose(0, 3, 1, 2)
X_train = map(self.flaten_aux, X_train)
X_valid = map(self.flaten_aux, X_valid)
X_test = map(self.flaten_aux, X_test)
# X = map(self.flaten_aux, X)
#print X_train.shape
#X = X.transpose(0, 3, 1, 2)
# X = np.asarray(X, dtype=theano.config.floatX)
# X = X.reshape((21, 3, 64, 64))
# print X.shape
# #X_train = X_train.transpose(0, 3, 1, 2)
# #print X[0].
# im = Image.fromarray(X[0],mode="RGB")
# im.show()
#self.reconstructImage(X[0]).show()
# sample = X_train[0].reshape(64,64)
# Image.fromarray(sample,mode="L").show()
#X = map(self.flaten_aux, X)
# X_train = X[0:train_length]
# X_valid = X[train_length: (train_length + valid_length)]
# X_test = X[-test_length:]
Y_train = Y[0:train_length]
Y_valid = Y[train_length:(train_length + valid_length)]
Y_test = Y[-test_length:]
#pkl_file = open( '../data/lb.pkl', 'rb')
#lb = cPickle.load(pkl_file)
#arr = np.array(np.round((X_train[0] * 256).reshape((64,64))),dtype=np.uint8)
# Image.fromarray(arr,mode="L").show()
# print lb.classes_
# print Y_train[0]
train_set = [X_train,Y_train]
valid_set = [X_valid,Y_valid]
test_set = [X_test,Y_test]
input = [X,Y]
if self.verbose:
print "X_train {} X_validation {} X_test {}".format(len(X_train),len(X_valid),len(X_test))
print "Y_train {} Y_validation {} Y_test {}".format(len(Y_train),len(Y_valid),len(Y_test))
output = open(self.data_path + 'train_set.pkl', 'wb')
cPickle.dump(train_set, output,protocol=-1)
output.close()
output = open(self.data_path + 'valid_set.pkl', 'wb')
cPickle.dump(valid_set, output,protocol=-1)
output.close()
output = open(self.data_path + 'test_set.pkl', 'wb')
cPickle.dump(test_set, output,protocol=-1)
output.close()
return train_set,valid_set,test_set
def reconstructImage(self,arr):
""" Reconstruct an image from array """
arr = arr * 256
arr = np.array(np.round(arr),dtype=np.uint8)
#arr = np.array(arr,dtype=np.uint8)
# We need to transpose the array because we flatten X by columns
#arr = arr.T
#a = arr.reshape((self.width, self.height,3))
if self.mode == 'L':
a = arr.reshape((self.width, self.height))
else:
a = arr.reshape((self.width, self.height,3))
#a = arr.reshape((3,self.width, self.height))
#a = arr.transpose(0, 3, 1, 2)
im = Image.fromarray(a,mode=self.mode)
return im
def ImagePipeline(self,cnn_pipe = False, batch_index = None):
""" This is the main pipeline to process the images"""
if self.verbose:
print "...createFolderStructure"
self.createFolderStructure()
if self.verbose:
print "...downloadImages"
self.downloadImages()
if self.verbose:
print "...binarize_classes"
classes, lb = self.binarize_classes()
if self.verbose:
print "...load_paths_and_labels"
im_paths, im_labels = self.load_paths_and_labels(classes)
if self.verbose:
print "...load_images"
# Uncomment this if you just want to use one cpu
#imlist = self.load_images(im_paths,cnn_pipe)
#self.load_images(im_paths,[],[])
#imlist = self.imlist
imlist, self.im_index = self.load_images_parallel(im_paths)
#print len(imlist)
# Sort the list by index so we don't have to do as many iteration in finding similar
#if not cnn_pipe:
zipped = zip(self.im_index, imlist)
zipped_sorted = sorted(zipped, key=lambda x: x[0])
self.im_index , imlist = zip(*zipped_sorted)
average_image = None
if cnn_pipe:
if self.verbose:
print "...calculate_average_image"
average_image = self.calculate_average_image(imlist)
if self.verbose:
print "\n...data_augmentation_and_vectorization\n"
#print imlist
X,Y = self.data_augmentation_and_vectorization(imlist,lb,im_labels,average_image)
output = open( self.data_path + 'im_index.pkl', 'wb')
cPickle.dump(self.im_index, output,protocol=-1)
output.close()
if self.verbose:
print "...dimReductionSdA"
X = self.dimReductionSdA(X)
# print X[0][0:3]
# print X[1][0:3]
#X = self.dimReduction(X)
output = open( self.data_path + 'X_compressed_'+str(batch_index)+'.pkl', 'wb')
cPickle.dump(X, output,protocol=-1)
output.close()
output = open( self.data_path + 'im_index_' + str(batch_index) + '.pkl', 'wb')
cPickle.dump(self.im_index, output,protocol=-1)
output.close()
if cnn_pipe:
if self.verbose:
print "\n...create_train_validate_test_sets\n"
train_set,valid_set,test_set = self.create_train_validate_test_sets(X, Y)
return train_set,valid_set,test_set
else:
if self.verbose:
print "\n...similarImages\n"
df, duplicated_images = self.similarImages(X)
return df,duplicated_images
def removeDuplicates(self,seq):
seen = set()
seen_add = seen.add
return [ x for x in seq if not (x in seen or seen_add(x))]
def createFolderStructure(self):
""" query to get the number of images per category
SELECT categories.id,categories.slug, categories.order
FROM categories
WHERE categories.order = 10
SELECT COUNT(*) as total, products.type, categories.`name`
FROM documents
JOIN products ON documents.`product_id` = products.id
JOIN `categories` ON categories.id = products.`category_id`
WHERE documents.type = 'photo'
AND products.`category_id` IS NOT NULL
GROUP BY products.`category_id`
ORDER BY total DESC"""
with open(self.data_path + 'categories.csv', 'rb') as csvfile:
reader = csv.reader(csvfile, delimiter=',', quotechar='"')
next(reader, None) # skip the headers
for row in reader:
directory = self.data_path + 'categories/' + str(row[1])
if not os.path.exists(directory):
os.makedirs(directory)
def downloadImages(self):
""" query to get all the images and slug
SELECT documents.`id`, documents.`name`, documents.`url`, categories.`slug`
FROM documents
JOIN products ON documents.`product_id` = products.id
JOIN `categories` ON categories.id = products.`category_id`
WHERE documents.type = 'photo'
AND products.`category_id` IS NOT NULL
"""
i = 0
for im in self.images:
# Let's get the file extension and file name and make the final file path.
# We need to do this to slugify the file name and avoid errors when loading images
file_name, file_extension = os.path.splitext(im['url'])
file_name = file_name.split("/")[-1]
file_path = self.data_path + self.dataset + "/" + im['slug'] + '/' + str(im['id']) + '_' + slugify(file_name) + file_extension
# If file is not in the file path, then download from the url
if not os.path.exists(file_path):
try:
urllib.urlretrieve(im['url'], file_path )
print "i:{} url:{}".format(i,im['url'])
except Exception, e:
print e
i += 1
def readImagesCSV(self):
images = []
with open(self.data_path + '/images.csv', 'rb') as csvfile:
reader = csv.reader(csvfile, delimiter=',', quotechar='"')
next(reader, None) # skip the headers
i = 0
for row in reader:
filename, file_extension = os.path.splitext(row[2])
file_name = filename.split("/")[-1]
file_path = self.data_path + self.dataset + "/" + row[3] + '/' + row[0] + '_' + slugify(file_name) + file_extension
#print row[3]
aux = {}
aux['url'] = row[2]
aux['file_path'] = file_path
images.append(aux)
return images
def downloadImagesCSV(self,images):
i = 0
for im in images:
# If file is not in the file path, then download from the url
if not os.path.exists(im['file_path']):
try:
#print "i:{} url:{}".format(i,im['url'])
urllib.urlretrieve(im['url'], im['file_path'] )
except Exception, e:
print e
i += 1
def cosine_distance(self,a, b):
dot_product = np.dot(a,b.T)
cosine_distance = dot_product / (LA.norm(a) * LA.norm(b))
return cosine_distance
def load_SdA_weights(self,num_SdA_layer):
SdA_layers_W = []
SdA_layers_b = []
for i in range(0,num_SdA_layer):
pkl_file = open(self.data_path + 'dA_layer'+str(i)+'_W.pkl', 'rb')
W_aux = cPickle.load(pkl_file)
W_aux = np.asarray(W_aux, dtype=theano.config.floatX)
SdA_layers_W.append(W_aux)
pkl_file = open(self.data_path + 'dA_layer'+str(i)+'_b.pkl', 'rb')
b_aux = cPickle.load(pkl_file)
b_aux = np.asarray(b_aux, dtype=theano.config.floatX)
SdA_layers_b.append(b_aux)
return SdA_layers_W, SdA_layers_b
def dimReductionSdA(self,X):
import theano
import theano.tensor as T
from scipy.special import expit
if self.verbose:
print "... flattening "
X = map(self.flaten_aux, X)
X = np.asarray(X, dtype=theano.config.floatX)
# Get activations unit for layer 0
#expit = sigmoid
SdA_layers_W, SdA_layers_b = self.load_SdA_weights(2)
W_0 = SdA_layers_W[0]
b_0 = SdA_layers_b[0]
print "X shape: {} W_0 shape:{} b_0 shape:{}".format(X.shape,W_0.shape,b_0.shape)
da1output = expit(np.dot(X,W_0) + b_0)
W_1 = SdA_layers_W[1]
b_1 = SdA_layers_b[1]
print "da1output shape: {} W_0 shape:{} b_0 shape:{}".format(da1output.shape,W_1.shape,b_1.shape)
da2output = expit(np.dot(da1output,W_1) + b_1)
#print da2output[0][0:10]
return da2output
"""
from SdA_v2 import SdA
#uncomment this to check duplicates
# seen = set()
# uniq = []
# for x in self.im_index:
# if x not in seen:
# uniq.append(x)
# seen.add(x)
# else:
# print "Repeated image_id: {}".format(x)
# print self.im_index
# print uniq
numpy_rng = np.random.RandomState(89677)
sda2 = SdA(
numpy_rng=numpy_rng,
n_ins=128 * 128 * 3,
hidden_layers_sizes=[1000, 1000],
n_outs=21,
data_path=self.data_path
)
#print X.get_value(borrow = True).shape
#sda2.load_weights()
W_0 = sda2.dA_layers[0].W.get_value(borrow=True)
b_0 = sda2.dA_layers[0].b.get_value(borrow=True)
W_0 = np.asarray(W_0, dtype=theano.config.floatX)
b_0 = np.asarray(b_0, dtype=theano.config.floatX)
print "X shape: {} W_0 shape:{} b_0 shape:{}".format(X.shape,W_0.shape,b_0.shape)
#print expit(np.dot(X,W_0) + b_0 )
da1output = expit(np.dot(X,W_0) + b_0)
#print da1output
W_1 = sda2.dA_layers[1].W.get_value(borrow=True)
b_1 = sda2.dA_layers[1].b.get_value(borrow=True)
W_1 = np.asarray(W_1, dtype=theano.config.floatX)
b_1 = np.asarray(b_1, dtype=theano.config.floatX)
print "da1output shape: {} W_0 shape:{} b_0 shape:{}".format(da1output.shape,W_1.shape,b_1.shape)
# print da1output.shape
# print W_1.shape
# print b_1.shape
#print expit(np.dot(X,W_0) + b_0 )
da2output = expit(np.dot(da1output,W_1) + b_1)
#print expit(np.dot(X,W_0 + b_0))
return da2output
#print da2output[0][0:10]"""
#print da2output
# X = da2output
# print X
# return X
#return T.nnet.sigmoid(T.dot(input, self.W) + self.b)
"""
X = theano.shared(np.asarray(X,
dtype=theano.config.floatX),
borrow=True)
x = T.matrix('x')
index_1 = T.lscalar() # index to a [mini]batch
index_2 = T.lscalar() # index to a [mini]batch
getHV = sda2.dA_layers[0].get_hidden_values(x)
getHiddenValues = theano.function(
[index_1,index_2],
getHV,
givens={
x: X[index_1:index_2]
}
)
#print X.get_value()[0].shape
#print getHiddenValues(0,len(X.get_value(borrow=True)))
da1output = T.matrix('da1output')
getHV2 = sda2.dA_layers[1].get_hidden_values(da1output)
getHiddenValues2 = theano.function(
[da1output],
getHV2
)
#print getHiddenValues2(getHiddenValues(0,1)).shape
X = getHiddenValues2(getHiddenValues(0,len(X.get_value(borrow=True))))
print X[0][0:10]
return X"""
def dimReduction(self,X):
seen = set()
uniq = []
for x in self.im_index:
if x not in seen:
uniq.append(x)
seen.add(x)
else:
print "Repeated image_id: {}".format(x)
print len(self.im_index)
print len(uniq)
if self.verbose:
print "... flattening "
X = map(self.flaten_aux, X)
# print len(self.im_index)
# print len(set(self.im_index))
#X = X.transpose(0, 3, 1, 2)
# print X[0].shape
# TODO: Do PCA in batches as we don't have lots of memory. Batch_size = 5000
if self.verbose:
print "... training PCA"
# batch_size = 2000
# num_batches = int(len(X) / batch_size) + 1
# if self.verbose:
# print "... training PCA in batches of size:{} num_batches: {}".format(batch_size,num_batches)
# X_aux = []
# #X_aux = np.asarray(X_aux)
# for i in xrange(0,num_batches):
# X_batch = X[ i * batch_size : (i+1) * batch_size]
# start_time = timeit.default_timer()
# #pca = PCA(n_components=0.95)
# pca = RandomizedPCA(n_components=676)
# pca.fit(X_batch)
# end_time = timeit.default_timer()
# elapsed_time = ((end_time - start_time) / 60.)
# print "Elapsed time pca {}m".format(elapsed_time)
# print "Total variance kept = {}".format(sum(pca.explained_variance_ratio_))
# print "... pca.transform"
# #X = pca.transform(X)
# if len(X_aux) == 0:
# X_aux = pca.transform(X_batch)
# else:
# X_aux = np.concatenate((X_aux, pca.transform(X_batch)),axis=0)
# # X_aux.append(pca.transform(X_batch))
# # print X_aux[0].shape
# X = X_aux
# # X = np.asarray(X)
start_time = timeit.default_timer()
#pca = RandomizedPCA(n_components=676)
pca = RandomizedPCA(n_components=676)
pca.fit(X)
X = pca.transform(X)
end_time = timeit.default_timer()
elapsed_time = ((end_time - start_time) / 60.)
print X.shape
print X[0].shape
print "... pca fit_transform time:{}m".format(elapsed_time)
print "Total variance kept = {}".format(sum(pca.explained_variance_ratio_))
# print X[0][0]
# output = open( self.data_path + 'pca_' + self.mode + '.pkl', 'wb')
# cPickle.dump(pca, output,protocol=-1)
# output.close()
# pkl_file = open( self.data_path + 'pca.pkl', 'rb')