-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrbepwt.py
2300 lines (2095 loc) · 94.2 KB
/
rbepwt.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
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
# Copyright 2017 Renato Budinich
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import ipdb
import copy
import PIL
import skimage.io
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import scipy
import scipy.io
import pywt
import pickle
import queue
import skimage.filters
from skimage.segmentation import felzenszwalb
from skimage.measure import compare_ssim
import sklearn.cluster as skluster
import skimage.restoration
_DEBUG = False
def myround(x):
return(np.floor(x+0.5))
def add_noise(img,sigma,loc=0):
ret = np.zeros_like(img)
for idx,val in np.ndenumerate(img):
newval = min(255,val + np.abs(np.random.normal(loc,sigma)))
ret[idx] = newval
return(ret)
def rescale(img,factor):
ret = np.zeros_like(img)
for idx,val in np.ndenumerate(img):
newval = min(255,factor*val)
ret[idx] = newval
return(ret)
def is_array_in_list(array,l):
for x in l:
if np.array_equal(x,array):
return(True)
return(False)
def entropy(string):
"""Computes entropy of string"""
probabilities = [float(string.count(s))/len(string) for s in set(string)]
H = - sum([p*np.log2(p) for p in probabilities])
return(H)
def compare_wavelet_dicts(wd1,wd2):
"""Compares wavelet dictionaries in the format given by the rbepwt.wavelet_coefs_dict() method"""
for level, coefs1 in wd1.items():
coefs2 = wd2[level]
for i in range(len(coefs1)):
v1 = wd1[level][i]
v2 = wd2[level][i]
if v1 != v2:
print("level: %2d\tindex: %4d\tvalue1: %5f\tvalue2: %5f" %(level,i,v1,v2))
def rotate(vector,theta):
"""Rotates a 2D vector counterclockwise by theta"""
matrix = np.array([[np.cos(theta), -np.sin(theta)],[np.sin(theta), np.cos(theta)]])
return(np.dot(matrix,vector))
def neighborhood(coord,level,mode='square',hole=False):
"""Returns N_ij^level = {(k,l) s.t. max{|k-i|, |l-j| <= 2^(level-1)} } where (i,j) == coord"""
ret = []
i,j = tuple(coord)
if mode == 'square':
row_range = list(range(-2**(level-1),2**(level-1)+1))
col_range = list(range(-2**(level-1),2**(level-1)+1))
ret = [(i+roff,j+coff) for roff in row_range for coff in col_range]
elif mode == 'cross':
for row_offset in range(-2**(level-1),2**(level-1)+1):
k = i+row_offset
ret.append((k,j))
for col_offset in range(-2**(level-1),2**(level-1)+1):
l = j+col_offset
ret.append((i,l))
else:
raise Exception("Mode must be either square or cross")
if hole:
ret.remove(tuple(coord))
return(ret)
def full_decode(wavelet_details_dict,wavelet_approx,label_img,wavelet,path_type='easypath'):
"""Returns the decoded image, without using information obtained from encoding (i.e. all paths are recomputed)"""
print("\n--FULL DECODE--")
levels = len(wavelet_details_dict)
li_inst = Image()
li_inst.read_array(label_img)
rb_inst = Rbepwt(li_inst,levels,wavelet,path_type=path_type)
segm_inst = Segmentation(li_inst)
segm_inst.label_img = label_img
segm_inst.compute_label_dict()
rb_inst.img.segmentation = segm_inst
rb_inst.img.has_segmentation = True
rb_inst.encode(onlypaths=True)
for lev, wdetail in wavelet_details_dict.items():
rb_inst.wavelet_details[lev] = wdetail
rb_inst.region_collection_at_level[levels+1].values = wavelet_approx
decoded_region_collection = rb_inst.decode()
decoded_img = np.zeros_like(label_img,dtype='float')
for coord,value in decoded_region_collection.points.items():
decoded_img[coord] = value
#decoded_img = np.rint(decoded_img).astype('uint8')
decoded_img[decoded_img > 255] = 255
decoded_img[decoded_img < 0] = 0
return(decoded_img)
def ispowerof2(n):
if n < 1:
return(False)
k = int(n)
while k == int(k):
k /= 2
if k != 0.5:
return(False)
else:
return(True)
def gaussian_kernel(sigma,normalize=True):
g = lambda x,y: 1/(2*np.pi*sigma**2)*np.exp(-(x**2 + y**2)/(2*sigma**2))
halfsize = int(4*sigma + 0.5) #like is done in scipy.ndimage.gaussian_filter1d
size = 2*halfsize + 1
ret = np.zeros((size,size))
for coord,value in np.ndenumerate(ret):
i,j = coord
x,y= j-halfsize,i-halfsize
ret[coord] = g(x,y)
if normalize:
ret /= ret.sum()
return(ret)
def psnr(img1,img2):
mse = np.sum((img1 - img2)**2)
if mse == 0:
return(-1)
mse /= img1.size
mse = np.sqrt(mse)
return(20*np.log10(255/mse))
def ssim(img1,img2):
img1 = img1.astype('float64')
img2 = img2.astype('float64')
return(compare_ssim(img1,img2,dynamic_range=256))
def VSI(img1,img2):
"""Computes VSI of img1 vs. img2. Requires file VSI.m to be present in working directory"""
from oct2py import octave
fakergb1 = np.stack([img1,img1,img1],2).astype('float64')
fakergb2 = np.stack([img2,img2,img2],2).astype('float64')
fakergb1 /= 255
fakergb2 /= 255
octave.eval('pkg load image')
vsi = octave.VSI(fakergb1,fakergb2)
return(vsi)
def HaarPSI(img1,img2):
"""Computes HaarPSI of img1 vs. img2. Requires file HaarPSI.m to be present in working directory"""
from oct2py import octave
img1 = img1.astype('float64')
img2 = img2.astype('float64')
octave.eval('pkg load image')
haarpsi = octave.HaarPSI(img1,img2)
return(haarpsi)
class Image:
def __init__(self):
self.has_segmentation = False
self.has_decoded_img = False
self.method = None
self.segmentation_method = None
def __getitem__(self, idx):
return(self.img[idx])
def read(self,filepath):
self.img = skimage.io.imread(filepath,as_grey=True)
self.size = self.img.size
self.imgpath = filepath
self.shape = self.img.shape
self.pict = Picture()
self.pict.load_array(self.img)
def read_array(self,array):
self.img = array
self.size = self.img.size
self.shape = self.img.shape
self.pict = Picture()
self.pict.load_array(self.img)
def info(self):
img = PIL.Image.open(self.imgpath)
print(img.info, "\nshape: %s\ntot pixels: %d\nmode: %s" % (img.size,img.size[0]*img.size[1],img.mode))
img.close()
def segment(self,method='felzenszwalb',**args):
self.segmentation = Segmentation(self.img)
self.segmentation_method = method
if method == 'felzenszwalb':
if 'scale' in args.keys():
scale = args['scale']
else:
scale = 200
if 'sigma' in args.keys():
sigma = args['sigma']
else:
sigma = 2
if 'min_size' in args.keys():
min_size = args['min_size']
else:
min_size = 10
self.label_img, self.label_pict = self.segmentation.felzenszwalb(scale,sigma,min_size)
self.felz_scale,self.felz_sigma,self.felz_min_size = scale,sigma, min_size
elif method == 'thresholded':
threshold = args['threshold']
sigma = args['sigma']
self.label_img, self.label_pict = self.segmentation.thresholded(threshold,sigma)
elif method == 'kmeans':
nclusters = args['nclusters']
self.label_img, self.label_pict = self.segmentation.kmeans(nclusters)
self.has_segmentation = True
def load_mat_segmentation(self,filepath,offset=-1,matlabvar='labels',segm_method='tbes'):
"""Loads segmentation from .mat file"""
self.segmentation = Segmentation(self.img)
self.segmentation_method = segm_method
self.label_img = (scipy.io.loadmat(filepath)[matlabvar] + offset).astype('int')
self.segmentation.label_img = self.label_img
self.segmentation.nlabels = int(self.label_img.max()) + 1
self.segmentation.compute_label_dict()
self.label_pict = Picture()
self.label_pict.load_array(self.label_img)
self.has_segmentation = True
def mask_region(self,regions,fillvalue=0,decoded=False,show=True,filepath=None):
ret = fillvalue*np.ones_like(self.img)
if decoded:
img = self.decoded_pict.array
else:
img = self.img
for idx,value in np.ndenumerate(self.img):
if self.label_img[idx] in regions:
ret[idx] = value
p = Picture()
p.load_array(ret)
if show:
if filepath is not None:
p.show(filepath=filepath)
else:
p.show()
else:
return(ret)
def enclosing_mask_region(self,label,decoded = False, show=False):
region = self.rbepwt.region_collection_at_level[1][label]
width = region.bottom_right[1] - region.top_left[1] + 1
height = region.bottom_right[0] - region.top_left[0] + 1
ret = -100*np.ones(shape=(height,width))
if decoded:
img = self.decoded_pict.array
else:
img = self.img
for idx,value in np.ndenumerate(img):
if self.label_img[idx] == label:
newidx = (idx[0] - region.top_left[0], idx[1] - region.top_left[1])
ret[newidx] = value
if show:
p = Picture()
p.load_array(ret)
p.show()
return(ret)
def encode_rbepwt(self,levels, wavelet,path_type='easypath',euclidean_distance=True,paths_first_level=False):
self.method = 'rbepwt'
self.rbepwt_path_type = path_type
if not ispowerof2(self.img.size):
raise Exception("Image size must be a power of 2")
self.rbepwt_levels = levels
self.rbepwt = Rbepwt(self,levels,wavelet,path_type=path_type,paths_first_level=paths_first_level)
self.rbepwt.encode(euclidean_distance=euclidean_distance)
def decode_rbepwt(self):
self.decoded_region_collection = self.rbepwt.decode()
self.decoded_img = np.zeros_like(self.img,dtype='float')
for coord,value in self.decoded_region_collection.points.items():
self.decoded_img[coord] = value
#self.decoded_img = np.rint(self.decoded_img).astype('uint8')
self.decoded_img[self.decoded_img > 255] = 255
self.decoded_img[self.decoded_img < 0] = 0
self.decoded_pict = Picture()
self.decoded_pict.load_array(self.decoded_img)
self.has_decoded_img = True
def encode_dwt(self,levels,wavelet):
self.method = 'dwt'
if not ispowerof2(self.img.size):
raise Exception("Image size must be a power of 2")
self.dwt = Dwt(self,levels,wavelet)
self.dwt_levels = levels
self.dwt.encode()
def decode_dwt(self):
self.decoded_img = self.dwt.decode()
self.decoded_img[self.decoded_img > 255] = 255
self.decoded_img[self.decoded_img < 0] = 0
self.decoded_pict = Picture()
self.decoded_pict.load_array(self.decoded_img)
self.has_decoded_img = True
def encode_epwt(self,levels, wavelet):
self.method = 'epwt'
self.encode_rbepwt(levels,wavelet,'epwt-easypath')
def decode_epwt(self):
self.decode_rbepwt()
def filter(self,sigma):
self.filtered_img = np.zeros_like(self.img)
for idx,region in self.rbepwt.region_collection_at_level[1]:
base_points = []
values = []
for coord,value in region:
base_points.append(coord)
values.append(self.decoded_img[coord])
tmpregion = Region(base_points,values)
#partial_img = skimage.filters.gaussian(tmpregion.get_enclosing_img(0),sigma)
tmpregion.filter(sigma)
#tmpregion.denoise()
for coord,value in tmpregion:
self.filtered_img[coord] = value
self.filtered_pict = Picture()
self.filtered_pict.load_array(self.filtered_img)
#return(self.filtered_img)
def psnr(self,filtered=False):
"""Returns PSNR (peak signal to noise ratio) of decoded image vs. original image"""
if filtered:
img = self.filtered_img
else:
img = self.decoded_img
return(psnr(self.img,img))
def ssim(self,filtered=False):
"""Retursn SSIM (Structural Similarity Index) of decoded image vs. original image"""
if filtered:
img = self.filtered_img
else:
img = self.decoded_img
return(ssim(self.img,img))
def vsi(self,filtered=False):
"""Returns VSI (Visual Saliency based Index) of decoded image vs. original image"""
if filtered:
img = self.filtered_img
else:
img = self.decoded_img
return(VSI(self.img,img))
def haarpsi(self,filtered=False):
"""Returns HaarPSI (Haar Perceptual Similarity Index) of decoded image vs. original image"""
if filtered:
img = self.filtered_img
else:
img = self.decoded_img
return(HaarPSI(self.img,img))
def quality_cost_index(self,bits,filtered=False):
if filtered:
img = self.filtered_img
else:
img = self.decoded_img
K = self.size*bits
return(K*HaarPSI(self.img,img)/self.encoding_cost(bits))
def sparse_coding_cost(self,bits):
n = self.size
N = self.nonzero_coefs()
HH = -(N/n)*np.log2(N/n) - ((n-N)/n)*np.log2((n-N)/n)
return(n*HH + N*bits)
def encoding_cost(self,bits):
totbits = self.sparse_coding_cost(bits)
if self.method in ['rbepwt']:
totbits += self.segmentation.compute_encoding_length()
return(totbits)
def error(self):
print("PSNR: %f\nSSIM: %f\nVSI: %f\nHAARPSI: %f\n" %\
(self.psnr(),self.ssim(),self.vsi(),self.haarpsi()))
def nonzero_coefs(self):
if self.method in ['rbepwt','epwt']:
return(self.nonzero_rbepwt_coefs())
else:
return(self.nonzero_dwt_coefs())
def nonzero_rbepwt_coefs(self):
ncoefs = 0
for level,arr in self.rbepwt.wavelet_details.items():
ncoefs += arr.nonzero()[0].size
ncoefs += self.rbepwt.region_collection_at_level[self.rbepwt_levels+1].values.nonzero()[0].size
return(ncoefs)
def nonzero_dwt_coefs(self):
ncoefs = self.dwt.wavelet_coefs[0].nonzero()[0].size
for tupl_coef in self.dwt.wavelet_coefs[1:]:
for coef in tupl_coef:
ncoefs += coef.nonzero()[0].size
return(ncoefs)
def threshold_coefs(self,ncoefs):
if self.method in ['epwt','rbepwt']:
self.rbepwt.threshold_coefs(ncoefs)
elif self.method == 'dwt':
self.dwt.threshold_coefs(ncoefs)
def save_pickle(self,filepath):
f = open(filepath,'wb')
pickle.dump(self.__dict__,f,3)
f.close()
def load_pickle(self,filepath):
f = open(filepath,'rb')
tmpdict = pickle.load(f)
f.close()
self.__dict__.update(tmpdict)
self.has_segmentation = True
self.has_decoded_img = True
if hasattr(self,'rbepwt'):
self.rbepwt.img = self
elif hasattr(self,'epwt'):
self.rbepwt.img = self
elif hasattr(self,'dwt'):
self.dwt.img = self
try:
self.label_img
except AttributeError:
self.has_segmentation = False
try:
self.decoded_img
except AttributeError:
self.has_decoded_img = False
def load_or_compute(self,imgpath,pickledpath,levels=12,wav='bior4.4'):
try:
self.load_pickle(pickledpath)
except FileNotFoundError:
self.read(imgpath)
self.segment(scale=200,sigma=0.8,min_size=10)
self.encode_rbepwt(levels,wav)
self.save_pickle(pickledpath)
def save(self,filepath):
skimage.io.imsave(filepath,self.img)
#def show(self,title='Original image',**args):
# self.pict.show(title=title,*args)
def show(self,**other_args):
if 'title' not in other_args.keys():
other_args['title'] = 'Original Image'
self.pict.show(**other_args)
def show_decoded(self,**other_args):
if 'title' not in other_args.keys():
other_args['title'] = 'Decoded Image'
self.decoded_pict.show(**other_args)
def show_filtered(self,**other_args):
if 'title' not in other_args.keys():
other_args['title'] = 'Filtered Image'
self.filtered_pict.show(**other_args)
def save_decoded(self,filepath,**other_args):
if 'title' not in other_args.keys():
other_args['title'] = 'Decoded Image'
self.decoded_pict.show(filepath=filepath,**other_args)
def show_segmentation(self,**other_args):
#self.label_pict.show(plt.cm.hsv)
self.segmentation.show(**other_args)
def save_segmentation(self,filepath,**other_args):
if 'title' not in other_args.keys():
other_args['title'] = None
self.segmentation.save(filepath=filepath,**other_args)
def segmented_img(self):
values = {}
working_img = self.img.astype('float64')
for idx,label in np.ndenumerate(self.segmentation.label_img):
if label in values.keys():
oldv = values[label][0]
newv = oldv + working_img[idx]
if newv < oldv:
ipdb.set_trace()
values[label][0] = newv
values[label][1] += 1
else:
values[label] = [working_img[idx],1]
#print(values[0])
#print(values.keys(),values.values())
##test:
#c = 0
#for a,b in values.items():
# c += b[1]
#print(c)
for label, l in values.items():
values[label] = float(l[0]/l[1])
out = np.zeros_like(self.label_img,dtype='float64')
for idx,label in np.ndenumerate(self.label_img):
out[idx] = values[label]
return(out)
def show_segmented_img(self,title=None,regions=None,filepath=None):
fig = plt.figure()
axis = fig.gca()
colormap = plt.cm.gray
segmented = self.segmented_img()
if regions is not None:
bg = 255*np.ones_like(segmented)
for rgid,rg in self.rbepwt.region_collection_at_level[1]:
if rgid not in regions:
continue
for coord,value in rg:
bg[coord] = value
arr = bg
else:
arr = segmented
border= 0
axis.spines['top'].set_linewidth(border)
axis.spines['right'].set_linewidth(border)
axis.spines['bottom'].set_linewidth(border)
axis.spines['left'].set_linewidth(border)
#plt.style.use('classic')
axis.imshow(arr, cmap=colormap, interpolation='none')
axis.tick_params(
which='both', # both major and minor ticks are affected
bottom='off', # ticks along the bottom edge are off
top='off', # ticks along the top edge are off
left='off',
right='off',
labelleft='off',
labelbottom='off')
self.pict = Picture()
self.pict.load_mpl_fig(fig)
self.pict.show(title,filepath=filepath)
class Picture:
def __init__(self):
self.array = None
self.mpl_fig = None
def load_array(self,array):
self.array = array
def load_mpl_fig(self,mpl_fig):
self.mpl_fig = mpl_fig
def __save_or_show__(self,fig,filepath=None):
if filepath is None:
fig.show()
else:
if self.array is not None:
#img = self.array/255.0
#skimage.io.imsave(filepath,img)
fig.savefig(filepath,bbox_inches='tight',pad_inches=0.0)#,dpi='figure')
elif self.mpl_fig is not None:
fig.savefig(filepath,bbox_inches='tight',pad_inches=0.0)#,dpi='figure')
def show(self,title=None,colormap=plt.cm.gray,filepath=None,border=False):
"""Shows self.array or self.mpl"""
if self.array is not None:
fig = plt.figure()
axis = fig.gca()
if border:
axis.spines['top'].set_linewidth(2)
axis.spines['right'].set_linewidth(2)
axis.spines['bottom'].set_linewidth(2)
axis.spines['left'].set_linewidth(2)
plt.style.use('classic')
plt.imshow(self.array, cmap=colormap, interpolation='none')
plt.tick_params(
which='both', # both major and minor ticks are affected
bottom='off', # ticks along the bottom edge are off
top='off', # ticks along the top edge are off
left='off',
right='off',
labelleft='off',
labelbottom='off')
#plt.axis('off')
if title is not None:
plt.title(title)
self.__save_or_show__(fig,filepath)
elif self.mpl_fig is not None:
ax = self.mpl_fig.gca()
if title is not None:
ax.set_title(title)
self.__save_or_show__(self.mpl_fig,filepath)
class SegmentationBorderElement:
def __init__(self,p1,p2,orientation=None):
if p1[0] == p2[0]:
self.orientation = 'vertical'
if p1[1] < p2[1]:
first_point = p1
second_point = p2
else:
first_point = p2
second_point = p1
elif p1[1] == p2[1]:
self.orientation = 'horizzontal'
if p1[0] < p2[0]:
first_point = p1
second_point = p2
else:
first_point = p2
second_point = p1
else:
raise Exception("This shouldn't happen")
if orientation is not None:
self.orientation = orientation
self.points = (tuple(first_point),tuple(second_point))
def __eq__(self,other_border_element):
if self.points == other_border_element.points:
return(True)
else:
return(False)
def __hash__(self):
#return(hash((self.points,self.orientation)))
return(hash(self.points))
def compute_neighbours(self):
if self.orientation == (1,0):
i,j = self.points[0]
if self.points[1] != (i,j+1):
raise Exception("This shouldn't happen")
dleftn = SegmentationBorderElement((i,j),(i+1,j))
drightn = SegmentationBorderElement((i,j+1),(i+1,j+1))
downn = SegmentationBorderElement((i+1,j),(i+1,j+1))
self.neighbours = (dleftn,drightn,downn)
elif self.orientation == (-1,0):
i,j = self.points[0]
if self.points[1] != (i,j+1):
raise Exception("This shouldn't happen")
uleftn = SegmentationBorderElement((i-1,j),(i,j))
urightn = SegmentationBorderElement((i-1,j+1),(i,j+1))
upn = SegmentationBorderElement((i-1,j),(i-1,j+1))
self.neighbours = (uleftn,urightn,upn)
elif self.orientation == (0,1):
i,j = self.points[0]
if self.points[1] != (i+1,j):
raise Exception("This shouldn't happen")
rdownn = SegmentationBorderElement((i+1,j),(i+1,j+1))
rupn = SegmentationBorderElement((i,j),(i,j+1))
rightn = SegmentationBorderElement((i,j+1),(i+1,j+1))
self.neighbours = (rdownn,rupn,rightn)
elif self.orientation == (0,-1):
i,j = self.points[0]
if self.points[1] != (i+1,j):
raise Exception("This shouldn't happen")
ldownn = SegmentationBorderElement((i+1,j-1),(i+1,j))
lupn = SegmentationBorderElement((i,j-1),(i,j))
leftn = SegmentationBorderElement((i,j-1),(i+1,j-1))
self.neighbours = (ldownn,lupn,leftn)
return(self.neighbours)
#def sum_dir(self,direc):
# p1,p2 = self.points
# ret = SegementationBorderElement(p1
def compute_new_direc(self,prev_bel):
pi,pj = prev_bel.points[0]
prev_direc = prev_bel.orientation
pdi,pdj = prev_direc
ni,nj = self.points[0]
ni1,nj1 = self.points[1]
#prev_bel is vertical iff pdi is 1 or -1:
if pdi == 1: #prev_bel is going down
if ni == pi and nj == pj: #going right
new_direc = (0,-1)
direc_change_bit = 1
elif ni == pi + 1 and nj == pj: #going straight
new_direc = (1,0)
direc_change_bit = 0
elif ni == pi and nj == pj + 1: #going left
new_direc = (0,1)
direc_change_bit = 3
else:
raise Exception("This shouldn't happen")
elif pdi == -1: #prev_bel is going up
if ni == pi - 1 and nj == pj + 1: #going right
new_direc = (0,1)
direc_change_bit = 1
elif ni == pi - 1 and nj == pj: #going straight or left
if ni1 == pi - 1 and nj1 == pj + 1: #going straight
new_direc = (-1,0)
direc_change_bit = 0
elif ni1 == pi and nj1 == pj : #going left
new_direc = (0,-1)
direc_change_bit = 3
else:
raise Exception("This shouldn't happen")
else:
raise Exception("This shouldn't happen")
#prev_bel is horizzontal iff pdj is 1 or -1:
elif pdj == 1: #prev_bel is going right
if ni == pi + 1 and nj == pj: #going right
new_direc = (1,0)
direc_change_bit = 1
elif ni == pi and nj == pj + 1: #going straight
new_direc = (0,1)
direc_change_bit = 0
elif ni == pi and nj == pj: #going left
new_direc = (-1,0)
direc_change_bit = 3
else:
raise Exception("This shouldn't happen")
elif pdj == -1: #prev_bel is going left
if ni == pi + 1 and nj == pj - 1: #going left
new_direc = (1,0)
direc_change_bit = 3
elif ni == pi and nj == pj - 1: #going straight or right
if ni1 == pi + 1 and nj1 == pj - 1: #going straight
new_direc = (0,-1)
direc_change_bit = 0
elif ni1 == pi and nj1 == pj : #going right
new_direc = (-1,0)
direc_change_bit = 1
else:
raise Exception("This shouldn't happen")
else:
raise Exception("This shouldn't happen")
return(new_direc,direc_change_bit)
class Segmentation:
def __init__(self,image):
self.img = image
self.has_label_dict = False
self.nlabels = -1
self.borders_set_built = False
self.computed_encoding = False
def felzenszwalb(self,scale,sigma,min_size):
self.label_img = felzenszwalb(self.img, scale=float(scale), sigma=float(sigma), min_size=int(min_size))
self.compute_label_dict()
self.nlabels = int(self.label_img.max()) + 1
self.label_pict = Picture()
self.label_pict.load_array(self.label_img)
return(self.label_img,self.label_pict)
def kmeans(self,nclusters):
points = None
for coord,value in np.ndenumerate(self.img):
if points is not None:
points = np.vstack((points,np.array([coord[0],coord[1],value])))
else:
points = np.array([coord[0],coord[1],value])
km = skluster.KMeans(nclusters)
km.fit(points)
self.label_img = np.zeros_like(self.img)
for idx,label in enumerate(km.labels_):
coord = int(points[idx][0]),int(points[idx][1])
self.label_img[coord] = label
self.compute_label_dict()
self.nlabels = nclusters
self.label_pict = Picture()
self.label_pict.load_array(self.label_img)
return(self.label_img,self.label_pict)
def thresholded(self,threshold,sigma=0.8):
indexes = set(map(lambda x: x[0], np.ndenumerate(self.img)))
fimg = skimage.filters.gaussian(self.img.astype('float64'),sigma=sigma)
self.label_img = -np.ones_like(fimg)
npoints = self.label_img.size
label = 0
avaiable_points = queue.Queue()
avaiable_points.put((0,0))
self.label_img[0,0] = label
new_starting_points = queue.Queue()
counter = 1
while counter < npoints:
if avaiable_points.empty():
cand = new_starting_points.get()
while self.label_img[cand] != -1:
cand = new_starting_points.get()
avaiable_points.put(cand)
label += 1
self.label_img[cand] = label
point = avaiable_points.get()
for cand in set(neighborhood(point,1,hole=True)).intersection(indexes):
diff = np.abs(fimg[cand] - fimg[point])
if self.label_img[cand] == -1 and diff < threshold:
self.label_img[cand] = label
avaiable_points.put(cand)
else:
new_starting_points.put(cand)
counter += 1
self.nlabels = int(self.label_img.max()) + 1
self.label_pict = Picture()
self.label_pict.load_array(self.label_img)
return(self.label_img.astype('uint8'),self.label_pict)
def compute_label_dict(self):
self.label_dict = {}
for idx,label in np.ndenumerate(self.label_img):
if label not in self.label_dict:
self.label_dict[label] = Region([idx],[self.img[idx]])
else:
self.label_dict[label] += Region([idx],[self.img[idx]])
self.has_label_dict = True
return(self.label_dict)
def __build_borders_set__(self):
n,m = self.label_img.shape
visited = set()
self.borders = set()
for coord,val in np.ndenumerate(self.label_img):
neighbors = neighborhood(coord,1,'cross')
neighbors.remove(coord)
for neighbour in neighbors:
i,j = neighbour
if i < 0 or i >= n or j < 0 or j >= m:
continue
#couple = frozenset([coord,neighbour])
couple = SegmentationBorderElement(coord,neighbour)
if self.label_img[coord] != self.label_img[neighbour] and couple not in visited:
self.borders.add(couple)
if len(self.borders) == 1:
self.first_border = couple
visited.add(couple)
self.borders_set_built = True
def estimate_perimeter(self):
if not self.borders_set_built:
self.__build_borders_set__()
return(len(self.borders))
def compute_encoding(self):
if not self.borders_set_built:
self.__build_borders_set__()
def update_orientation(bel):
orientation = bel.orientation
if orientation == 'vertical':
return((1,0))
elif orientation == 'horizzontal':
return((0,1))
else:
raise Exception("This shouldn't happen")
#go through all segementation border elements like if we were exploring a tree depth first (sort of depth first...)
bif_points = queue.Queue() #bifurcation points in the segmentation border
point_counter = 1
dir_counter = 0 #counts how many direction elements we must store
visited = set()
prev = self.first_border
self.first_border.orientation = update_orientation(self.first_border)
enc_string = '[' + str(self.first_border.points) + ']'
avaiable_bels = self.borders.copy()
avaiable_bels.remove(self.first_border)
visited.add(self.first_border)
cur = self.first_border
direc_change_string = ''
while True:
#print(cur.points,bif_points.empty())
#border_type = cur.orientation
possible_neighbours = cur.compute_neighbours()
candidate_bels = set() #candidate border elements
for cbel in possible_neighbours:
#if cbel not in visited and cbel != prev and cbel in self.borders:
if cbel != prev and cbel in avaiable_bels:
candidate_bels.add(cbel)
#print(cbel.points)
if len(candidate_bels) == 0:
if bif_points.empty():
#print(cur.points,[x.points for x in avaiable_bels])
try:
new_border_el = avaiable_bels.pop()
except KeyError:
break
new_border_el.orientation = update_orientation(new_border_el)
else:
new_border_el = bif_points.get()
point_counter += 1
enc_string += '\t[' + str(new_border_el.points) + ']'
else:
new_border_el = candidate_bels.pop() #TODO: something smarter can be done to select the next border element, like choosing the one that makes for the straighter path
visited.add(new_border_el)
avaiable_bels.remove(new_border_el)
if len(candidate_bels) > 0:
bif_points.put(cur)
#direc = None
#if border_type == 'vertical':
# if new_border_el == dleftn:
# # direc =
# pass
#if new_border_el.points[0] == (54,43):
# ipdb.set_trace()
direc,direc_change_bit = new_border_el.compute_new_direc(cur)
dir_counter += 1
enc_string += str(direc_change_bit)
direc_change_string += str(direc_change_bit)
new_border_el.orientation = direc
prev = cur
cur = new_border_el
self.encoding_npoints = point_counter
self.encoding_ndirs = dir_counter
self.computed_encoding = True
self.direc_change_string = direc_change_string
return(enc_string,point_counter,dir_counter)
def compute_encoding_length(self):
if not self.computed_encoding:
self.compute_encoding()
#sizeof_int = 16
#totbits = sizeof_int*4*self.encoding_npoints + 2*self.encoding_ndirs
H = entropy(self.direc_change_string)
beta = 18 #16bits for two coordinates and 2 for the side of the pixel the border is on
totbits = self.encoding_npoints*beta + len(self.direc_change_string)*H
return(totbits)
def show(self,title=None,colorbar=True,border=False,regions=None,filepath=None):
fig = plt.figure()
axis = fig.gca()
if regions is None:
imshow = self.label_img
else:
colorbar = False
bg_value=-100
fill_value = 1
imshow = bg_value*np.ones_like(self.label_img)
for coord,v in np.ndenumerate(self.label_img):
if v in regions:
#imshow[coord] = v
imshow[coord] = fill_value
plt.imshow(imshow,interpolation='none',cmap=plt.cm.plasma)
if border:
axis.spines['top'].set_linewidth(2)
axis.spines['right'].set_linewidth(2)
axis.spines['bottom'].set_linewidth(2)
axis.spines['left'].set_linewidth(2)
plt.tick_params(
which='both', # both major and minor ticks are affected
bottom='off', # ticks along the bottom edge are off
top='off', # ticks along the top edge are off
left='off',
right='off',
labelleft='off',
labelbottom='off')
#plt.axis('off')
if colorbar:
plt.colorbar()
self.pict = Picture()
self.pict.load_mpl_fig(fig)
self.pict.show(title,filepath=filepath)
class Region:
"""Region of points, which can always be thought of as a path since points are ordered"""
def __init__(self, base_points, values=None, compute_dict = True, avg_grad=None,):
#if type(base_points) != type([]):
# raise Exception('The points to init the Path must be a list')