-
Notifications
You must be signed in to change notification settings - Fork 0
/
mokas_stackimages.py
2080 lines (1905 loc) · 87.7 KB
/
mokas_stackimages.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
import os, sys, glob, time, re
import scipy
import scipy.ndimage as nd
import scipy.signal as signal
import scipy.stats.stats
import numpy as np
import numpy.ma as ma
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as cmx
from colorsys import hsv_to_rgb
from gpuSwitchtime import get_gpuSwitchTime #gpuSwitchtimeBackup
from PIL import Image
import tifffile
import getLogDistributions as gLD
import getAxyLabels as gal
import rof
import mahotas
#import h5py
import tables
import mokas_polar as polar
import mokas_collect_images as collect_images
from mokas_colors import get_cmap, getKoreanColors, getPalette
import mokas_gpu as mkGpu
from mokas_domains import Domains
import pickle
from skimage import measure
import warnings
try:
#from bokeh.models import (BasicTicker, Circle, ColumnDataSource, DataRange1d,
# Grid, LinearAxis, PanTool, Plot, WheelZoomTool,)
import bokeh.models as bkm
import bokeh.plotting as plk
from bokeh.models import Label, DataRange1d, Range1d
from bokeh.models.annotations import Title
import bokeh.palettes as palettes
from bokeh.transform import factor_cmap, linear_cmap
import colorcet as cc
is_bokeh = True
except:
is_bokeh = False
SPACE = "###"
# Check if pycuda is available
try:
import pycuda.driver as driver
isPyCuda = True
#free_mem_gpu, total_mem_gpu = driver.mem_get_info()
except:
isPyCuda = False
print("Please install PyCuda")
sys.exit()
# Load scikits modules if available
try:
from skimage.filters import tv_denoise
isTv_denoise = True
filters['tv'] = tv_denoise
except:
isTv_denoise = False
try:
import skimage.io as im_io
from skimage import filters as skfilters
from skimage import measure
isScikits = True
except:
isScikits = False
print("*********** There is no Scikits-image installed")
sys.exit()
plugins = im_io.available_plugins
keys = plugins.keys()
mySeq = ['gtk', 'pil', 'matplotlib', 'qt']
for plugin in mySeq:
if plugin in keys:
use = plugin
try:
im_io.use_plugin('pil', 'imread')
except:
print("No plugin available between %s" % str(mySeq))
# Adjust the interpolation scheme to show the images
mpl.rcParams['image.interpolation'] = 'nearest'
def natural_key(string_):
"""See http://www.codinghorror.com/blog/archives/001018.html"""
return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string_)]
# ###################################################################
class StackImages:
"""
Load and analyze a sequence of images
as a multi-dimensional scipy 3D array.
The k-th element of the array (i.e. myArray[k])
is the k-th image of the sequence.
Parameters:
----------------
mainDir : string
Directory of the image files
pattern : string
Pattern of the input image files,
as for instance "Data1-*.tif"
firstImage, lastIm : int, opt
first and last image (included) to be loaded
These numbers refer to the numbers of the filenames
subDirs : list
list of subdirectories to save the data into (hdf5 style)
resize_factor : int, opt
Reducing factor for the size of raw images
filtering : string, opt
Apply a filter to the raw images between the following:
'gauss': nd.gaussian_filter (Default)
'fouriergauss': nd.fourier_gaussian,
'median': nd.median_filter,
'tv': tv_denoise,
'wiener': signal.wiener
sigma : scalar or sequence of scalars, required with filtering
for 'gauss': standard deviation for Gaussian kernel.
for 'fouriergauss': The sigma of the Gaussian kernel.
for 'median': the size of the filter
for 'tv': denoising weight
for 'wiener': A scalar or an N-length list as size of the Wiener filter
window in each dimension.
imCrop : 4-element tuple
Crop the image
hdf5_signature : dict
A dictionary containing the essential data to identify a measurement
if None, the code does not save data on a hdf5
visualization_library : str
'mpl': matplotlib (default)
'bokeh' : Bokeh (https://docs.bokeh.org/en/latest/index.html)
"""
def __init__(self, subDirs, pattern, resize_factor=None,
firstIm=None, lastIm=None,
filtering=None, sigma=None,
kernel_half_width_of_ones = 10,
kernel_sign = None,
#kernel_switch_position = 'center',
boundary=None, imCrop=False,
initial_domain_region=None, subtract=None,
exclude_switches_from_central_domain=True,
exclude_switches_out_of_final_domain=False,
erase_small_events_percent = None,
rotation=None, fillValue=-1,
hdf5_use=False,
hdf5_signature=None,
visualization_library = 'mpl'):
"""
Initialized the class
"""
# Initialize variables
self._subDirs = subDirs
rootDir, subMat, subMagn, subRun, seq = subDirs
self._mainDir = os.path.join(rootDir, subMat, subMagn, subRun)
self._colorImage = None
self._koreanPalette = None
self._isColorImage = False
self._isSwitchAndStepsDone = False
self._isDistributions = False
self._switchTimes = None
self._threshold = None
self._figTimeSeq = None
self.figDiffs = None
self._figHistogram = None
self.is_histogram = False
self._figColorImage = None
self._figColorImage2 = None
self.isConnectionRawImage = False
self.figRawAndCalc = None
self.imagesRange = (firstIm, lastIm)
self.imageDir = None
self.initial_domain_region = initial_domain_region
self.is_plotContours = False
self.isTwoImages = False
self.is_minmax_switches = False
self.pattern = pattern
self.fillValue = fillValue
NN = 3
self.NNstructure = np.ones((NN,NN))
if boundary == 'periodic':
self.boundary = 'periodic'
else:
self.boundary = None
if not lastIm:
lastIm = -1
# Variables for image analysis
self.exclude_switches_out_of_final_domain = exclude_switches_out_of_final_domain
self.erase_small_events_percent = erase_small_events_percent
self.visualization_library = visualization_library
# Check paths
if not os.path.isdir(self._mainDir):
print("Please check you dir %s" % self._mainDir)
print("Path not found")
sys.exit()
#############################################################################
out = collect_images.images2array(self._mainDir, pattern, firstIm, lastIm, imCrop,
rotation, filtering, sigma, subtract=subtract,
hdf5_use=hdf5_use, hdf5_signature=hdf5_signature)
if hdf5_use:
self.Array, self.imageNumbers, self.hdf5 = out
else:
self.Array, self.imageNumbers = out
##############################################################################
self.shape = self.Array.shape
self.n_images, self.dimX, self.dimY = self.shape
print("%i image(s) loaded, of %i x %i pixels" % (self.n_images, self.dimX, self.dimY))
if imCrop is None:
self.imWidth, self.imHeight = self.dimX, self.dimY
else:
(x0, y0), (x1, y1) = imCrop
self.imWidth, self.imHeight = (x1-x0), (y1 -y0)
if kernel_sign is None:
self.multiplier = 1
self.isMultiplierSetByUser = False
else:
self.multiplier = kernel_sign
self.isMultiplierSetByUser = True
self.convolSize = kernel_half_width_of_ones
# Make a kernel as a step-function
self.kernel_half_width_of_ones = kernel_half_width_of_ones
self.visualization_library = visualization_library
# def _get_multiplier(self, method='average_gray'):
# """
# multiplier is +1 if -1 -> +1
# multiplier is -1 if +1 -> -1
# The method below is only valid for bubbles
# TODO: make it as a specific method of the subclasses (bubbles, wires, labyrinths)
# """
# if method == 'average_gray':
# grey_first_image = np.mean([scipy.mean(self.Array[k,:,:].flatten()) for k in range(4)])
# grey_last_image = np.mean([scipy.mean(self.Array[-k,:,:].flatten()) for k in range(1,5)])
# print("grey scale: %i, %i" % (grey_first_image, grey_last_image))
# if grey_first_image > grey_last_image:
# return 1.
# else:
# return -1.
# elif method == 'bubble':
# #im = self.Array[-1]
# return -1
def __get__(self):
"""
redifine the get
"""
return self.Array
def __getitem__(self,n):
"""Get the n-th image"""
index = self._getImageIndex(n)
if index is not None:
return self.Array[index]
def _getImageIndex(self,n):
"""
check if image number n has been loaded
and return the index of it in the Array
"""
ns = list(self.imageNumbers)
try:
if n < 0:
n = self.imageNumbers[n]
return ns.index(n)
except:
print("Image number %i is out of the range (%i,%i)" % (n, ns[0], ns[-1]))
return None
def showMeanGreyLevels(self):
indexImages = np.array(self.imageNumbers) - self.imageNumbers[0]
plt.figure()
for n in indexImages:
meanGrey = np.mean(self.Array[n,:,:].flatten())
plt.plot(n, meanGrey, 'bo')
return
def showRawImage(self, imageNumber, plugin='mpl'):
"""
showImage(imageNumber)
Show the n-th image where n = image_number
Parameters:
---------------
imageNumber : int
Number of the image to be shown.
plugin : str, optional
Use a plugin to show an image (default: matplotlib)
"""
n = self._getImageIndex(imageNumber)
if n is not None:
im = self[imageNumber]
if plugin == 'mpl':
plt.imshow(im, plt.cm.gray)
plt.show()
else:
im_io.imshow(self[imageNumber])
def _getWidth(self):
try:
width = self.width
except:
self.width = 'all'
print("Warning: the levels are calculated over all the points of the sequence")
return self.width
def _pixel2rowcol(self, pixel, closest_integer=False):
"""
Transforn from pixel values to (row, col)
calculating the integer values if needed
"""
if closest_integer:
pixel = int(round(pixel[0])), int(round(pixel[1]))
return pixel[1], pixel[0]
def pixelTimeSequence(self,pixel=(0,0)):
"""
pixelTimeSequence(pixel)
Returns the temporal sequence of the gray level of a pixel
Parameters:
---------------
pixel : tuple
The (x,y) pixel of the image, as (row, column)
"""
x,y = self._pixel2rowcol(pixel)
return self.Array[:,x,y]
def showPixelTimeSequence(self, pixel=(0,0), newPlot=False, show_kernel=True):
"""
pixelTimeSequenceShow(pixel)
Plot the temporal sequence of the gray levels of a pixel;
Parameters:
---------------
pixel : tuple
The (x,y) pixel of the image
newPlot : bool
Option to open a new frame or use the last one
show_kernel : bool
Show the kernel (step function) in the plot
"""
if not self._figTimeSeq or newPlot==True:
self._figTimeSeq = plt.figure()
else:
plt.figure(self._figTimeSeq.number)
ax = plt.gca()
# Plot the temporal sequence first
pxt = self.pixelTimeSequence(pixel)
label_pixel = "(%i, %i)" % (pixel[0], pixel[1])
ax.plot(self.imageNumbers,pxt,'-o', label=label_pixel)
# Add the calculus of GPU
row, col = self._pixel2rowcol(pixel)
switch = self._switchTimes2D[row, col]
step = self._switchSteps2D[row, col]
# Plot the step-like function
l0 = self.kernel_half_width_of_ones
pxt_average = np.mean(pxt[switch - l0:switch + l0]) # to check
print("switch at %i, gray level change = %i" % (switch, step))
kernel0 = -self.multiplier * np.ones(self.kernel_half_width_of_ones)
kernel0 = np.concatenate((kernel0, -kernel0))
kernel = kernel0 * step / 2 + pxt_average
# This is valid for the step kernel ONLY
x = np.arange(switch - l0, switch + l0)
ax.plot(x, kernel, '-o')
plt.legend()
plt.show()
def getSwitchTime(self, pixel=(0,0), useKernel='step', method='convolve1d'):
"""
getSwitchTime(pixel, useKernel='step', method="convolve1d")
Return the position of a step in a sequence
and the left and the right values of the gray level (as a tuple)
Parameters:
---------------
pixel : tuple
The (x,y) pixel of the image, as (row, column).
useKernel : string
step = [1]*5 +[-1]*5
zero = [1]*5 +[0] + [-1]*5
both = step & zero, the one with the highest convolution is chosen
method : string
For the moment, only the 1D convolution calculation
with scipy.ndimage.convolve1d is available
"""
pxTimeSeq = self.pixelTimeSequence(pixel)
if method == "convolve1d":
if useKernel == 'step' or useKernel == 'both':
convolution_of_stepKernel = nd.convolve1d(pxTimeSeq,self.kernel)
minStepKernel = convolution_of_stepKernel.min()
switchStepKernel = convolution_of_stepKernel.argmin() +1
switch = switchStepKernel
kernel_to_use = 'step'
if useKernel == 'zero' or useKernel == 'both':
convolution_of_zeroKernel = nd.convolve1d(pxTimeSeq,self.kernel0)
minZeroKernel = convolution_of_zeroKernel.min()
switchZeroKernel = convolution_of_zeroKernel.argmin() + 1
switch = switchZeroKernel
kernel_to_use = 'zero'
if useKernel == 'both':
if minStepKernel <= minZeroKernel:
switch = switchStepKernel
kernel_to_use = 'step'
else:
switch = switchZeroKernel
kernel_to_use = 'zero'
else:
raise RuntimeError("Method not yet implemented")
levels = self._getLevels(pxTimeSeq, switch, kernel_to_use)
# Now redefine the switch using the correct image number
switch = self.imageNumbers[switch]
return switch, levels
def _imDiff(self, imNumbers, invert=False):
"""Properly rescaled difference between images
Parameters:
---------------
imNumbers : tuple
the numbers the images to subtract
invert : bool
Invert black and white grey levels
TODO: do it properly!!!!
"""
i, j = imNumbers
try:
im = self[i]-self[j]
except:
return
if invert:
im = 255 - im
imMin = scipy.amin(im)
imMax = scipy.amax(im)
im = scipy.absolute(im-imMin)/float(imMax-imMin)*255
return scipy.array(im,dtype='int16')
def showTwoImageDifference(self, imNumbers, invert=False):
"""Show the output of self._imDiff
Parameters:
---------------
imNumbers : tuple
the numbers of the two images to subtract
invert : bool, opt
Invert the gray level black <-> white
"""
if type(invert).__name__ == 'int':
imNumbers = imNumbers, invert
print("Warning: you should use a tuple as image Numbers")
try:
plt.imshow(self._imDiff(imNumbers, invert), plt.cm.gray)
plt.show()
except:
return
def imDiffSave(self,imNumbers='all', invert=False, mainDir=None):
"""
Save the difference(s) between a series of images
Parameters:
---------------
imNumbers : tuple or string
the numbers of the images to subtract
* when 'all' the whole sequence of differences is saved
* when a tuple of two number (i.e., (i, j),
all the differences of the images between i and j (included)
are saved
"""
if mainDir == None:
mainDir = self._mainDir
dirSeq = os.path.join(mainDir,"Diff")
if not os.path.isdir(dirSeq):
os.mkdir(dirSeq)
if imNumbers == 'all':
imRange = self.imageNumbers[:-1]
else:
im0, imLast = imNumbers
imRange = range(im0, imLast)
if im0 >= imLast:
print("Error: sequence not valid")
return
for i in imRange:
im = self._imDiff((i+1,i))
imPIL = scipy.misc.toimage(im)
fileName = "imDiff_%i_%i.tif" % (i+1,i)
print(fileName)
imageFileName = os.path.join(dirSeq, fileName)
imPIL.save(imageFileName)
def getSwitchTimesAndStepsAndThresholdAndMultiplier(self, isCuda=True, kernel=None, device=0, threshold=None, showHist=True):
"""
Calculate the switch times and the gray level changes
for each pixel in the image sequence.
It calculates:
self._switchTimes
self._switchSteps
Calculus of switch times.
Assume a kernel from +1 to -1, for reference
if kernel is a step function, switch is the last point at +1
so we need to add 1 to switch
If kernel has points between +1 and -1,
i.e. self.kernel_internal_points is not 0
we need to add int(self.kernel_internal_points/2) + 1
"""
#if kernel is None:
# kernel = self.kernel
startTime = time.time()
# ####################
if isPyCuda and isCuda:
#kernel32 = np.asarray(kernel, dtype=np.int32)
stack32 = np.asarray(self.Array, dtype=np.int32)
need_mem = 2 * stack32.nbytes + 2 * stack32[0].nbytes
print("Total memory to be used: %.2f GB" % (need_mem/1e9))
current_dev, ctx, (free_mem_gpu, total_mem_gpu) = mkGpu.gpu_init(device)
if need_mem < free_mem_gpu:
switchTimesMin, switchStepsMin, switchTimesMax, switchStepsMax = get_gpuSwitchTime(stack32, self.convolSize,self.multiplier, current_dev, ctx)
else:
nsplit = int(float(need_mem)/free_mem_gpu) + 1
print("Splitting images in %d parts..." % nsplit)
stack32s = np.array_split(stack32, nsplit, 1)
print("Done")
switchTimesMin = np.array([])
switchStepsMin = np.array([])
for k, stack32 in enumerate(stack32s):
print("Calculation split %i" % k)
#a = stack32.astype(np.int32)
switch, step, switchMax, stepMax = get_gpuSwitchTime(stack32, self.convolSize,self.multiplier, current_dev, ctx)
if not k:
switchTimesMin = switch
switchStepsMin = step
switchTimesMax = switchMax
switchStepsMax = stepMax
else:
switchTimesMin = np.vstack((switchTimesMin, switch))
switchStepsMin = np.vstack((switchStepsMin, step))
switchTimesMax = np.vstack((switchTimesMax, switchMax))
switchStepsMax = np.vstack((switchStepsMax, stepMax))
switchStepsMin = switchStepsMin.flatten()
switchStepsMax = switchStepsMax.flatten()
# Add the value of the first image
switchTimesMin = self.imageNumbers[0] + switchTimesMin.flatten()
switchTimesMax = self.imageNumbers[0] + switchTimesMax.flatten()
# Close device properly
success = mkGpu.gpu_deinit(current_dev, ctx)
if not success:
print("There is a problem with the device %i" % device)
print('Analysing done in %f seconds' % (time.time()-startTime))
else:
# DO NOT USE!
switchTimes = []
switchSteps = []
for x in range(self.dimX):
# Print current row
if not (x+1)%10:
strOut = 'Analysing row: %i/%i on %f seconds\r' % (x+1, self.dimX, time.time()-startTime)
sys.stderr.write(strOut)
#sys.stdout.flush()
for y in range(self.dimY):
switch, levels = self.getSwitchTime((x,y))
grayChange = np.abs(levels[0]- levels[1])
if switch == 0: # TODO: how to deal with steps at zero time
print(x,y)
switchTimes.append(switch)
switchSteps.append(grayChange)
print("\n")
# Note that the _swithchSteps can be zero and
# _swithTimes set to the first image
# This problem must be solved out this method
self._switchTimes = np.asarray(switchTimes)
self._switchSteps = np.asarray(switchSteps)
# Below : Calculates the threshold and the multiplier
# It is necessary to calculate it just after get_gpuSwitchTime because
# we need both switchStepsMin and switchStepsMax to calculate the multiplier
if showHist:
plt.hist(np.concatenate([switchStepsMin, switchStepsMax]), bins=100)
plt.show()
mean_mins_convol = abs(np.mean(switchStepsMin))
mean_maxs_convol = abs(np.mean(switchStepsMax))
if(mean_mins_convol > mean_maxs_convol):
estimated_threshold = mean_mins_convol
print("Estimated threshold : ", estimated_threshold)
print("Estimated multiplier :", self.multiplier) #If the negative ("min") levels have a greater average than the positive ones ("max"), we chose the right multiplier
if not self.isMultiplierSetByUser:
print("Multiplier set to", self.multiplier)
self._switchSteps = np.abs(switchStepsMin)
self._switchTimes = switchTimesMin
else:
estimated_threshold = mean_maxs_convol
print("Estimated threshold : ", estimated_threshold)
print("Estimated multiplier :", -self.multiplier) #Otherwise, we chose the wrong one => we have to change (change made if multiplier was not defined by the user only)
if self.isMultiplierSetByUser:
warnings.warn("You may have chosen the wrong multiplier")
self._switchSteps = np.abs(switchStepsMin)
self._switchTimes = switchTimesMin
else:
self.multiplier *= -1
print("Multiplier set to", self.multiplier)
self._switchSteps = np.abs(switchStepsMax)
self._switchTimes = switchTimesMax
if threshold is None:
self._threshold = estimated_threshold
print("Threshold set to", self._threshold)
else:
self._threshold = threshold
self._isColorImage = True
self._isSwitchAndStepsDone = True
return
def _getSwitchTimesOverThreshold(self, isFirstSwitchZero=False, fillValue=-1):
"""
_getSwitchTimesOverThreshold()
Returns the array of the switch times
considering a self._threshold in the gray level change at the switch
Parameters:
----------------
isFirstSwitchZero : bool
Put the first switch equal to zero, useful to set the colors
in a long sequence of images where the first avalanche
occurs after many frames
fillValue : number, int
The value to set in the array for the non-switching pixel (below the threshold)
-1 is used as the last value of array when used as index (i.e. with colors)
"""
# self.isPixelSwitched = (self._switchSteps >= self._threshold)
###
#get sigma from hist of images and use it as threshold
###
#self._setThresholdAndSwitchTimesAndLevels(self._threshold)
self.isPixelSwitched = (self._switchSteps >= self._threshold) & (self._switchTimes > self.kernel_half_width_of_ones)
maskedSwitchTimes = ma.array(self._switchTimes, mask = ~self.isPixelSwitched)
# Move to the first switch time if required
self._switchTimesOverThreshold = maskedSwitchTimes.compressed()
if isFirstSwitchZero:
maskedSwitchTimes = maskedSwitchTimes - self.min_switch
# Set the non-switched pixels to use the last value of the pColor array, i.e. noSwitchColorValue
switchTimesWithFillValue = maskedSwitchTimes.filled(fillValue) # Isn't it fantastic?
return switchTimesWithFillValue
def _isColorImageDone(self,ask=True, threshold=None):
print("You must first run the getSwitchTimesAndStepsAndThresholdAndMultiplier script: I'll do that for you")
if ask:
yes_no = raw_input("Do you want me to run the script for you (y/N)?")
yes_no = yes_no.upper()
if yes_no != "Y":
return
self.getSwitchTimesAndStepsAndThresholdAndMultiplier(threshold=threshold)
return
def _getColorImage(self, palette, noSwitchColor='black', erase_small_events_percent=None, threshold=None):
"""
Calculate the color Image using the output of getSwitchTimesAndStepsAndThresholdAndMultiplier
Parameters:
---------------
threshold: int, opt
Set the minimim value of the gray level change at the switch to
consider the pixel as 'switched', i.e. belonging to an avalanche
This value is set as a class variable from here on.
Rerun self._getColorImage to change it
Results:
----------
self._switchTimes2D as a 2D array of the switchTime
with steps >= threshold, and first image number set to 0
"""
if not self._isSwitchAndStepsDone:
self._isColorImageDone(ask=False, threshold=threshold)
elif threshold is not None :
self._threshold = threshold #It is necessary to be able to change the threshold even after the calculation of switches (when _isSwitchAndStepsDone is True)
self.min_switch = np.min(self._switchTimes)
self.max_switch = np.max(self._switchTimes)
print("Avalanches occur between frame %i and %i" % (self.min_switch, self.max_switch))
self._nImagesWithSwitch = self.max_switch - self.min_switch + 1
print("Gray changes are between %s and %s" % (min(self._switchSteps), max(self._switchSteps)))
# Calculate the colours, considering the range of the switch values obtained
self._pColors = getPalette(self._nImagesWithSwitch, palette, noSwitchColor)
self._colorMap = mpl.colors.ListedColormap(self._pColors, 'pColorMap')
if self.visualization_library == 'bokeh':
background_color = mpl.colors.to_hex(noSwitchColor)
if "_" in palette:
name, number = palette.split("_")
number = int(number)
p = [background_color] + list(palettes.all_palettes[name][number])
else:
p = [mpl.colors.to_hex(c) for c in self._colorMap.colors]
p = [background_color] + p
self._colorMap = tuple(p)
central_points = np.arange(self.min_switch, self.max_switch, dtype=float)
# Calculate the switch time Array (2D) considering the threshold and the start from zero
self._switchTimes2D = self._getSwitchTimesOverThreshold(False, self.fillValue).reshape(self.dimX, self.dimY)
self._switchSteps2D = self._switchSteps.reshape(self.dimX, self.dimY)
self._switchTimes2D_original = np.copy(self._switchTimes2D)
# Now check if getting rid of the wrong switches
if self.exclude_switches_out_of_final_domain:
print("%s Exclude switches out of final domain" % SPACE)
q = self._switchTimes2D != self.fillValue
clusters, n_cluster = mahotas.label(q, self.NNstructure)
sizes = mahotas.labeled.labeled_size(clusters)
max_size = np.max(sizes[1:])
too_small = np.where(sizes < max_size)
# Get the largest final domain only
final_domain = mahotas.labeled.remove_regions(clusters, too_small).astype('bool')
self._switchTimes2D[~final_domain] = self.fillValue
if self.erase_small_events_percent:
print("%s erase_small_events_percent" % SPACE)
percentage = self.erase_small_events_percent/100.
# This gets rid of the wrong switchesf
# Using the cluster max sizes for the switches
# It redefines self._switchTimes2D
#self.final_domain = self._find_final_domain(self._switchTimes2D, fillValue)
#self._switchTimes2D[self.final_domain == False] = -1
# Erase small event
#im, n_cluster = mahotas.label(~self.final_domain, self.NNstructure)
q = np.copy(self._switchTimes2D)
q[q == -1] = 0
im, n_cluster = mahotas.label(q, self.NNstructure)
im = mahotas.labeled.remove_bordering(im)
im, n_cluster = mahotas.labeled.relabel(im)
sizes = mahotas.labeled.labeled_size(im)
if len(sizes) > 1:
too_small = np.where(sizes < percentage * np.max(sizes[1:]))
im = mahotas.labeled.remove_regions(im, too_small)
print("Small events erased")
#index_max_size = sizes.argmax()
#self.initial_domain = im == index_max_size + 1
# Erase the small switches
self._switchTimes2D[im == 0] = self.fillValue
if self.fillValue in self._switchTimes2D:
self._switchTimesUnique = np.unique(self._switchTimes2D)[1:] + self.min_switch
else:
self._switchTimesUnique = np.unique(self._switchTimes2D) + self.min_switch
return
def showColorImage(self, threshold=None, data=None, palette='random', erase_small_events_percent=None,
plotHist=False, plot_contours=False, noSwitchColor='black',
ask=False, fig=None, ax=None, title=None, figsize=(8,7),
xax=False, yax=False):
"""
Show the calculated color Image of the avalanches.
Run getSwitchTimesAndStepsAndThresholdAndMultiplier if not done before.
Parameters
---------------
threshold: integer, optional
Defines if the pixel switches when gray_level_change >= threshold
palette: string, required, default = 'random'
erase_small_events_percent: int, optional
Erase events smaller than a percentage of the largest one
noSwithColor: string, optional, default = 'black'
background color for pixels having gray_level_change below the threshold
"""
# set the threshold
# estimated_threshold = int(np.std(self.Array.flatten())*0.1)
# print("Estimated threshold = %d" % estimated_threshold)
# if not threshold:
# self._threshold = estimated_threshold
# else:
# self._threshold = threshold
# Calculate the Color Image
self._getColorImage(palette, noSwitchColor, erase_small_events_percent, threshold)
# Prepare to plot
if data is None:
data = self._switchTimes2D
if fig is None:
self._figColorImage = self._plotColorImage(data,
self._colorMap, self._figColorImage,
title=title, figsize=figsize)
fig = self._figColorImage
else:
fig = self._plotColorImage(data, colorMap=self._colorMap,
fig=fig, ax=ax, title=title)
if plot_contours:
if ax is None:
ax = fig.gca()
self.plotContours(lines_color='black', remove_bordering=True, invert_y_axis=False,
fig=fig, ax=ax)
if plotHist:
# Plot the histogram
self.plotHistogram(self._switchTimesOverThreshold, ylabel="Avalanche size (pixels)")
# Count the number of the switched pixels
switchPixels = np.sum(self.isPixelSwitched)
totNumPixels = self.dimX * self.dimY
noSwitchPixels = totNumPixels - switchPixels
swPrint = (switchPixels, switchPixels/float(totNumPixels)*100.,
noSwitchPixels, noSwitchPixels/float(totNumPixels)*100.)
print("There are %d (%.2f %%) switched and %d (%.2f %%) not-switched pixels" % swPrint)
plt.show()
return fig
def _call_pixel_switch(self, p0, p1):
x, y = self._pixel2rowcol((p0,p1), closest_integer=True)
if x >= 0 and x < self.dimX and y >= 0 and y < self.dimY:
index = x * self.dimY + y
s = "pixel (%i,%i) - switch at: %i, gray step: %i" % \
(p0, p1, self._switchTimes2D[x,y], self._switchSteps2D[x,y])
return s
else:
return ""
def _call_pixel_time_sequence(self, event):
if event.dblclick:
pixel = int(round(event.xdata)), int(round(event.ydata))
print("Pixel: (%i, %i)" % (pixel[0],pixel[1]))
self.showPixelTimeSequence(pixel, newPlot=True)
#plt.show()
def _plotColorImage(self, data, colorMap, fig=None, ax=None, title=None, figsize=(8,7)):
"""
if the caption is not shown, just enlarge the image
as it depends on the length of the string retured by
_call_pixel_switch
"""
# Sets the limits of the image
extent = 0, self.dimY, self.dimX, 0
bounds = np.unique(data)
bounds = np.append(bounds, bounds[-1]+1)-0.5
self.norm = mpl.colors.BoundaryNorm(bounds, len(bounds)-1)
if self.visualization_library == 'mpl':
if not fig:
fig = plt.figure()
fig.set_size_inches(*figsize, forward=True)
ax = fig.add_subplot(1, 1, 1)
else:
fig = plt.figure(fig.number)
if ax is None:
ax = fig.gca()
ax.format_coord = lambda p0, p1: self._call_pixel_switch(p0, p1)
#ax.pcolormesh(data,cmap=colorMap,norm=self.norm)
ax.imshow(data, cmap=colorMap, norm=self.norm)
ax.axis(extent)
for tick in ax.xaxis.get_major_ticks():
tick.label.set_fontsize('xx-small')
for tick in ax.yaxis.get_major_ticks():
tick.label.set_fontsize('xx-small')
if title is None:
first, last = self.imagesRange
#title = "DW motion from image %i to image %i" % (first, last)
title = self.pattern
ax.set_title(title, fontsize='xx-small')
cid = fig.canvas.mpl_connect('button_press_event', self._call_pixel_time_sequence)
elif self.visualization_library == 'bokeh':
xdr = DataRange1d(bounds=None)
ydr = DataRange1d(bounds=None)
if not fig:
fig = plk.figure(x_range=xdr, y_range=ydr,
tooltips=[("x", "$x"), ("y", "$y"), ("switch", "@image")], match_aspect=True,
plot_width=self.dimY, plot_height=self.dimX, tools='pan,box_zoom,reset')
xlabel_pos = self.dimY - len(title)*12 - 3
_title = Label(x=xlabel_pos, y=self.dimX * 0.9, text=title,render_mode='css',
background_fill_color='black', background_fill_alpha=1.0,
text_font_size='12px', text_color='white')
fig.add_layout(_title)
#fig.x_range.range_padding = fig.y_range.range_padding = 0
#fig.renderers = []
fig.image(image=[np.flipud(data)], x=0, y=0, dw=self.dimY, dh=self.dimX, palette=colorMap)
#fig.add_tools(bkm.PanTool(), bkm.WheelZoomTool(), bkm.BoxSelectTool(), bkm.BoxZoomTool(),
# bkm.LassoSelectTool(), bkm.PanTool(), bkm.WheelZoomTool(), bkm.SaveTool(), bkm.ResetTool())
#fig.add_tools(bkm.BoxSelectTool(), bkm.ResetTool())
#print(fig)
return fig
def plotHistogram(self, data, palette='random',fill_color=None, fig=None, ax=None, title=None, ylabel=None):
#image_numbers = np.unique(data)
#i0, i1 = image_numbers[0], image_numbers[-1] + 1
#central_points = np.arange(i0, i1)
central_points = self.imageNumbers
rng = np.append(central_points, central_points[-1] + 1) - 0.5
if self.visualization_library == 'mpl':
if fig:
plt.figure(fig.number)
if ax is None:
ax = plt.gca()
else:
if self._figHistogram is None:
self._figHistogram = plt.figure()
else:
plt.figure(self._figHistogram.number)
plt.clf()
ax = plt.gca()
self.N_hist, self.bins_hist, patches = ax.hist(data, rng)
ax.format_coord = lambda x,y : "image Number: %i, avalanche size (pixels): %i" % (int(x+0.5), int(y+0.5))
ax.set_xlabel("image number",fontsize='xx-small')
if title:
ax.set_title(title, fontsize='xx-small')
if ylabel:
ax.set_ylabel(ylabel, fontsize='xx-small')
ax.set_xlim(0, ax.get_xlim()[1])
# Set the colors
for thisfrac, thispatch in zip(central_points, patches):
c = self._colorMap(self.norm(thisfrac))
thispatch.set_facecolor(c)
self.is_histogram = True
elif self.visualization_library == 'bokeh':
hist, edges = np.histogram(data, bins=rng, density=True)
#fill_color = [self._colorMap(self.norm(c)) for c in central_points]
fig = plk.figure(title=title, tools='', background_fill_color="#fafafa")
#mapper = linear_cmap(field_name='edges', palette=palette ,low=edges[1],high=edges[-1])
fig.quad(top=hist,bottom=0, left=edges[:-1], right=edges[1:],
fill_color=self._colorMap[:len(edges)-1],
#fill_color = self._colorMap,
line_color="white", alpha=1)
fig.y_range.start = 0
fig.grid.grid_line_color = 'white'
return fig
def saveColorImage(self,fileName,threshold=None, palette='random',noSwitchColor='black'):
"""
saveColorImage(fileName, threshold=None,
palette='korean',noSwitchColor='black')
makes color image and saves
"""
self._colorImage = self._getColorImage(palette,noSwitchColor)
imOut = scipy.misc.toimage(self._colorImage)
imOut.save(fileName)
def saveImage(self, figureNumber):
"""
generic method to save an image or a plot in the figure(figureNumber)
"""
filename = raw_input("file name (.png for images)? ")
fig = plt.figure(figureNumber)
ax = fig.gca()
if len(ax.get_images()):
im = ax.get_images()[-1]
name, ext = os.path.splitext(filename)
if ext != ".png":
filename = name +".png"
filename = os.path.join(self._mainDir, filename)
im.write_png(filename)
else:
filename = os.path.join(self._mainDir, filename)
fig.save(filename)
def imDiffCalculated(self, imageNum, haveColors=True):
"""
Get the difference in BW between two images imageNum and imageNum+1
as calculated by the self._colorImage