-
Notifications
You must be signed in to change notification settings - Fork 28
/
post_processing.py
1774 lines (1435 loc) · 72.4 KB
/
post_processing.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 torch
import cv2
import os
import math
import statistics
import sys
import time
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.transforms as transforms
import fill_voids
import edt
from tqdm import tqdm
from scipy import ndimage as ndi
from scipy.signal import find_peaks
from scipy.spatial import KDTree, cKDTree
from scipy.spatial.distance import cdist
from scipy.ndimage.morphology import binary_erosion, binary_dilation
from scipy.ndimage import rotate, grey_dilation, distance_transform_edt
from scipy.signal import savgol_filter
from scipy.ndimage.filters import median_filter
from scipy.ndimage.measurements import center_of_mass
from skimage import morphology
from skimage.morphology import disk, ball, remove_small_objects, dilation, erosion
from skimage.segmentation import watershed
from skimage.filters import rank, threshold_otsu
from skimage.measure import label, regionprops_table
from skimage.io import imread
from skimage.exposure import equalize_adapthist
from engine.metrics import jaccard_index_numpy
from utils.util import pad_and_reflect, save_tif
from data.pre_processing import normalize
from data.data_3D_manipulation import crop_3D_data_with_overlap
from data.pre_processing import reduce_dtype
def boundary_refinement_watershed(X, Y_pred, erode=True, save_marks_dir=None):
"""Apply watershed to the given predictions with the goal of refine the boundaries of the artifacts.
Based on https://docs.opencv.org/master/d3/db4/tutorial_py_watershed.html.
Parameters
----------
X : 4D Numpy array
Original data to guide the watershed. E.g. ``(img_number, y, x, channels)``.
Y_pred : 4D Numpy array
Predicted data to refine the boundaries. E.g. ``(img_number, y, x, channels)``.
erode : bool, optional
To extract the sure foreground eroding the artifacts instead of doing with distanceTransform.
save_marks_dir : str, optional
Directory to save the markers used to make the watershed. Useful for debugging.
Returns
-------
Array : 4D Numpy array
Refined boundaries of the predictions. E.g. ``(img_number, y, x, channels)``.
Examples
--------
+------------------------------------------------+------------------------------------------------+
| .. figure:: ../../../img/lucchi_test_0.png | .. figure:: ../../../img/lucchi_test_0_gt.png |
| :width: 80% | :width: 80% |
| :align: center | :align: center |
| | |
| Original image | Ground truth |
+------------------------------------------------+------------------------------------------------+
| .. figure:: ../../../img/lucchi_test_0_pred.png| .. figure:: ../../../img/lucchi_test_0_wa.png |
| :width: 80% | :width: 80% |
| :align: center | :align: center |
| | |
| Predicted image | Watershed ouput |
+------------------------------------------------+------------------------------------------------+
The marks used to guide the watershed is this example are these:
.. image:: ../../../img/watershed2_marks_test0.png
:width: 70%
:align: center
"""
if save_marks_dir is not None:
os.makedirs(save_marks_dir, exist_ok=True)
watershed_predictions = np.zeros(Y_pred.shape[:3])
kernel = np.ones((3,3),np.uint8)
d = len(str(X.shape[0]))
for i in tqdm(range(X.shape[0])):
im = cv2.cvtColor(X[i,...]*255, cv2.COLOR_GRAY2RGB)
pred = Y_pred[i,...,0]
# sure background area
sure_bg = cv2.dilate(pred, kernel, iterations=3)
sure_bg = np.uint8(sure_bg)
# Finding sure foreground area
if erode:
sure_fg = cv2.erode(pred, kernel, iterations=3)
else:
dist_transform = cv2.distanceTransform(a, cv2.DIST_L2, 5)
ret, sure_fg = cv2.threshold(dist_transform, 0.7*dist_transform.max(), 255,0)
sure_fg = np.uint8(sure_fg)
# Finding unknown region
unknown_reg = cv2.subtract(sure_bg, sure_fg)
# Marker labelling
ret, markers = cv2.connectedComponents(sure_fg)
# Add one to all labels so that sure background is not 0, but 1
markers = markers+1
# Now, mark the region of unknown with zero
markers[unknown_reg==1] = 0
if save_marks_dir is not None:
f = os.path.join(save_marks_dir, "mark_" + str(i).zfill(d) + ".png")
cv2.imwrite(f, markers)
markers = cv2.watershed((im).astype(np.uint8), markers)
watershed_predictions[i] = markers
# Label all artifacts into 1 and the background with 0
watershed_predictions[watershed_predictions==1] = 0
watershed_predictions[watershed_predictions>1] = 1
watershed_predictions[watershed_predictions==-1] = 0
return np.expand_dims(watershed_predictions, -1)
def boundary_refinement_watershed2(X, Y_pred, save_marks_dir=None):
"""Apply watershed to the given predictions with the goal of refine the boundaries of the artifacts. This function
was implemented using scikit instead of opencv as :meth:`post_processing.boundary_refinement_watershed`.
Based on https://scikit-image.org/docs/dev/auto_examples/segmentation/plot_watershed.html.
Parameters
----------
X : 4D Numpy array
Original data to guide the watershed. E.g. ``(img_number, y, x, channels)``.
Y_pred : 4D Numpy array
Predicted data to refine the boundaries. E.g. ``(img_number, y, x, channels)``.
save_marks_dir : str, optional
Directory to save the markers used to make the watershed. Useful for debugging.
Returns
-------
Array : 4D Numpy array
Refined boundaries of the predictions. E.g. ``(img_number, y, x, channels)``.
"""
if save_marks_dir is not None:
os.makedirs(save_marks_dir, exist_ok=True)
watershed_predictions = np.zeros(Y_pred.shape[:3], dtype=np.uint8)
d = len(str(X.shape[0]))
for i in tqdm(range(X.shape[0])):
im = (X[i,...,0]*255).astype(np.uint8)
pred = (Y_pred[i,...,0]*255).astype(np.uint8)
# find continuous region
markers = rank.gradient(pred, disk(12)) < 10
markers = ndi.label(markers)[0]
# local gradient (disk(2) is used to keep edges thin)
gradient = rank.gradient(im, disk(2))
# process the watershed
labels = watershed(gradient, markers)
if save_marks_dir is not None:
f = os.path.join(save_marks_dir, "mark_" + str(i).zfill(d) + ".png")
cv2.imwrite(f, markers)
watershed_predictions[i] = labels
# Label all artifacts into 1 and the background with 0
watershed_predictions[watershed_predictions==1] = 0
watershed_predictions[watershed_predictions>1] = 1
return np.expand_dims(watershed_predictions, -1)
def watershed_by_channels(data, channels, ths={}, remove_before=False, thres_small_before=10, seed_morph_sequence=[],
seed_morph_radius=[], erode_and_dilate_foreground=False, fore_erosion_radius=5, fore_dilation_radius=5,
rmv_close_points=False, remove_close_points_radius=-1, resolution=[1,1,1], save_dir=None):
"""
Convert binary foreground probability maps and instance contours to instance masks via watershed segmentation
algorithm.
Implementation based on `PyTorch Connectomics' process.py
<https://github.com/zudi-lin/pytorch_connectomics/blob/master/connectomics/utils/process.py>`_.
Parameters
----------
data : 4D Numpy array
Binary foreground labels and contours data to apply watershed into. E.g. ``(397, 1450, 2000, 2)``.
channels : str
Channel type used. Possible options: ``BC``, ``BCM``, ``BCD``, ``BCDv2``, ``Dv2`` and ``BDv2``.
ths : float, optional
Thresholds to be used on each channel. ``TH_BINARY_MASK`` used in the semantic mask to create watershed seeds;
``TH_CONTOUR`` used in the contours to create watershed seeds; ``TH_FOREGROUND`` used in the semantic mask to create the
foreground mask; ``TH_POINTS`` used in the point mask to create watershed seeds; ``TH_DISTANCE`` used in the
distances to create watershed seeds.
remove_before : bool, optional
To remove objects before watershed.
thres_small_before : int, optional
Theshold to remove small objects created by the watershed.
seed_morph_sequence : List of str, optional
List of strings to determine the morphological filters to apply to instance seeds. They will be done in that order.
E.g. ``['dilate','erode']``.
seed_morph_radius: List of ints, optional
List of ints to determine the radius of the erosion or dilation for instance seeds.
erode_and_dilate_foreground : bool, optional
To erode and dilate the foreground mask before using marker controlled watershed. The idea is to
remove the small holes that may be produced so the instances grow without them.
fore_erosion_radius: int, optional
Radius to erode the foreground mask.
fore_dilation_radius: int, optional
Radius to dilate the foreground mask.
rmv_close_points : bool, optional
To remove close points to each other. Used in 'BP' channel configuration.
remove_close_points_radius : float, optional
Radius from each point to decide what points to keep. Used in 'BP' channel configuration.
E.g. ``10.0``.
resolution : ndarray of floats
Resolution of the data, in ``(z,y,x)`` to calibrate coordinates. E.g. ``[30,8,8]``.
save_dir : str, optional
Directory to save watershed output into.
"""
assert channels in ['BC', 'BCM', 'BCD', 'BCDv2', 'Dv2', 'BDv2', 'BP', 'BD']
def erode_seed_and_foreground():
nonlocal seed_map
nonlocal foreground
if len(seed_morph_sequence) != 0:
print("Applying {} to seeds . . .".format(seed_morph_sequence))
if erode_and_dilate_foreground:
print("Foreground erosion . . .")
if len(seed_morph_sequence) != 0:
morph_funcs = []
for operation in seed_morph_sequence:
if operation == "dilate":
morph_funcs.append(binary_dilation)
elif operation == "erode":
morph_funcs.append(binary_erosion)
image3d = True if seed_map.ndim == 3 else False
if not image3d:
seed_map = np.expand_dims(seed_map,0)
foreground = np.expand_dims(foreground,0)
for i in tqdm(range(seed_map.shape[0])):
if len(seed_morph_sequence) != 0:
for k, morph_function in enumerate(morph_funcs):
seed_map[i] = morph_function(seed_map[i], disk(radius=seed_morph_radius[k]))
if erode_and_dilate_foreground:
foreground[i] = binary_dilation(foreground[i], disk(radius=fore_erosion_radius))
foreground[i] = binary_erosion(foreground[i], disk(radius=fore_dilation_radius))
if not image3d:
seed_map = seed_map.squeeze()
foreground = foreground.squeeze()
if channels in ["BC", "BCM"]:
if ths['TYPE'] == "auto":
ths['TH_BINARY_MASK'] = threshold_otsu(data[...,0])
ths['TH_CONTOUR'] = threshold_otsu(data[...,1])
ths['TH_FOREGROUND'] = ths['TH_BINARY_MASK']/2
seed_map = (data[...,0] > ths['TH_BINARY_MASK']) * (data[...,1] < ths['TH_CONTOUR'])
foreground = (data[...,0] > ths['TH_FOREGROUND'])
if len(seed_morph_sequence) != 0 or erode_and_dilate_foreground:
erode_seed_and_foreground()
res = (1,)+resolution if len(resolution) == 2 else resolution
semantic = edt.edt(foreground, anisotropy=res, black_border=False, order='C')
seed_map = label(seed_map, connectivity=1)
elif channels in ["BP"]:
if ths['TYPE'] == "auto":
ths['TH_POINTS'] = threshold_otsu(data[...,1])
ths['TH_FOREGROUND'] = threshold_otsu(data[...,0])
seed_map = (data[...,1] > ths['TH_POINTS'])
foreground = (data[...,0] > ths['TH_FOREGROUND'])
print("Creating the central points . . .")
seed_map = label(seed_map, connectivity=1)
instances = np.unique(seed_map)[1:]
seed_coordinates = center_of_mass(seed_map, label(seed_map), instances)
seed_coordinates = np.round(seed_coordinates).astype(int)
if rmv_close_points:
seed_coordinates = remove_close_points(seed_coordinates, remove_close_points_radius, resolution,
ndim=seed_map.ndim)
seed_map = np.zeros(data.shape[:-1], dtype=np.uint8)
for sd in tqdm(seed_coordinates, total=len(seed_coordinates)):
z,y,x = sd
seed_map[z,y,x] = 1
res = (1,)+resolution if len(resolution) == 2 else resolution
semantic = -edt.edt(1 - seed_map, anisotropy=res, black_border=False, order='C')
if len(seed_morph_sequence) != 0 or erode_and_dilate_foreground:
erode_seed_and_foreground()
seed_map = label(seed_map, connectivity=1)
elif channels in ["BD"]:
semantic = data[...,0]
if ths['TYPE'] == "auto":
ths['TH_BINARY_MASK'] = threshold_otsu(data[...,0])
ths['TH_FOREGROUND'] = ths['TH_BINARY_MASK']/2
seed_map = (data[...,0] > ths['TH_BINARY_MASK']) * (data[...,1] < ths['TH_DISTANCE'])
foreground = (semantic > ths['TH_FOREGROUND'])
seed_map = label(seed_map, connectivity=1)
elif channels in ["BCD"]:
semantic = data[...,0]
if ths['TYPE'] == "auto":
ths['TH_BINARY_MASK'] = threshold_otsu(data[...,0])
ths['TH_CONTOUR'] = threshold_otsu(data[...,1])
ths['TH_FOREGROUND'] = ths['TH_BINARY_MASK']/2
seed_map = (data[...,0] > ths['TH_BINARY_MASK']) * (data[...,1] < ths['TH_CONTOUR']) * (data[...,2] < ths['TH_DISTANCE'])
foreground = (semantic > ths['TH_FOREGROUND'])
if len(seed_morph_sequence) != 0 or erode_and_dilate_foreground:
erode_seed_and_foreground()
seed_map = label(seed_map, connectivity=1)
else: # 'BCDv2', 'Dv2', 'BDv2'
semantic = data[...,-1]
foreground = None
if channels == "BCDv2": # 'BCDv2'
if ths['TYPE'] == "auto":
ths['TH_BINARY_MASK'] = threshold_otsu(data[...,0])
ths['TH_CONTOUR'] = threshold_otsu(data[...,1])
seed_map = (data[...,0] > ths['TH_BINARY_MASK']) * (data[...,1] < ths['TH_CONTOUR']) * (data[...,1] < ths['TH_DISTANCE'])
background_seed = binary_dilation( ((data[...,0]>ths['TH_BINARY_MASK']) + (data[...,1]>ths['TH_CONTOUR'])).astype(np.uint8), iterations=2)
seed_map, num = label(seed_map, connectivity=1, return_num=True)
# Create background seed and label correctly
background_seed = 1 - background_seed
background_seed[background_seed==1] = num+1
seed_map = seed_map + background_seed
del background_seed
elif channels == "BDv2": # 'BDv2'
if ths['TYPE'] == "auto":
ths['TH_BINARY_MASK'] = threshold_otsu(data[...,0])
seed_map = (data[...,0] > ths['TH_BINARY_MASK']) * (data[...,1] < ths['TH_DISTANCE'])
background_seed = binary_dilation((data[...,1]<ths['TH_DISTANCE']).astype(np.uint8), iterations=2)
seed_map = label(seed_map, connectivity=1)
background_seed = label(background_seed, connectivity=1)
props = regionprops_table(seed_map, properties=('area','centroid'))
for n in range(len(props['centroid-0'])):
label_center = [props['centroid-0'][n], props['centroid-1'][n], props['centroid-2'][n]]
instance_to_remove = background_seed[label_center]
background_seed[background_seed == instance_to_remove] = 0
seed_map = seed_map + background_seed
del background_seed
seed_map = label(seed_map, connectivity=1) # re-label again
elif channels == "Dv2": # 'Dv2'
seed_map = data[...,0] < ths['TH_DISTANCE']
seed_map = label(seed_map, connectivity=1)
if len(seed_morph_sequence) != 0:
erode_seed_and_foreground()
# Print the thresholds used in automatic case
if ths['TYPE'] == "auto":
print("Thresholds used: {}".format(ths))
if remove_before:
seed_map = remove_small_objects(seed_map, thres_small_before)
segm = watershed(-semantic, seed_map, mask=foreground)
# Choose appropiate dtype
max_value = np.max(segm)
if max_value < 255:
segm = segm.astype(np.uint8)
elif max_value < 65535:
segm = segm.astype(np.uint16)
else:
segm = segm.astype(np.uint32)
if save_dir is not None:
save_tif(np.expand_dims(np.expand_dims(seed_map,-1),0).astype(segm.dtype), save_dir, ["seed_map.tif"], verbose=False)
save_tif(np.expand_dims(np.expand_dims(semantic,-1),0).astype(np.float32), save_dir, ["semantic.tif"], verbose=False)
if channels in ["BC", "BCM", "BCD", "BP"]:
save_tif(np.expand_dims(np.expand_dims(foreground,-1),0).astype(np.uint8), save_dir, ["foreground.tif"], verbose=False)
return segm
def calculate_zy_filtering(data, mf_size=5):
"""Applies a median filtering in the z and y axes of the provided data.
Parameters
----------
data : 4D Numpy array
Data to apply the filter to. E.g. ``(num_of_images, y, x, channels)``.
mf_size : int, optional
Size of the median filter. Must be an odd number.
Returns
-------
Array : 4D Numpy array
Filtered data. E.g. ``(num_of_images, y, x, channels)``.
"""
out_data = np.copy(data)
# Must be odd
if mf_size % 2 == 0:
mf_size += 1
for i in range(data.shape[0]):
for c in range(data.shape[-1]):
sl = (data[i,...,c]).astype(np.float32)
sl = cv2.medianBlur(sl, mf_size)
out_data[i,...,c] = sl
return out_data
def calculate_z_filtering(data, mf_size=5):
"""Applies a median filtering in the z dimension of the provided data.
Parameters
----------
data : 4D Numpy array
Data to apply the filter to. E.g. ``(num_of_images, y, x, channels)``.
mf_size : int, optional
Size of the median filter. Must be an odd number.
Returns
-------
Array : 4D Numpy array
Filtered data. E.g. ``(num_of_images, y, x, channels)``.
"""
out_data = np.copy(data)
# Must be odd
if mf_size % 2 == 0:
mf_size += 1
for c in range(out_data.shape[-1]):
out_data[...,c] = median_filter(data[...,c], size=(mf_size,1,1,1))
return out_data
def ensemble8_2d_predictions(o_img, pred_func, batch_size_value=1, n_classes=1):
"""Outputs the mean prediction of a given image generating its 8 possible rotations and flips.
Parameters
----------
o_img : 3D Numpy array
Input image. E.g. ``(y, x, channels)``.
pred_func : function
Function to make predictions.
batch_size_value : int, optional
Batch size value.
n_classes : int, optional
Number of classes.
Returns
-------
out : 3D Numpy array
Output image ensembled. E.g. ``(y, x, channels)``.
Examples
--------
::
# EXAMPLE 1
# Apply ensemble to each image of X_test
X_test = np.ones((165, 768, 1024, 1))
out_X_test = np.zeros(X_test.shape, dtype=(np.float32))
for i in tqdm(range(X_test.shape[0])):
pred_ensembled = ensemble8_2d_predictions(X_test[i],
pred_func=(lambda img_batch_subdiv: model.predict(img_batch_subdiv)), n_classes=n_classes)
out_X_test[i] = pred_ensembled
# Notice that here pred_func is created based on model.predict function of Keras
"""
# Prepare all the image transformations per channel
total_img = []
for channel in range(o_img.shape[-1]):
aug_img = []
# Transformations per channel
_img = np.expand_dims(o_img[...,channel], -1)
# Convert into square image to make the rotations properly
pad_to_square = _img.shape[0] - _img.shape[1]
if pad_to_square < 0:
img = np.pad(_img, [(abs(pad_to_square), 0), (0, 0), (0, 0)], 'reflect')
else:
img = np.pad(_img, [(0, 0), (pad_to_square, 0), (0, 0)], 'reflect')
# Make 8 different combinations of the img
aug_img.append(img)
aug_img.append(np.rot90(img, axes=(0, 1), k=1))
aug_img.append(np.rot90(img, axes=(0, 1), k=2))
aug_img.append(np.rot90(img, axes=(0, 1), k=3))
aug_img.append(img[:, ::-1])
img_aux = img[:, ::-1]
aug_img.append(np.rot90(img_aux, axes=(0, 1), k=1))
aug_img.append(np.rot90(img_aux, axes=(0, 1), k=2))
aug_img.append(np.rot90(img_aux, axes=(0, 1), k=3))
aug_img = np.array(aug_img)
total_img.append(aug_img)
del aug_img, img_aux
# Merge channels
total_img = np.concatenate(total_img, -1)
# Make the prediction
_decoded_aug_img = []
l = int(math.ceil(total_img.shape[0]/batch_size_value))
for i in range(l):
top = (i+1)*batch_size_value if (i+1)*batch_size_value < total_img.shape[0] else total_img.shape[0]
with torch.cuda.amp.autocast():
r_aux = pred_func(total_img[i*batch_size_value:top])
# Take just the last output of the network in case it returns more than one output
if isinstance(r_aux, list):
r_aux = np.array(r_aux[-1])
if n_classes > 1:
r_aux = np.expand_dims(np.argmax(r_aux, -1), -1)
_decoded_aug_img.append(r_aux)
_decoded_aug_img = np.concatenate(_decoded_aug_img)
# Undo the combinations of the img
arr = []
for c in range(_decoded_aug_img.shape[-1]):
# Remove the last channel to make the transformations correctly
decoded_aug_img = _decoded_aug_img[...,c].astype(np.float32)
# Undo the combinations of the image
out_img = []
out_img.append(decoded_aug_img[0])
out_img.append(np.rot90(decoded_aug_img[1], axes=(0, 1), k=3))
out_img.append(np.rot90(decoded_aug_img[2], axes=(0, 1), k=2))
out_img.append(np.rot90(decoded_aug_img[3], axes=(0, 1), k=1))
out_img.append(decoded_aug_img[4][:, ::-1])
out_img.append(np.rot90(decoded_aug_img[5], axes=(0, 1), k=3)[:, ::-1])
out_img.append(np.rot90(decoded_aug_img[6], axes=(0, 1), k=2)[:, ::-1])
out_img.append(np.rot90(decoded_aug_img[7], axes=(0, 1), k=1)[:, ::-1])
out_img = np.array(out_img)
out_img = np.expand_dims(out_img, -1)
arr.append(out_img)
out_img = np.concatenate(arr, -1)
del decoded_aug_img, _decoded_aug_img, arr
if pad_to_square != 0:
if pad_to_square < 0:
out = np.zeros((out_img.shape[0], img.shape[0]+pad_to_square, img.shape[1], out_img.shape[-1]))
else:
out = np.zeros((out_img.shape[0], img.shape[0], img.shape[1]-pad_to_square, out_img.shape[-1]))
else:
out = np.zeros(out_img.shape)
# Undo the padding
for i in range(out_img.shape[0]):
if pad_to_square < 0:
out[i] = out_img[i,abs(pad_to_square):,:]
else:
out[i] = out_img[i,:,abs(pad_to_square):]
return np.mean(out, axis=0)
def ensemble16_3d_predictions(vol, pred_func, batch_size_value=1, n_classes=1):
"""Outputs the mean prediction of a given image generating its 16 possible rotations and flips.
Parameters
----------
o_img : 4D Numpy array
Input image. E.g. ``(z, y, x, channels)``.
pred_func : function
Function to make predictions.
batch_size_value : int, optional
Batch size value.
n_classes : int, optional
Number of classes.
Returns
-------
out : 4D Numpy array
Output image ensembled. E.g. ``(z, y, x, channels)``.
Examples
--------
::
# EXAMPLE 1
# Apply ensemble to each image of X_test
X_test = np.ones((10, 165, 768, 1024, 1))
out_X_test = np.zeros(X_test.shape, dtype=(np.float32))
for i in tqdm(range(X_test.shape[0])):
pred_ensembled = ensemble8_2d_predictions(X_test[i],
pred_func=(lambda img_batch_subdiv: model.predict(img_batch_subdiv)), n_classes=n_classes)
out_X_test[i] = pred_ensembled
# Notice that here pred_func is created based on model.predict function of Keras
"""
total_vol = []
for channel in range(vol.shape[-1]):
aug_vols = []
# Transformations per channel
_vol = vol[...,channel]
# Convert into square image to make the rotations properly
pad_to_square = _vol.shape[2] - _vol.shape[1]
if pad_to_square < 0:
volume = np.pad(_vol, [(0,0), (0,0), (abs(pad_to_square),0)], 'reflect')
else:
volume = np.pad(_vol, [(0,0), (pad_to_square,0), (0,0)], 'reflect')
# Make 16 different combinations of the volume
aug_vols.append(volume)
aug_vols.append(rotate(volume, mode='reflect', axes=(2, 1), angle=90, reshape=False))
aug_vols.append(rotate(volume, mode='reflect', axes=(2, 1), angle=180, reshape=False))
aug_vols.append(rotate(volume, mode='reflect', axes=(2, 1), angle=270, reshape=False))
volume_aux = np.flip(volume, 0)
aug_vols.append(volume_aux)
aug_vols.append(rotate(volume_aux, mode='reflect', axes=(2, 1), angle=90, reshape=False))
aug_vols.append(rotate(volume_aux, mode='reflect', axes=(2, 1), angle=180, reshape=False))
aug_vols.append(rotate(volume_aux, mode='reflect', axes=(2, 1), angle=270, reshape=False))
volume_aux = np.flip(volume, 1)
aug_vols.append(volume_aux)
aug_vols.append(rotate(volume_aux, mode='reflect', axes=(2, 1), angle=90, reshape=False))
aug_vols.append(rotate(volume_aux, mode='reflect', axes=(2, 1), angle=180, reshape=False))
aug_vols.append(rotate(volume_aux, mode='reflect', axes=(2, 1), angle=270, reshape=False))
volume_aux = np.flip(volume, 2)
aug_vols.append(volume_aux)
aug_vols.append(rotate(volume_aux, mode='reflect', axes=(2, 1), angle=90, reshape=False))
aug_vols.append(rotate(volume_aux, mode='reflect', axes=(2, 1), angle=180, reshape=False))
aug_vols.append(rotate(volume_aux, mode='reflect', axes=(2, 1), angle=270, reshape=False))
aug_vols = np.array(aug_vols)
# Add the last channel again
aug_vols = np.expand_dims(aug_vols, -1)
total_vol.append(aug_vols)
del aug_vols, volume_aux
# Merge channels
total_vol = np.concatenate(total_vol, -1)
_decoded_aug_vols = []
l = int(math.ceil(total_vol.shape[0]/batch_size_value))
for i in range(l):
top = (i+1)*batch_size_value if (i+1)*batch_size_value < total_vol.shape[0] else total_vol.shape[0]
with torch.cuda.amp.autocast():
r_aux = pred_func(total_vol[i*batch_size_value:top])
# Take just the last output of the network in case it returns more than one output
if isinstance(r_aux, list):
r_aux = np.array(r_aux[-1])
if n_classes > 1:
r_aux = np.expand_dims(np.argmax(r_aux, -1), -1)
if r_aux.ndim == 4:
r_aux = np.expand_dims(r_aux, 0)
_decoded_aug_vols.append(r_aux)
_decoded_aug_vols = np.concatenate(_decoded_aug_vols)
volume = np.expand_dims(volume, -1)
arr = []
for c in range(_decoded_aug_vols.shape[-1]):
# Remove the last channel to make the transformations correctly
decoded_aug_vols = _decoded_aug_vols[...,c].astype(np.float32)
# Undo the combinations of the volume
out_vols = []
out_vols.append(np.array(decoded_aug_vols[0]))
out_vols.append(rotate(np.array(decoded_aug_vols[1]), mode='reflect', axes=(2, 1), angle=-90, reshape=False))
out_vols.append(rotate(np.array(decoded_aug_vols[2]), mode='reflect', axes=(2, 1), angle=-180, reshape=False))
out_vols.append(rotate(np.array(decoded_aug_vols[3]), mode='reflect', axes=(2, 1), angle=-270, reshape=False))
out_vols.append(np.flip(np.array(decoded_aug_vols[4]), 0))
out_vols.append(np.flip(rotate(np.array(decoded_aug_vols[5]), mode='reflect', axes=(2, 1), angle=-90, reshape=False), 0))
out_vols.append(np.flip(rotate(np.array(decoded_aug_vols[6]), mode='reflect', axes=(2, 1), angle=-180, reshape=False), 0))
out_vols.append(np.flip(rotate(np.array(decoded_aug_vols[7]), mode='reflect', axes=(2, 1), angle=-270, reshape=False), 0))
out_vols.append(np.flip(np.array(decoded_aug_vols[8]), 1))
out_vols.append(np.flip(rotate(np.array(decoded_aug_vols[9]), mode='reflect', axes=(2, 1), angle=-90, reshape=False), 1))
out_vols.append(np.flip(rotate(np.array(decoded_aug_vols[10]), mode='reflect', axes=(2, 1), angle=-180, reshape=False), 1))
out_vols.append(np.flip(rotate(np.array(decoded_aug_vols[11]), mode='reflect', axes=(2, 1), angle=-270, reshape=False), 1))
out_vols.append(np.flip(np.array(decoded_aug_vols[12]), 2))
out_vols.append(np.flip(rotate(np.array(decoded_aug_vols[13]), mode='reflect', axes=(2, 1), angle=-90, reshape=False), 2))
out_vols.append(np.flip(rotate(np.array(decoded_aug_vols[14]), mode='reflect', axes=(2, 1), angle=-180, reshape=False), 2))
out_vols.append(np.flip(rotate(np.array(decoded_aug_vols[15]), mode='reflect', axes=(2, 1), angle=-270, reshape=False), 2))
out_vols = np.array(out_vols)
out_vols = np.expand_dims(out_vols, -1)
arr.append(out_vols)
out_vols = np.concatenate(arr, -1)
del decoded_aug_vols, _decoded_aug_vols, arr
# Create the output data
if pad_to_square != 0:
if pad_to_square < 0:
out = np.zeros((out_vols.shape[0], volume.shape[0], volume.shape[1], volume.shape[2]+pad_to_square, out_vols.shape[-1]))
else:
out = np.zeros((out_vols.shape[0], volume.shape[0], volume.shape[1]-pad_to_square, volume.shape[2], out_vols.shape[-1]))
else:
out = np.zeros(out_vols.shape)
# Undo the padding
for i in range(out_vols.shape[0]):
if pad_to_square < 0:
out[i] = out_vols[i,:,:,abs(pad_to_square):,:]
else:
out[i] = out_vols[i,:,abs(pad_to_square):,:,:]
return np.mean(out, axis=0)
def create_th_plot(ths, y_list, th_name="TH_BINARY_MASK", chart_dir=None, per_sample=True, ideal_value=None):
"""Create plots for threshold value calculation.
Parameters
----------
ths : List of floats
List of thresholds. It will be the ``x`` axis.
y_list : List of ints/floats
Values of ``y`` axis.
th_name : str, optional
Name of the threshold.
chart_dir : str, optional
Path where the charts are stored.
per_sample : bool, optional
Create the plot per list in ``y_list``.
ideal_value : int/float, optional
Value that should be the ideal optimum. It is going to be marked with a red line in the chart.
"""
assert th_name in ['TH_BINARY_MASK', 'TH_CONTOUR', 'TH_FOREGROUND', 'TH_DISTANCE', 'TH_DIST_FOREGROUND']
fig, ax = plt.subplots(figsize=(25,10))
ths = [str(i) for i in ths]
num_points=len(ths)
N = len(y_list)
colors = list(range(0,N))
c_labels = list("vol_"+str(i) for i in range(0,N))
if per_sample:
for i in range(N):
l = '_nolegend_' if i > 30 else c_labels[i]
ax.plot(ths, y_list[i], label=l, alpha=0.4)
# Shrink current axis by 20%
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
# Put a legend to the right of the current axis
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
else:
y_list = np.array(y_list)
y_mean = np.mean(y_list, axis=0)
y_std = np.std(y_list, axis=0)
ax.plot(ths, y_mean, label="sample (mean)")
plt.fill_between(ths, y_mean-y_std, y_mean+y_std, alpha=0.25)
if ideal_value is not None:
plt.axhline(ideal_value, color='r')
trans = transforms.blended_transform_factory(ax.get_yticklabels()[0].get_transform(), ax.transData)
ax.text(1.12,ideal_value, "Ideal (mean)", color="red", transform=trans, ha="right", va="center")
ax.legend(loc='center right')
# Set labels of x axis
plt.xticks(ths)
a = np.arange(num_points)
ax.xaxis.set_ticks(a)
ax.xaxis.set_ticklabels(ths)
plt.title('Threshold '+str(th_name))
plt.xlabel("Threshold")
if th_name == 'TH_FOREGROUND' or th_name == 'TH_DIST_FOREGROUND':
plt.ylabel("IoU")
else:
plt.ylabel("Number of objects")
p = "_per_validation_sample" if per_sample else ""
plt.savefig(os.path.join(chart_dir, str(th_name)+p+".svg"), format = 'svg', dpi=100)
plt.show()
def voronoi_on_mask(data, mask, th=0, verbose=False):
"""Apply Voronoi to the voxels not labeled yet marked by the mask. It is done using distances from the un-labeled
voxels to the cell perimeters.
Parameters
----------
data : 2D/3D Numpy array
Data to apply Voronoi. ``(y, x)`` for 2D or ``(z, y, x)`` for 3D.
E.g. ``(397, 1450, 2000)`` for 3D.
mask : 3D/4D Numpy array
Data mask to determine which points need to be proccessed. ``(z, y, x, channels)`` e.g.
``(397, 1450, 2000, 3)``.
th : float, optional
Threshold used to binarize the input. If th=0, otsu threshold is used.
thres_small : int, optional
Theshold to remove small objects created by the watershed.
verbose : bool, optional
To print saving information.
Returns
-------
data : 4D Numpy array
Image with Voronoi applied. ``(num_of_images, z, y, x)`` e.g. ``(1, 397, 1450, 2000)``
"""
if data.ndim != 2 and data.ndim != 3:
raise ValueError("Data must be 2/3 dimensional, provided {}".format(data.shape))
if mask.ndim != 3 and mask.ndim != 4:
raise ValueError("Data mask must be 3/4 dimensional, provided {}".format(mask.shape))
if mask.shape[-1] < 2:
raise ValueError("Mask needs to have two channels at least, received {}".format(mask.shape[-1]))
if verbose:
print("Applying Voronoi {}D . . .".format(data.ndim))
image3d = False if data.ndim != 2 else True
if image3d:
data = np.expand_dims(data,0)
mask = np.expand_dims(mask,0)
# Extract mask from prediction
if mask.shape[-1] == 3:
mask = mask[...,2]
else:
mask = mask[...,0]+mask[...,1]
mask_shape = np.shape(mask)
# Binarize
if th == 0:
thresh = threshold_otsu(mask)
else:
thresh = th
binaryMask = mask > thresh
# Close to fill holes
closedBinaryMask = morphology.closing(binaryMask, morphology.ball(radius=5)).astype(np.uint8)
voronoiCyst = data*closedBinaryMask
binaryVoronoiCyst = (voronoiCyst > 0)*1
binaryVoronoiCyst = binaryVoronoiCyst.astype('uint8')
# Cell Perimeter
erodedVoronoiCyst = morphology.binary_erosion(binaryVoronoiCyst, morphology.ball(radius=2))
cellPerimeter = binaryVoronoiCyst - erodedVoronoiCyst
# Define ids to fill where there is mask but no labels
idsToFill = np.argwhere((closedBinaryMask==1) & (data==0))
labelPerId = np.zeros(np.size(idsToFill))
idsPerim = np.argwhere(cellPerimeter==1)
labelsPerimIds = voronoiCyst[cellPerimeter==1]
# Generating voronoi
for nId in tqdm(range(1,len(idsToFill))):
distCoord = cdist([idsToFill[nId]], idsPerim)
idSeedMin = np.argwhere(distCoord==np.min(distCoord))
idSeedMin = idSeedMin[0][1]
labelPerId[nId] = labelsPerimIds[idSeedMin]
voronoiCyst[idsToFill[nId][0], idsToFill[nId][1], idsToFill[nId][2]] = labelsPerimIds[idSeedMin]
if image3d:
data = data[0]
mask = mask[0]
voronoiCyst = voronoiCyst[0]
return voronoiCyst
def remove_close_points(points, radius, resolution, classes=None, ndim=3, return_drops=False):
"""
Remove all points from ``point_list`` that are at a ``radius``
or less distance from each other.
Parameters
----------
points : ndarray of floats
List of 3D points. E.g. ``((0,0,0), (1,1,1)``.
radius : float
Radius from each point to decide what points to keep. E.g. ``10.0``.
resolution : ndarray of floats
Resolution of the data, in ``(z,y,x)`` to calibrate coordinates.
E.g. ``[30,8,8]``.
ndim : int, optional
Number of dimension of the data.
return_drops : bool, optional
Whether to return or not a list containing the positions of the points removed.
Returns
-------
new_point_list : List of floats
New list of points after removing those at a distance of ``radius``
or less from each other.
"""
print("Removing close points . . .")
print('Initial number of points: ' + str( len( points ) ) )
point_list = points.copy()
if classes is not None:
class_list = classes.copy()
# Resolution adjust
for i in range(len(point_list)):
point_list[i][0] = point_list[i][0]* resolution[0]
point_list[i][1] = point_list[i][1]* resolution[1]
if ndim == 3:
point_list[i][2] = point_list[i][2]* resolution[2]
mynumbers = [tuple(point) for point in point_list]
if len(mynumbers) == 0:
return []
tree = cKDTree(mynumbers) # build k-dimensional tree
pairs = tree.query_pairs( radius ) # find all pairs closer than radius
neighbors = {} # create dictionary of neighbors
for i,j in pairs: # iterate over all pairs
if i not in neighbors:
neighbors[i] = {j}
else:
neighbors[i].add(j)
if j not in neighbors:
neighbors[j] = {i}
else:
neighbors[j].add(i)
positions = [i for i in range(0, len( point_list ))]
keep = []
discard = set()
for node in positions:
if node not in discard: # if node already in discard set: skip