-
Notifications
You must be signed in to change notification settings - Fork 53
/
segment.py
1870 lines (1610 loc) · 76.3 KB
/
segment.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
#!/usr/bin/env python
"""
Functions for segmenting a surface mesh.
Authors:
- Yrjo Hame, 2012 ([email protected])
- Arno Klein, 2012-2016 ([email protected]) http://binarybottle.com
Copyright 2016, Mindboggle team (http://mindboggle.info), Apache v2.0 License
"""
def propagate(points, faces, region, seeds, labels,
max_iters=500, tol=0.001, sigma=10, background_value=-1,
verbose=False):
"""
Propagate labels to segment a surface into contiguous regions,
starting from seed vertices.
Imports : mindboggle.guts.rebound
Parameters
----------
points : array (or list) of lists of three integers
coordinates for all vertices
faces : list of lists of three integers
indices to three vertices per face (indices start from zero)
region : list (or array) of integers
values > background_value: inclusion in a region for all vertices
seeds : numpy array of integers
seed numbers for all vertices
labels : numpy array of integers
label numbers for all vertices
max_iters : integer
maximum number of iterations to run graph-based learning algorithm
tol: float
threshold to assess convergence of the algorithm
sigma: float
gaussian kernel parameter
background_value : integer
background value
verbose : bool
print statements?
Returns
-------
segments : numpy array of integers
region numbers for all vertices
Examples
--------
>>> # Propagate labels between label boundary segments in a single fold:
>>> import numpy as np
>>> import mindboggle.guts.rebound as rb
>>> from mindboggle.guts.mesh import find_neighbors
>>> from mindboggle.guts.segment import extract_borders
>>> from mindboggle.guts.segment import propagate
>>> from mindboggle.mio.vtks import read_scalars, read_vtk
>>> from mindboggle.mio.labels import DKTprotocol
>>> from mindboggle.mio.fetch_data import prep_tests
>>> urls, fetch_data = prep_tests()
>>> label_file = fetch_data(urls['left_freesurfer_labels'], '', '.vtk')
>>> folds_file = fetch_data(urls['left_folds'], '', '.vtk')
>>> dkt = DKTprotocol()
>>> folds, name = read_scalars(folds_file, True, True)
>>> points, f1,f2, faces, labels, f3, npoints, f4 = read_vtk(label_file,
... True, True)
>>> neighbor_lists = find_neighbors(faces, npoints)
>>> background_value = -1
>>> # Limit number of folds to speed up the test:
>>> limit_folds = True
>>> if limit_folds:
... fold_numbers = [4, 7] #[4, 6]
... indices_fold = [i for i,x in enumerate(folds) if x in fold_numbers]
... i0 = [i for i,x in enumerate(folds) if x not in fold_numbers]
... folds[i0] = background_value
... else:
... indices_fold = range(len(values))
>>> # Extract the boundary for this fold:
>>> indices_borders, label_pairs, foo = extract_borders(indices_fold,
... labels, neighbor_lists, [], True)
>>> # Select boundary segments in the sulcus labeling protocol:
>>> seeds = background_value * np.ones(npoints)
>>> for ilist,label_pair_list in enumerate(dkt.sulcus_label_pair_lists):
... I = [x for i,x in enumerate(indices_borders)
... if np.sort(label_pairs[i]).tolist() in label_pair_list]
... seeds[I] = ilist
>>> verbose = False
>>> region = folds
>>> max_iters = 500
>>> tol = 0.001
>>> sigma = 10
>>> segments = propagate(points, faces, region, seeds, labels,
... max_iters, tol, sigma, background_value, verbose)
>>> np.unique(segments)[0:10]
array([-1., 3., 12., 22.])
>>> len_segments = [len(np.where(segments == x)[0])
... for x in np.unique(segments) if x != background_value]
>>> len_segments[0:10]
[1152, 388, 116]
Write results to vtk file and view (skip test):
>>> from mindboggle.mio.plots import plot_surfaces # doctest: +SKIP
>>> from mindboggle.mio.vtks import rewrite_scalars # doctest: +SKIP
>>> rewrite_scalars(label_file, 'propagate.vtk',
... segments, 'segments', folds, background_value) # doctest: +SKIP
>>> plot_surfaces('propagate.vtk') # doctest: +SKIP
"""
import numpy as np
from mindboggle.guts.mesh import keep_faces
import mindboggle.guts.kernels as kernels
import mindboggle.guts.rebound as rebound
# Make sure arguments are numpy arrays:
if not isinstance(seeds, np.ndarray):
seeds = np.array(seeds)
if not isinstance(labels, np.ndarray):
labels = np.array(labels)
if not isinstance(points, np.ndarray):
points = np.array(points)
if points.size and faces:
segments = background_value * np.ones(len(points))
indices_region = [i for i,x in enumerate(region)
if x != background_value]
if indices_region:
local_indices_region = background_value * np.ones(labels.shape)
local_indices_region[indices_region] = list(range(len(indices_region)))
if verbose:
n_sets = len(np.unique([x for x in seeds
if x != background_value]))
if n_sets == 1:
print('Segment {0} vertices from 1 set of seed vertices'.
format(len(indices_region)))
else:
print('Segment {0} vertices from {1} sets of seed '
'vertices'.format(len(indices_region), n_sets))
# Remove faces whose 3 vertices are not among specified indices:
refaces = keep_faces(faces, indices_region)
# Set up rebound Bounds class instance:
B = rebound.Bounds()
if refaces:
B.Faces = np.array(refaces)
B.Indices = local_indices_region
B.Points = points[indices_region]
B.Labels = labels[indices_region]
B.seed_labels = seeds[indices_region]
B.num_points = len(B.Points)
B.verbose = verbose
# Propagate seed IDs from seeds:
B.graph_based_learning(method='propagate_labels',
realign=False,
kernel=kernels.rbf_kernel,
sigma=sigma,
max_iters=max_iters,
tol=tol,
vis=False,
verbose=verbose)
# Assign maximum probability seed IDs to each point of region:
max_prob_labels = B.assign_max_prob_label(verbose=False)
# Return segment IDs in original vertex array:
segments[indices_region] = max_prob_labels
else:
if verbose:
print(" No faces")
else:
segments = []
return segments
def segment_regions(vertices_to_segment, neighbor_lists, min_region_size=1,
seed_lists=[], keep_seeding=False,
spread_within_labels=False, labels=[], label_lists=[],
values=[], max_steps='', background_value=-1, verbose=False):
"""
Segment vertices of surface into contiguous regions by seed growing,
starting from zero or more lists of seed vertices.
Parameters
----------
vertices_to_segment : list of integers
indices to mesh vertices to be segmented
neighbor_lists : list of lists of integers
each list contains indices to neighboring vertices for each vertex
min_region_size : integer
minimum size of segmented set of vertices
seed_lists : list of lists, or empty list
each list contains indices to seed vertices to segment vertices_to_segment
keep_seeding : bool
grow from new seeds even after all seed lists have fully grown
spread_within_labels : bool
grow seeds only by vertices with labels in the seed labels?
labels : list of integers (required only if spread_within_labels)
label numbers for all vertices
label_lists : list of lists of integers (required only if spread_within_labels)
List of unique labels for each seed list to grow into
(If empty, set to unique labels for each seed list)
values : list of floats (default empty)
values for all vertices for use in preferentially directed segmentation
(segment in direction of lower values)
max_steps : integer (or empty string for infinity)
maximum number of segmentation steps to take for each seed list
background_value : integer or float
background value
verbose : bool
print statements?
Returns
-------
segments : numpy array of integers
region numbers for all vertices
Examples
--------
>>> # Segment deep regions with or without seeds:
>>> import numpy as np
>>> from mindboggle.guts.segment import segment_regions
>>> from mindboggle.mio.vtks import read_vtk
>>> from mindboggle.guts.mesh import find_neighbors
>>> from mindboggle.mio.fetch_data import prep_tests
>>> background_value = -1
>>> urls, fetch_data = prep_tests()
>>> depth_file = fetch_data(urls['left_travel_depth'], '', '.vtk')
>>> f1,f2,f3, faces, depths, f4, npoints, t5 = read_vtk(depth_file,
... True, True)
>>> vertices_to_segment = np.where(depths > 0.50)[0].tolist() # (sped up)
>>> neighbor_lists = find_neighbors(faces, npoints)
Example 1: without seed lists
>>> segments = segment_regions(vertices_to_segment, neighbor_lists)
>>> len(np.unique(segments))
92
>>> len_segments = [len(np.where(segments == x)[0])
... for x in np.unique(segments) if x != background_value]
>>> len_segments[0:10]
[110928, 4, 1399, 1274, 5, 139, 255, 12, 5, 1686]
Write results to vtk file and view (skip test):
>>> from mindboggle.mio.plots import plot_surfaces # doctest: +SKIP
>>> from mindboggle.mio.vtks import rewrite_scalars # doctest: +SKIP
>>> rewrite_scalars(depth_file, 'segment_regions_no_seeds.vtk', segments,
... 'segments', [], -1) # doctest: +SKIP
>>> plot_surfaces('segment_regions_no_seeds.vtk') # doctest: +SKIP
Example 2: with seed lists
>>> from mindboggle.guts.segment import extract_borders
>>> from mindboggle.mio.vtks import read_scalars
>>> from mindboggle.mio.labels import DKTprotocol
>>> dkt = DKTprotocol()
>>> label_lists = [np.unique(np.ravel(x)) for x in dkt.sulcus_label_pair_lists]
>>> labels_file = fetch_data(urls['left_freesurfer_labels'], '', '.vtk')
>>> labels, name = read_scalars(labels_file)
>>> indices_borders, label_pairs, foo = extract_borders(vertices_to_segment,
... labels, neighbor_lists, ignore_values=[], return_label_pairs=True)
>>> seed_lists = []
>>> for label_pair_list in dkt.sulcus_label_pair_lists:
... seed_lists.append([x for i,x in enumerate(indices_borders)
... if np.sort(label_pairs[i]).tolist()
... in label_pair_list])
>>> keep_seeding = True
>>> spread_within_labels = True
>>> values = []
>>> max_steps = ''
>>> background_value = -1
>>> verbose = False
>>> segments = segment_regions(vertices_to_segment,
... neighbor_lists, 1, seed_lists, keep_seeding, spread_within_labels,
... labels, label_lists, values, max_steps, background_value, verbose)
>>> len(np.unique(segments))
122
>>> np.unique(segments)[0:10]
array([-1., 1., 3., 4., 5., 6., 7., 8., 9., 11.])
>>> len_segments = [len(np.where(segments == x)[0])
... for x in np.unique(segments) if x != background_value]
>>> len_segments[0:10]
[6962, 8033, 5965, 5598, 7412, 3636, 3070, 5244, 3972, 6144]
Write results to vtk file and view (skip test):
>>> from mindboggle.mio.plots import plot_surfaces # doctest: +SKIP
>>> from mindboggle.mio.vtks import rewrite_scalars # doctest: +SKIP
>>> rewrite_scalars(depth_file, 'segment_regions.vtk', segments,
... 'segments_from_seeds', [], -1) # doctest: +SKIP
>>> plot_surfaces('segment_regions.vtk') # doctest: +SKIP
"""
import numpy as np
verbose = False
# Make sure arguments are lists:
if isinstance(vertices_to_segment, np.ndarray):
vertices_to_segment = vertices_to_segment.tolist()
if isinstance(labels, np.ndarray):
labels = [int(x) for x in labels]
if isinstance(values, np.ndarray):
values = values.tolist()
# ------------------------------------------------------------------------
# If seed_lists is empty, select first vertex from vertices_to_segment
# (single vertex selection does not affect result -- see below*):
# ------------------------------------------------------------------------
if seed_lists:
select_single_seed = False
if verbose:
if len(seed_lists) == 1:
print(' Segment {0} vertices from seed vertices'.
format(len(vertices_to_segment)))
else:
print(' Segment {0} vertices from {1} sets of seed vertices'.
format(len(vertices_to_segment), len(seed_lists)))
else:
select_single_seed = True
seed_lists = [[vertices_to_segment[0]]]
if verbose:
print(' Segment {0} vertices from first vertex as initial seed'.
format(len(vertices_to_segment)))
# ------------------------------------------------------------------------
# Initialize variables, including the list of vertex indices for each region,
# vertex indices for all regions, and Boolean list indicating which regions
# are fully grown, number of segments, etc.:
# ------------------------------------------------------------------------
segments = background_value * np.ones(len(neighbor_lists))
region_lists = [[] for x in seed_lists]
all_regions = []
fully_grown = [False for x in seed_lists]
new_segment_index = 0
counter = 0
if isinstance(max_steps, str):
max_steps = np.Inf
# ------------------------------------------------------------------------
# If label_lists empty, set to unique labels for each seed list:
# ------------------------------------------------------------------------
if spread_within_labels:
if not len(label_lists):
label_lists = []
for seed_list in seed_lists:
seed_labels = np.unique([labels[x] for x in seed_list])
label_lists.append(seed_labels)
# ------------------------------------------------------------------------
# Loop until all of the seed lists have grown to their full extent:
# ------------------------------------------------------------------------
count = 0
while not all(fully_grown):
# Loop through seed lists over and over again:
for ilist, seed_list in enumerate(seed_lists):
# If seed list empty
if not len(seed_list):
fully_grown[ilist] = True
# If seed list not fully grown:
if not fully_grown[ilist]:
# Add seeds to region:
region_lists[ilist].extend(seed_list)
all_regions.extend(seed_list)
# Remove seeds from vertices to segment:
vertices_to_segment = list(frozenset(vertices_to_segment).
difference(seed_list))
if vertices_to_segment:
# Find neighbors of each seed with lower values than the seed:
if values:
neighbors = []
for seed in seed_list:
seed_neighbors = neighbor_lists[seed]
seed_neighbors = [x for x in seed_neighbors
if values[x] <= values[seed]]
if seed_neighbors:
neighbors.extend(seed_neighbors)
else:
# Find neighbors of seeds:
neighbors = []
[neighbors.extend(neighbor_lists[x]) for x in seed_list]
# Select neighbors that have not been previously selected
# and are among the vertices to segment:
seed_list = list(frozenset(neighbors).intersection(vertices_to_segment))
seed_list = list(frozenset(seed_list).difference(all_regions))
else:
seed_list = []
# If there are seeds remaining:
if seed_list and count < max_steps:
# Select neighbors with the same labels
# as the initial seed labels:
if spread_within_labels:
seed_list = [x for x in seed_list
if labels[x] in label_lists[ilist]]
# Continue growing seed list:
seed_lists[ilist] = seed_list
count += 1
# If there are no seeds remaining:
else:
# Stop growing seed list (see exception below):
fully_grown[ilist] = True
# If the region size is large enough:
size_region = len(region_lists[ilist])
if size_region >= min_region_size:
# Assign ID to segmented region and increment ID:
if select_single_seed:
new_segment_index = counter
counter += 1
else:
new_segment_index = ilist
segments[region_lists[ilist]] = new_segment_index
# Display current number and size of region:
if verbose and size_region > 1:
if len(seed_lists) == 1 and vertices_to_segment:
print(" {0} vertices remain".
format(len(vertices_to_segment)))
else:
print(" Region {0}: {1} vertices ({2} remain)".
format(int(new_segment_index), size_region,
len(vertices_to_segment)))
# If selecting a single seed, continue growing
# if there are more vertices to segment:
if select_single_seed and count < max_steps:
if len(vertices_to_segment) >= min_region_size:
fully_grown[0] = False
seed_lists[0] = [vertices_to_segment[0]]
region_lists[0] = []
# ------------------------------------------------------------------------
# Keep growing from new seeds even after all seed lists have fully grown:
# ------------------------------------------------------------------------
if keep_seeding and len(vertices_to_segment) >= min_region_size:
if verbose:
print(' Keep seeding to segment {0} remaining vertices'.
format(len(vertices_to_segment)))
# Select first unsegmented vertex as new seed:
seed_list = [vertices_to_segment[0]]
# Loop until the seed list has grown to its full extent:
new_segment_index = ilist + 1
region = []
while len(vertices_to_segment) >= min_region_size:
# Add seeds to region:
region.extend(seed_list)
all_regions.extend(seed_list)
# Remove seeds from vertices to segment:
vertices_to_segment = list(frozenset(vertices_to_segment).
difference(seed_list))
if vertices_to_segment:
# Identify neighbors of seeds:
neighbors = []
[neighbors.extend(neighbor_lists[x]) for x in seed_list]
# Select neighbors that have not been previously selected
# and are among the vertices to segment:
seed_list = list(frozenset(vertices_to_segment).intersection(neighbors))
seed_list = list(frozenset(seed_list).difference(all_regions))
else:
seed_list = []
# If there are no seeds remaining:
if not len(seed_list):
# If the region size is large enough:
size_region = len(region)
if size_region >= min_region_size:
# Assign ID to segmented region and increment ID:
segments[region] = new_segment_index
new_segment_index += 1
# Display current number and size of region:
if verbose and size_region > 1:
print(" {0} vertices remain".
format(len(vertices_to_segment)))
# Select first unsegmented vertex as new seed:
if len(vertices_to_segment) >= min_region_size:
seed_list = [vertices_to_segment[0]]
region = []
return segments
def segment_by_region(data, regions=[], surface_file='', save_file=False,
output_file='', background_value=-1, verbose=False):
"""
Segment data on one surface by regions on a corresponding surface.
For example use sulcus regions to segment fundus data.
Parameters
----------
data : list of integers
numbers for all vertices (including background_value)
regions : numpy array or list of integers
number for each vertex, used to filter and label data
surface_file : string (if save_file)
VTK file
save_file : bool
save output VTK file?
output_file : string
output VTK file
background_value : integer or float
background value
verbose : bool
print statements?
Returns
-------
segment_per_region : list of integers
region numbers for all vertices (or background_value)
n_segments : integer
number of segments
segment_per_region_file : string (if save_file)
output VTK file with region numbers for data vertices
Examples
--------
>>> # Segment fundus data by sulcus regions:
>>> import numpy as np
>>> from mindboggle.guts.segment import segment_by_region
>>> from mindboggle.mio.vtks import read_scalars
>>> from mindboggle.mio.fetch_data import prep_tests
>>> urls, fetch_data = prep_tests()
>>> fundus_file = fetch_data(urls['left_fundus_per_fold'], '', '.vtk')
>>> data, name = read_scalars(fundus_file, True, True)
>>> surface_file = fetch_data(urls['left_sulci'], '', '.vtk')
>>> regions, name = read_scalars(surface_file, True, True)
>>> save_file = True
>>> output_file = 'segment_by_region.vtk'
>>> background_value = -1
>>> verbose = False
>>> o1, o2, segment_per_region_file = segment_by_region(data, regions,
... surface_file, save_file, output_file, background_value, verbose)
>>> segment_numbers = [x for x in np.unique(o1) if x != background_value]
>>> lens = []
>>> for segment_number in segment_numbers:
... lens.append(len([x for x in o1 if x == segment_number]))
>>> lens[0:10]
[333, 229, 419, 251, 281, 380, 162, 137, 256, 29]
View result (skip test):
>>> from mindboggle.mio.plots import plot_surfaces
>>> plot_surfaces(segment_per_region_file) # doctest: +SKIP
"""
# Extract a skeleton to connect endpoints in a fold:
import os
import numpy as np
from mindboggle.mio.vtks import rewrite_scalars
if isinstance(regions, list):
regions = np.array(regions)
# ------------------------------------------------------------------------
# Segment data with overlapping regions:
# ------------------------------------------------------------------------
indices = [i for i,x in enumerate(data)
if x != background_value]
if indices and np.size(regions):
segment_per_region = background_value * np.ones(len(regions))
segment_per_region[indices] = regions[indices]
n_segments = len([x for x in np.unique(segment_per_region)
if x != background_value])
else:
segment_per_region = []
n_segments = 0
if n_segments == 1:
sdum = 'sulcus fundus'
else:
sdum = 'sulcus fundi'
if verbose:
print(' Segmented {0} {1}'.format(n_segments, sdum))
# ------------------------------------------------------------------------
# Return segments, number of segments, and file name:
# ------------------------------------------------------------------------
segment_per_region_file = None
if n_segments > 0:
segment_per_region = [int(x) for x in segment_per_region]
if save_file and os.path.exists(surface_file):
if output_file:
segment_per_region_file = output_file
else:
segment_per_region_file = os.path.join(os.getcwd(),
'segment_per_region.vtk')
# Do not filter faces/points by scalars when saving file:
rewrite_scalars(surface_file, segment_per_region_file,
segment_per_region, 'segment_per_region', [],
background_value)
if not os.path.exists(segment_per_region_file):
raise IOError(segment_per_region_file + " not found")
return segment_per_region, n_segments, segment_per_region_file
def segment_by_filling_borders(regions, neighbor_lists, background_value=-1,
verbose=False):
"""
Fill borders (contours) on a surface mesh
to segment vertices into contiguous regions.
Steps ::
1. Extract region borders (assumed to be closed contours)
2. Segment borders into separate, contiguous borders
3. For each boundary
4. Find the neighbors to either side of the boundary
5. Segment the neighbors into exterior and interior sets of neighbors
6. Find the interior (smaller) sets of neighbors
7. Fill the contours formed by the interior neighbors
Parameters
----------
regions : numpy array of integers
region numbers for all vertices
neighbor_lists : list of lists of integers
each list contains indices to neighboring vertices for each vertex
background_value : integer or float
background value
verbose : bool
print statements?
Returns
-------
segments : numpy array of integers
region numbers for all vertices
Examples
--------
>>> # Segment folds by extracting their borders and filling them in separately:
>>> import numpy as np
>>> from mindboggle.guts.segment import segment_by_filling_borders
>>> from mindboggle.guts.mesh import find_neighbors
>>> from mindboggle.mio.vtks import read_vtk
>>> from mindboggle.mio.fetch_data import prep_tests
>>> urls, fetch_data = prep_tests()
>>> depth_file = fetch_data(urls['left_travel_depth'], '', '.vtk')
>>> f1,f2,f3, faces, depths, f4, npoints, input_vtk = read_vtk(depth_file,
... True, True)
>>> background_value = -1
>>> regions = background_value * np.ones(npoints)
>>> regions[depths > 0.50] = 1
>>> neighbor_lists = find_neighbors(faces, npoints)
>>> verbose = False
>>> segments = segment_by_filling_borders(regions, neighbor_lists,
... background_value, verbose)
>>> len(np.unique(segments))
19
>>> len_segments = []
>>> for useg in np.unique(segments):
... len_segments.append(len(np.where(segments == useg)[0]))
>>> len_segments[0:10]
[19446, 8619, 13846, 23, 244, 101687, 16, 792, 210, 76]
Write results to vtk file and view (skip test):
>>> from mindboggle.mio.plots import plot_surfaces # doctest: +SKIP
>>> from mindboggle.mio.vtks import rewrite_scalars # doctest: +SKIP
>>> rewrite_scalars(depth_file, 'segment_by_filling_borders.vtk',
... segments, 'segments', [], -1) # doctest: +SKIP
>>> plot_surfaces('segment_by_filling_borders.vtk') # doctest: +SKIP
"""
import numpy as np
from mindboggle.guts.segment import extract_borders
from mindboggle.guts.segment import segment_regions
include_boundary = False
# Make sure arguments are numpy arrays
if not isinstance(regions, np.ndarray):
regions = np.array(regions)
if verbose:
print('Segment vertices using region borders')
# Extract region borders (assumed to be closed contours)
if verbose:
print(' Extract region borders (assumed to be closed contours)')
indices_borders, foo1, foo2 = extract_borders(list(range(len(regions))),
regions, neighbor_lists)
# Extract background
indices_background = list(frozenset(list(range(len(regions)))).
difference(indices_borders))
# Segment borders into separate, contiguous borders
if verbose:
print(' Segment borders into separate, contiguous borders')
borders = segment_regions(indices_borders, neighbor_lists, 1, [], False,
False, [], [], [], '', background_value,
verbose)
# For each boundary
unique_borders = [x for x in np.unique(borders) if x != background_value]
segments = background_value * np.ones(len(regions))
for boundary_number in unique_borders:
if verbose:
print(' Boundary {0} of {1}:'.format(int(boundary_number),
len(unique_borders)))
border_indices = [i for i,x in enumerate(borders)
if x == boundary_number]
# Find the neighbors to either side of the boundary
indices_neighbors = []
[indices_neighbors.extend(neighbor_lists[i]) for i in border_indices]
#indices_neighbors2 = indices_neighbors[:]
#[indices_neighbors2.extend(neighbor_lists[i]) for i in indices_neighbors]
indices_neighbors = list(frozenset(indices_neighbors).
difference(indices_borders))
# Segment the neighbors into exterior and interior sets of neighbors
if verbose:
print(' Segment the neighbors into exterior and interior sets '
'of neighbors')
neighbors = segment_regions(indices_neighbors, neighbor_lists, 1, [],
False, False, [], [], [], '',
background_value, verbose)
# Find the interior (smaller) sets of neighbors
if verbose:
print(' Find the interior (smaller) sets of neighbors')
seed_lists = []
unique_neighbors = [x for x in np.unique(neighbors)
if x != background_value]
max_neighbor = 0
max_len = 0
for ineighbor, neighbor in enumerate(unique_neighbors):
indices_neighbor = [i for i,x in enumerate(neighbors)
if x == neighbor]
seed_lists.append(indices_neighbor)
if len(indices_neighbor) > max_len:
max_len = len(indices_neighbor)
max_neighbor = ineighbor
seed_lists = [x for i,x in enumerate(seed_lists) if i != max_neighbor]
seed_list = []
[seed_list.extend(x) for x in seed_lists if len(x) > 2]
# Fill the contours formed by the interior neighbors
if verbose:
print(' Fill the contour formed by the interior neighbors')
vertices_to_segment = list(frozenset(indices_background).
difference(indices_borders))
segmented_regions = segment_regions(vertices_to_segment,
neighbor_lists, 1, [seed_list],
False, False, [], [], [], '',
background_value, verbose)
if include_boundary:
segmented_regions[border_indices] = 1
segments[segmented_regions != background_value] = boundary_number
return segments
def segment_rings(region, seeds, neighbor_lists, step=1, background_value=-1,
verbose=False):
"""
Iteratively segment a region of surface mesh as concentric segments.
Parameters
----------
region : list of integers
indices of region vertices to segment (such as a fold)
seeds : list of integers
indices of seed vertices
neighbor_lists : list of lists of integers
indices to neighboring vertices for each vertex
step : integer
number of segmentation steps before assessing segments
background_value : integer
background value
verbose : bool
print statements?
Returns
-------
segments : list of lists of integers
indices to vertices for each concentric segment
Examples
--------
>>> import numpy as np
>>> from mindboggle.mio.vtks import read_scalars
>>> from mindboggle.guts.mesh import find_neighbors_from_file
>>> from mindboggle.guts.segment import extract_borders
>>> from mindboggle.guts.segment import segment_rings
>>> from mindboggle.mio.fetch_data import prep_tests
>>> urls, fetch_data = prep_tests()
>>> vtk_file = fetch_data(urls['left_travel_depth'], '', '.vtk')
>>> folds_file = fetch_data(urls['left_folds'], '', '.vtk')
>>> values, name = read_scalars(vtk_file, True, True)
>>> neighbor_lists = find_neighbors_from_file(vtk_file)
>>> background_value = -1
>>> fold, name = read_scalars(folds_file)
>>> indices = [i for i,x in enumerate(fold) if x != background_value]
>>> # Initialize seeds with the boundary of thresholded indices:
>>> use_threshold = True
>>> if use_threshold:
... # Threshold at the median depth or within maximum values in boundary:
... threshold = np.median(values[indices]) #+ np.std(values[indices])
... indices_high = [x for x in indices if values[x] >= threshold]
... # Make sure threshold is within the maximum values of the boundary:
... B = np.ones(len(values))
... B[indices] = 2
... borders, foo1, foo2 = extract_borders(list(range(len(B))), B, neighbor_lists)
... borders = [x for x in borders if values[x] != background_value]
... if list(frozenset(indices_high).intersection(borders)):
... threshold = np.max(values[borders]) + np.std(values[borders])
... indices_high = [x for x in indices if values[x] >= threshold]
... # Extract threshold boundary vertices as seeds:
... B = background_value * np.ones(len(values))
... B[indices_high] = 2
... seeds, foo1, foo2 = extract_borders(list(range(len(values))), B, neighbor_lists)
... # Or initialize P with the maximum value point:
... else:
... seeds = [indices[np.argmax(values[indices])]]
... indices_high = []
>>> indices = list(frozenset(indices).difference(indices_high))
>>> indices = list(frozenset(indices).difference(seeds))
>>> step = 1
>>> verbose = False
>>> segments = segment_rings(indices, seeds, neighbor_lists, step,
... background_value, verbose)
>>> len(segments)
56
>>> [len(x) for x in segments][0:10]
[5540, 5849, 6138, 5997, 4883, 3021, 1809, 1165, 842, 661]
>>> segments[0][0:10]
[65539, 65540, 98308, 98316, 131112, 131121, 131122, 131171, 131175, 131185]
Write results to vtk file and view (skip test):
>>> from mindboggle.mio.plots import plot_surfaces # doctest: +SKIP
>>> from mindboggle.mio.vtks import read_scalars, rewrite_scalars # doctest: +SKIP
>>> S = background_value * np.ones(len(values)) # doctest: +SKIP
>>> for i, segment in enumerate(segments): S[segment] = i # doctest: +SKIP
>>> rewrite_scalars(vtk_file, 'segment_rings.vtk', S, 'segment_rings',
... [], -1) # doctest: +SKIP
>>> plot_surfaces('segment_rings.vtk') # doctest: +SKIP
"""
from mindboggle.guts.segment import segment_regions
segments = []
while seeds:
# Segment step-wise starting from seeds and through the region:
seeds_plus_new = segment_regions(region, neighbor_lists, 1, [seeds],
False, False, [], [], [],
step, background_value, verbose)
seeds_plus_new = [i for i,x in enumerate(seeds_plus_new)
if x != background_value]
# Store the new segment after removing the previous segment:
region = list(frozenset(region).difference(seeds))
seeds = list(frozenset(seeds_plus_new).difference(seeds))
if seeds:
# Add the new segment and remove it from the region:
segments.append(seeds)
region = list(frozenset(region).difference(seeds))
return segments
def watershed(depths, points, indices, neighbor_lists, min_size=1,
depth_factor=0.25, depth_ratio=0.1, tolerance=0.01, regrow=True,
background_value=-1, verbose=False):
"""
Segment surface vertices into contiguous regions by a watershed algorithm.
Segment surface mesh into contiguous "watershed basins"
by seed growing from an iterative selection of the deepest vertices.
Steps ::
1. Grow segments from an iterative selection of the deepest seeds.
2. Regrow segments from the resulting seeds, until each seed's
segment touches a boundary.
3. Use the segment() function to fill in the rest.
4. Merge segments if their seeds are too close to each other
or their depths are very different.
Note ::
Despite the above precautions, the order of seed selection in segment()
could possibly influence the resulting borders between adjoining
segments (vs. propagate(), which is slower and insensitive to depth,
but is not biased by seed order).
In the example below, white spots indicate incomplete segmentation.
Parameters
----------
depths : numpy array of floats
depth values for all vertices
points : list of lists of floats
each element is a list of 3-D coordinates of a vertex on a surface mesh
indices : list of integers
indices to mesh vertices to be segmented
min_size : index
the minimum number of vertices in a basin
neighbor_lists : list of lists of integers
each list contains indices to neighboring vertices for each vertex
depth_factor : float
factor to determine whether to merge two neighboring watershed catchment
basins -- they are merged if the Euclidean distance between their basin
seeds is less than this fraction of the maximum Euclidean distance
between points having minimum and maximum depths
depth_ratio : float
the minimum fraction of depth for a neighboring shallower
watershed catchment basin (otherwise merged with the deeper basin)
tolerance : float
tolerance for detecting differences in depth between vertices
regrow : bool
regrow segments from watershed seeds?
background_value : integer or float
background value
verbose : bool
print statements?
Returns
-------
segments : list of integers
region numbers for all vertices
seed_indices : list of integers
list of indices to seed vertices
Examples
--------
>>> # Perform watershed segmentation on the deeper portions of a surface:
>>> import numpy as np
>>> from mindboggle.guts.mesh import find_neighbors
>>> from mindboggle.guts.segment import watershed
>>> from mindboggle.mio.vtks import read_vtk
>>> from mindboggle.mio.fetch_data import prep_tests
>>> urls, fetch_data = prep_tests()
>>> depth_file = fetch_data(urls['left_travel_depth'], '', '.vtk')
>>> points, indices, f1, faces, depths, f2, npoints, f3 = read_vtk(depth_file,
... return_first=True, return_array=True)
>>> indices = np.where(depths > 0.01)[0] # high to speed up
>>> neighbor_lists = find_neighbors(faces, npoints)
>>> min_size = 50
>>> depth_factor = 0.25
>>> depth_ratio = 0.1
>>> tolerance = 0.01
>>> regrow = True
>>> background_value = -1
>>> verbose = False
>>> segments, seed_indices = watershed(depths, points,
... indices, neighbor_lists, min_size, depth_factor, depth_ratio,
... tolerance, regrow, background_value, verbose)
>>> len(np.unique(segments))
202
>>> len_segments = []
>>> for useg in np.unique(segments):
... len_segments.append(len(np.where(segments == useg)[0]))
>>> len_segments[0:10]
[2976, 4092, 597, 1338, 1419, 1200, 1641, 220, 1423, 182]
Write watershed segments and seeds to vtk file and view (skip test).
Note: white spots indicate incomplete segmentation:
>>> from mindboggle.mio.plots import plot_surfaces # doctest: +SKIP
>>> from mindboggle.mio.vtks import rewrite_scalars # doctest: +SKIP
>>> segments_array = np.array(segments)
>>> segments_array[seed_indices] = 1.5 * np.max(segments_array)
>>> rewrite_scalars(depth_file, 'watershed.vtk',
... segments_array, 'segments', [], -1) # doctest: +SKIP