0
# Segmentation and Clustering
1
2
Streamline clustering, bundle segmentation, and white matter bundle extraction algorithms for organizing and analyzing tractography results. DIPY provides comprehensive tools for grouping similar streamlines and extracting anatomically meaningful fiber bundles.
3
4
## Capabilities
5
6
### QuickBundles Clustering
7
8
Fast streamline clustering algorithm using centroid-based similarity metrics.
9
10
```python { .api }
11
class QuickBundles:
12
"""Fast streamline clustering using centroid-based approach."""
13
def __init__(self, threshold, metric='average'):
14
"""
15
Initialize QuickBundles clustering.
16
17
Parameters:
18
threshold (float): distance threshold for clustering
19
metric (str): distance metric ('average', 'hausdorff', 'mdf')
20
"""
21
22
def cluster(self, streamlines):
23
"""
24
Cluster streamlines into bundles.
25
26
Parameters:
27
streamlines (list): streamlines to cluster
28
29
Returns:
30
ClusterMapCentroid: clustering results with centroids
31
"""
32
33
class ClusterMapCentroid:
34
"""Container for clustering results."""
35
@property
36
def centroids(self):
37
"""list: cluster centroid streamlines"""
38
39
@property
40
def clusters(self):
41
"""list: cluster assignments for each streamline"""
42
43
def __len__(self):
44
"""Number of clusters."""
45
46
def __getitem__(self, key):
47
"""Access individual clusters."""
48
```
49
50
### Bundle Shape Analysis
51
52
Advanced metrics for comparing bundle shapes and analyzing bundle properties.
53
54
```python { .api }
55
def bundle_shape_similarity(bundle1, bundle2, rng=None, clust_thr=5, threshold=5):
56
"""
57
Calculate shape similarity between two bundles.
58
59
Parameters:
60
bundle1 (list): first bundle streamlines
61
bundle2 (list): second bundle streamlines
62
rng (RandomState): random number generator
63
clust_thr (float): clustering threshold
64
threshold (float): shape similarity threshold
65
66
Returns:
67
tuple: (similarity_score, matched_pairs)
68
"""
69
70
def bundle_adjacency(dtracks0, dtracks1, threshold):
71
"""
72
Calculate adjacency between streamline bundles.
73
74
Parameters:
75
dtracks0 (list): first set of streamlines
76
dtracks1 (list): second set of streamlines
77
threshold (float): distance threshold
78
79
Returns:
80
array: adjacency matrix between bundles
81
"""
82
83
def length_similarity(bundle1, bundle2, alpha=0.5):
84
"""
85
Compare bundle length distributions.
86
87
Parameters:
88
bundle1 (list): first bundle
89
bundle2 (list): second bundle
90
alpha (float): length weighting factor
91
92
Returns:
93
float: length similarity score
94
"""
95
```
96
97
### RecoBundles Bundle Recognition
98
99
Automated recognition and extraction of anatomical bundles using atlas-based approaches.
100
101
```python { .api }
102
class RecoBundles:
103
"""Bundle recognition using streamline-based atlas."""
104
def __init__(self, streamlines_atlas, greater_than=50, less_than=1000,
105
cluster_map=None, clust_thr=15, nb_pts=20):
106
"""
107
Initialize RecoBundles recognition.
108
109
Parameters:
110
streamlines_atlas (list): atlas streamlines for each bundle
111
greater_than (int): minimum streamlines per bundle
112
less_than (int): maximum streamlines per bundle
113
cluster_map (ClusterMap): optional pre-computed clustering
114
clust_thr (float): clustering threshold
115
nb_pts (int): number of points for resampling
116
"""
117
118
def recognize(self, streamlines, model_bundle, model_clust_thr=1.25,
119
reduction_thr=10, reduction_distance='mdf', slr=True, slr_metric='symmetric'):
120
"""
121
Recognize bundle in target streamlines.
122
123
Parameters:
124
streamlines (list): target streamlines to search
125
model_bundle (list): model bundle for recognition
126
model_clust_thr (float): model clustering threshold
127
reduction_thr (float): streamline reduction threshold
128
reduction_distance (str): distance metric for reduction
129
slr (bool): use Streamline-based Linear Registration
130
slr_metric (str): SLR distance metric
131
132
Returns:
133
tuple: (recognized_bundle, bundle_labels)
134
"""
135
```
136
137
### Bundle Segmentation Metrics
138
139
Distance metrics and similarity measures for streamline comparison and segmentation.
140
141
```python { .api }
142
class AveragePointwiseEuclideanMetric:
143
"""Average pointwise Euclidean distance metric."""
144
def __init__(self):
145
"""Initialize metric."""
146
147
def distance(self, s1, s2):
148
"""Calculate distance between two streamlines."""
149
150
class MinimumAverageDirectFlipMetric:
151
"""Minimum average direct-flip distance metric."""
152
def __init__(self):
153
"""Initialize MDF metric."""
154
155
def distance(self, s1, s2):
156
"""Calculate MDF distance between streamlines."""
157
158
def set_number_of_points(streamlines, nb_points=20):
159
"""
160
Resample streamlines to fixed number of points.
161
162
Parameters:
163
streamlines (list): input streamlines
164
nb_points (int): target number of points
165
166
Returns:
167
list: resampled streamlines
168
"""
169
170
def length(streamlines):
171
"""
172
Calculate streamline lengths.
173
174
Parameters:
175
streamlines (list): input streamlines
176
177
Returns:
178
array: length of each streamline
179
"""
180
```
181
182
### Anatomical Bundle Atlas
183
184
Tools for working with anatomical bundle atlases and bundle-specific analysis.
185
186
```python { .api }
187
def read_bundles_2_subjects():
188
"""
189
Load example bundle data from 2 subjects.
190
191
Returns:
192
tuple: (bundles_subj1, bundles_subj2)
193
"""
194
195
def read_five_af_bundles():
196
"""
197
Load arcuate fasciculus bundles.
198
199
Returns:
200
tuple: bundle data and bundle names
201
"""
202
203
class BundleAnalysis:
204
"""Bundle-specific analysis tools."""
205
def __init__(self, bundles, bundle_names=None):
206
"""
207
Initialize bundle analysis.
208
209
Parameters:
210
bundles (list): list of bundles
211
bundle_names (list): names for each bundle
212
"""
213
214
def compute_bundle_stats(self):
215
"""Compute statistics for each bundle."""
216
217
def compare_bundles(self, other_bundles):
218
"""Compare with another set of bundles."""
219
```
220
221
### Usage Examples
222
223
```python
224
# QuickBundles clustering example
225
from dipy.segment.clustering import QuickBundles
226
from dipy.segment.metric import AveragePointwiseEuclideanMetric
227
from dipy.data import read_bundles_2_subjects
228
229
# Load example streamlines
230
bundle1, bundle2 = read_bundles_2_subjects()
231
streamlines = bundle1 + bundle2
232
233
# Perform clustering
234
feature = AveragePointwiseEuclideanMetric()
235
qb = QuickBundles(threshold=10.0, metric=feature)
236
clusters = qb.cluster(streamlines)
237
238
print(f"Number of clusters: {len(clusters)}")
239
print(f"Cluster sizes: {[len(cluster) for cluster in clusters]}")
240
241
# Access cluster centroids
242
centroids = clusters.centroids
243
largest_cluster = clusters[0] # Largest cluster
244
245
# Bundle recognition with RecoBundles
246
from dipy.segment.bundles import RecoBundles
247
from dipy.data import read_five_af_bundles
248
249
# Load atlas bundles
250
atlas_bundles, bundle_names = read_five_af_bundles()
251
252
# Initialize RecoBundles
253
rb = RecoBundles(atlas_bundles, greater_than=20, less_than=1000000)
254
255
# Recognize bundles in new data
256
recognized = rb.recognize(streamlines, atlas_bundles[0])
257
print(f"Recognized {len(recognized[0])} streamlines for bundle: {bundle_names[0]}")
258
259
# Bundle shape similarity
260
from dipy.segment.bundles import bundle_shape_similarity
261
262
similarity = bundle_shape_similarity(bundle1, bundle2)
263
print(f"Bundle shape similarity: {similarity[0]:.3f}")
264
265
# Streamline metrics
266
from dipy.segment.metric import length, set_number_of_points
267
268
# Calculate lengths
269
lengths = length(streamlines)
270
print(f"Mean streamline length: {lengths.mean():.2f} mm")
271
272
# Resample to fixed number of points
273
resampled = set_number_of_points(streamlines, nb_points=100)
274
print(f"Resampled to {len(resampled[0])} points per streamline")
275
```