segment
segment.benchmarks
segment.benchmarks.bench_quickbundles
segment.bundles
segment.clustering
segment.mask
segment.metric
segment.quickbundles
segment.threshold
segment.tissue
MDFpy
Metric
QB_New
QB_Old
BundleMinDistanceAsymmetricMetric
BundleMinDistanceMetric
BundleSumDistanceMatrixMetric
RecoBundles
StreamlineLinearRegistration
Streamlines
chain
ABCMeta
AveragePointwiseEuclideanMetric
Cluster
ClusterCentroid
ClusterMap
ClusterMapCentroid
Clustering
Identity
Metric
MinimumAverageDirectFlipMetric
QuickBundles
QuickBundlesX
ResampleFeature
TreeCluster
TreeClusterMap
ArcLengthFeature
AveragePointwiseEuclideanMetric
CenterOfMassFeature
CosineMetric
EuclideanMetric
Feature
IdentityFeature
Metric
MidpointFeature
MinimumAverageDirectFlipMetric
ResampleFeature
SumPointwiseEuclideanMetric
VectorOfEndpointsFeature
QuickBundles
ConstantObservationModel
IteratedConditionalModes
TissueClassifierHMRF
segment
segment.benchmarks.bench_quickbundles
Benchmarks for QuickBundles
Run all benchmarks with:
import dipy.segment as dipysegment
dipysegment.bench()
With Pytest, Run this benchmark with:
pytest svv c bench.ini /path/to/bench_quickbundles.py
MDFpy 


Metric 
Computes a distance between two sequential data.  
QB_New 
alias of dipy.segment.clustering.QuickBundles 

QB_Old 
alias of dipy.segment.quickbundles.QuickBundles 

assert_array_equal (x, y[, err_msg, verbose]) 
Raises an AssertionError if two array_like objects are not equal.  
assert_arrays_equal (arrays1, arrays2) 

assert_equal (actual, desired[, err_msg, verbose]) 
Raises an AssertionError if two objects are not equal.  
bench_quickbundles () 

get_fnames ([name]) 
provides filenames of some test datasets or other useful parametrisations  
measure (code_str[, times, label]) 
Return elapsed time for executing code in the namespace of the caller. 
segment.bundles
BundleMinDistanceAsymmetricMetric ([num_threads]) 
Asymmetric Bundlebased Minimum distance 
BundleMinDistanceMetric ([num_threads]) 
Bundlebased Minimum Distance aka BMD 
BundleSumDistanceMatrixMetric ([num_threads]) 
Bundlebased Sum Distance aka BMD 
RecoBundles (streamlines[, greater_than, …]) 
Methods 
StreamlineLinearRegistration ([metric, x0, …]) 
Methods 
Streamlines 
alias of nibabel.streamlines.array_sequence.ArraySequence 
chain 
chain(*iterables) –> chain object 
afq_profile (data, bundle[, affine, …]) 
Calculates a summarized profile of data for a bundle or tract along its length. 
apply_affine (aff, pts) 
Apply affine matrix aff to points pts 
ba_analysis (recognized_bundle, expert_bundle) 

bundle_adjacency (dtracks0, dtracks1, threshold) 
Find bundle adjacency between two given tracks/bundles 
bundles_distances_mam 
Calculate distances between list of tracks A and list of tracks B 
bundles_distances_mdf 
Calculate distances between list of tracks A and list of tracks B 
check_range (streamline, gt, lt) 

gaussian_weights (bundle[, n_points, …]) 
Calculate weights for each streamline/node in a bundle, based on a Mahalanobis distance from the core the bundle, at that node (mean, per default). 
length 
Euclidean length of streamlines 
mahalanobis (u, v, VI) 
Compute the Mahalanobis distance between two 1D arrays. 
nbytes (streamlines) 

orient_by_streamline (streamlines, standard) 
Orient a bundle of streamlines to a standard streamline. 
qbx_and_merge (streamlines, thresholds[, …]) 
Run QuickBundlesX and then run again on the centroids of the last layer 
select_random_set_of_streamlines (…[, rng]) 
Select a random set of streamlines 
set_number_of_points 
Change the number of points of streamlines 
time () 
Return the current time in seconds since the Epoch. 
values_from_volume (data, streamlines[, affine]) 
Extract values of a scalar/vector along each streamline from a volume. 
segment.clustering
ABCMeta 
Metaclass for defining Abstract Base Classes (ABCs).  
AveragePointwiseEuclideanMetric 
Computes the average of pointwise Euclidean distances between two sequential data.  
Cluster ([id, indices, refdata]) 
Provides functionalities for interacting with a cluster.  
ClusterCentroid (centroid[, id, indices, refdata]) 
Provides functionalities for interacting with a cluster.  
ClusterMap ([refdata]) 
Provides functionalities for interacting with clustering outputs.  
ClusterMapCentroid ([refdata]) 
Provides functionalities for interacting with clustering outputs that have centroids.  
Clustering 
Methods 

Identity 
Provides identity indexing functionality.  
Metric 
Computes a distance between two sequential data.  
MinimumAverageDirectFlipMetric 
Computes the MDF distance (minimum average directflip) between two sequential data.  
QuickBundles (threshold[, metric, …]) 
Clusters streamlines using QuickBundles [Garyfallidis12].  
QuickBundlesX (thresholds[, metric]) 
Clusters streamlines using QuickBundlesX.  
ResampleFeature 
Extracts features from a sequential datum.  
TreeCluster (threshold, centroid[, indices]) 


TreeClusterMap (root) 


abstractmethod (funcobj) 
A decorator indicating abstract methods.  
nbytes (streamlines) 

qbx_and_merge (streamlines, thresholds[, …]) 
Run QuickBundlesX and then run again on the centroids of the last layer  
set_number_of_points 
Change the number of points of streamlines  
time () 
Return the current time in seconds since the Epoch. 
segment.mask
applymask (vol, mask) 
Mask vol with mask. 
binary_dilation (input[, structure, …]) 
Multidimensional binary dilation with the given structuring element. 
bounding_box (vol) 
Compute the bounding box of nonzero intensity voxels in the volume. 
clean_cc_mask (mask) 
Cleans a segmentation of the corpus callosum so no random pixels are included. 
color_fa (fa, evecs) 
Color fractional anisotropy of diffusion tensor 
crop (vol, mins, maxs) 
Crops the input volume. 
fractional_anisotropy (evals[, axis]) 
Fractional anisotropy (FA) of a diffusion tensor. 
generate_binary_structure (rank, connectivity) 
Generate a binary structure for binary morphological operations. 
median_filter (input[, size, footprint, …]) 
Calculate a multidimensional median filter. 
median_otsu (input_volume[, median_radius, …]) 
Simple brain extraction tool method for images from DWI data. 
multi_median (input, median_radius, numpass) 
Applies median filter multiple times on input data. 
otsu (image[, nbins]) 
Return threshold value based on Otsu’s method. 
segment_from_cfa (tensor_fit, roi, threshold) 
Segment the cfa inside roi using the values from threshold as bounds. 
warn 
Issue a warning, or maybe ignore it or raise an exception. 
segment.metric
ArcLengthFeature 
Extracts features from a sequential datum. 
AveragePointwiseEuclideanMetric 
Computes the average of pointwise Euclidean distances between two sequential data. 
CenterOfMassFeature 
Extracts features from a sequential datum. 
CosineMetric 
Computes the cosine distance between two vectors. 
EuclideanMetric 
alias of dipy.segment.metricspeed.SumPointwiseEuclideanMetric 
Feature 
Extracts features from a sequential datum. 
IdentityFeature 
Extracts features from a sequential datum. 
Metric 
Computes a distance between two sequential data. 
MidpointFeature 
Extracts features from a sequential datum. 
MinimumAverageDirectFlipMetric 
Computes the MDF distance (minimum average directflip) between two sequential data. 
ResampleFeature 
Extracts features from a sequential datum. 
SumPointwiseEuclideanMetric 
Computes the sum of pointwise Euclidean distances between two sequential data. 
VectorOfEndpointsFeature 
Extracts features from a sequential datum. 
dist 
Computes a distance between datum1 and datum2. 
distance_matrix 
Computes the distance matrix between two lists of sequential data. 
mdf (s1, s2) 
Computes the MDF (Minimum average DirectFlip) distance [Garyfallidis12] between two streamlines. 
segment.quickbundles
QuickBundles (tracks[, dist_thr, pts]) 


bundles_distances_mdf 
Calculate distances between list of tracks A and list of tracks B  
downsample (xyz[, n_pols]) 
downsample for a specific number of points along the curve/track  
local_skeleton_clustering 
Efficient tractography clustering  
warn 
Issue a warning, or maybe ignore it or raise an exception. 
segment.threshold
otsu (image[, nbins]) 
Return threshold value based on Otsu’s method. 
upper_bound_by_percent (data[, percent]) 
Find the upper bound for visualization of medical images 
upper_bound_by_rate (data[, rate]) 
Adjusts upper intensity boundary using rates 
segment.tissue
ConstantObservationModel 
Observation model assuming that the intensity of each class is constant. 
IteratedConditionalModes 
Methods 
TissueClassifierHMRF ([save_history, verbose]) 
This class contains the methods for tissue classification using the Markov Random Fields modeling approach 
add_noise (signal, snr, S0[, noise_type]) 
Add noise of specified distribution to the signal from a single voxel. 
MDFpy
dipy.segment.benchmarks.bench_quickbundles.
MDFpy
Bases: dipy.segment.metricspeed.Metric
Attributes: 


Methods
are_compatible (shape1, shape2) 
Checks if features can be used by metric.dist based on their shape. 
dist (features1, features2) 
Computes a distance between two data points based on their features. 
are_compatible
(shape1, shape2)Checks if features can be used by metric.dist based on their shape.
Basically this method exists so we don’t have to do this check inside the metric.dist function (speedup).
Parameters: 


Returns: 

Metric
dipy.segment.benchmarks.bench_quickbundles.
Metric
Bases: object
Computes a distance between two sequential data.
A sequence of Ndimensional points is represented as a 2D array with shape (nb_points, nb_dimensions). A feature object can be specified in order to calculate the distance between extracted features, rather than directly between the sequential data.
Parameters: 


Notes
When subclassing Metric, one only needs to override the dist and are_compatible methods.
Attributes: 


Methods
are_compatible 
Checks if features can be used by metric.dist based on their shape. 
dist 
Computes a distance between two data points based on their features. 
are_compatible
()Checks if features can be used by metric.dist based on their shape.
Basically this method exists so we don’t have to do this check inside the metric.dist function (speedup).
Parameters: 


Returns: 

QB_New
dipy.segment.benchmarks.bench_quickbundles.
QB_New
alias of dipy.segment.clustering.QuickBundles
QB_Old
dipy.segment.benchmarks.bench_quickbundles.
assert_array_equal
(x, y, err_msg='', verbose=True)Raises an AssertionError if two array_like objects are not equal.
Given two array_like objects, check that the shape is equal and all elements of these objects are equal. An exception is raised at shape mismatch or conflicting values. In contrast to the standard usage in numpy, NaNs are compared like numbers, no assertion is raised if both objects have NaNs in the same positions.
The usual caution for verifying equality with floating point numbers is advised.
Parameters: 


Raises: 

See also
assert_allclose
assert_array_almost_equal_nulp
, assert_array_max_ulp
, assert_equal
Examples
The first assert does not raise an exception:
>>> np.testing.assert_array_equal([1.0,2.33333,np.nan],
... [np.exp(0),2.33333, np.nan])
Assert fails with numerical inprecision with floats:
>>> np.testing.assert_array_equal([1.0,np.pi,np.nan],
... [1, np.sqrt(np.pi)**2, np.nan])
...
<type 'exceptions.ValueError'>:
AssertionError:
Arrays are not equal
(mismatch 50.0%)
x: array([ 1. , 3.14159265, NaN])
y: array([ 1. , 3.14159265, NaN])
Use assert_allclose or one of the nulp (number of floating point values) functions for these cases instead:
>>> np.testing.assert_allclose([1.0,np.pi,np.nan],
... [1, np.sqrt(np.pi)**2, np.nan],
... rtol=1e10, atol=0)
dipy.segment.benchmarks.bench_quickbundles.
assert_equal
(actual, desired, err_msg='', verbose=True)Raises an AssertionError if two objects are not equal.
Given two objects (scalars, lists, tuples, dictionaries or numpy arrays), check that all elements of these objects are equal. An exception is raised at the first conflicting values.
Parameters: 


Raises: 

Examples
>>> np.testing.assert_equal([4,5], [4,6])
...
<type 'exceptions.AssertionError'>:
Items are not equal:
item=1
ACTUAL: 5
DESIRED: 6
dipy.segment.benchmarks.bench_quickbundles.
get_fnames
(name='small_64D')provides filenames of some test datasets or other useful parametrisations
Parameters: 


Returns: 

Examples
>>> import numpy as np
>>> from dipy.data import get_fnames
>>> fimg,fbvals,fbvecs=get_fnames('small_101D')
>>> bvals=np.loadtxt(fbvals)
>>> bvecs=np.loadtxt(fbvecs).T
>>> import nibabel as nib
>>> img=nib.load(fimg)
>>> data=img.get_data()
>>> data.shape == (6, 10, 10, 102)
True
>>> bvals.shape == (102,)
True
>>> bvecs.shape == (102, 3)
True
dipy.segment.benchmarks.bench_quickbundles.
measure
(code_str, times=1, label=None)Return elapsed time for executing code in the namespace of the caller.
The supplied code string is compiled with the Python builtin compile
.
The precision of the timing is 10 milliseconds. If the code will execute
fast on this timescale, it can be executed many times to get reasonable
timing accuracy.
Parameters: 


Returns: 

Examples
>>> etime = np.testing.measure('for i in range(1000): np.sqrt(i**2)',
... times=times)
>>> print("Time for a single execution : ", etime / times, "s")
Time for a single execution : 0.005 s
BundleMinDistanceAsymmetricMetric
dipy.segment.bundles.
BundleMinDistanceAsymmetricMetric
(num_threads=None)Bases: dipy.align.streamlinear.BundleMinDistanceMetric
Asymmetric Bundlebased Minimum distance
This is a cost function that can be used by the StreamlineLinearRegistration class.
Methods
distance (xopt) 
Distance calculated from this Metric 
setup (static, moving) 
Setup static and moving sets of streamlines 
__init__
(num_threads=None)An abstract class for the metric used for streamline registration
If the two sets of streamlines match exactly then method distance
of this object should be minimum.
Parameters: 


BundleMinDistanceMetric
dipy.segment.bundles.
BundleMinDistanceMetric
(num_threads=None)Bases: dipy.align.streamlinear.StreamlineDistanceMetric
Bundlebased Minimum Distance aka BMD
This is the cost function used by the StreamlineLinearRegistration
References
[Garyfallidis14]  Garyfallidis et al., “Direct nativespace fiber bundle alignment for group comparisons”, ISMRM, 2014. 
Methods
setup(static, moving)  
distance(xopt) 
__init__
(num_threads=None)An abstract class for the metric used for streamline registration
If the two sets of streamlines match exactly then method distance
of this object should be minimum.
Parameters: 


distance
(xopt)Distance calculated from this Metric
Parameters: 


setup
(static, moving)Setup static and moving sets of streamlines
Parameters: 


Notes
Call this after the object is initiated and before distance.
BundleSumDistanceMatrixMetric
dipy.segment.bundles.
BundleSumDistanceMatrixMetric
(num_threads=None)Bases: dipy.align.streamlinear.BundleMinDistanceMatrixMetric
Bundlebased Sum Distance aka BMD
This is a cost function that can be used by the StreamlineLinearRegistration class.
Notes
The difference with BundleMinDistanceMatrixMetric is that it uses uses the sum of the distance matrix and not the sum of mins.
Methods
setup(static, moving)  
distance(xopt) 
__init__
(num_threads=None)An abstract class for the metric used for streamline registration
If the two sets of streamlines match exactly then method distance
of this object should be minimum.
Parameters: 


RecoBundles
dipy.segment.bundles.
RecoBundles
(streamlines, greater_than=50, less_than=1000000, cluster_map=None, clust_thr=15, nb_pts=20, rng=None, verbose=True)Bases: object
Methods
evaluate_results (model_bundle, …) 
Comapare the similiarity between two given bundles, model bundle, and extracted bundle. 
recognize (model_bundle, model_clust_thr[, …]) 
Recognize the model_bundle in self.streamlines 
refine (model_bundle, pruned_streamlines, …) 
Refine and recognize the model_bundle in self.streamlines This method expects once pruned streamlines as input. 
__init__
(streamlines, greater_than=50, less_than=1000000, cluster_map=None, clust_thr=15, nb_pts=20, rng=None, verbose=True)Recognition of bundles
Extract bundles from a participants’ tractograms using model bundles segmented from a different subject or an atlas of bundles. See [Garyfallidis17] for the details.
Parameters: 


Notes
Make sure that before creating this class that the streamlines and the model bundles are roughly in the same space. Also default thresholds are assumed in RAS 1mm^3 space. You may want to adjust those if your streamlines are not in world coordinates.
References
[Garyfallidis17]  (1, 2) Garyfallidis et al. Recognition of white matter bundles using local and global streamlinebased registration and clustering, Neuroimage, 2017. 
evaluate_results
(model_bundle, pruned_streamlines, slr_select)Comapare the similiarity between two given bundles, model bundle, and extracted bundle.
Parameters: 


Returns: 

recognize
(model_bundle, model_clust_thr, reduction_thr=10, reduction_distance='mdf', slr=True, slr_num_threads=None, slr_metric=None, slr_x0=None, slr_bounds=None, slr_select=(400, 600), slr_method='LBFGSB', pruning_thr=5, pruning_distance='mdf')Recognize the model_bundle in self.streamlines
Parameters: 


Returns: 

References
[Garyfallidis17]  Garyfallidis et al. Recognition of white matter bundles using local and global streamlinebased registration and clustering, Neuroimage, 2017. 
refine
(model_bundle, pruned_streamlines, model_clust_thr, reduction_thr=14, reduction_distance='mdf', slr=True, slr_metric=None, slr_x0=None, slr_bounds=None, slr_select=(400, 600), slr_method='LBFGSB', pruning_thr=6, pruning_distance='mdf')Refine and recognize the model_bundle in self.streamlines This method expects once pruned streamlines as input. It refines the first ouput of recobundle by applying second local slr (optional), and second pruning. This method is useful when we are dealing with noisy data or when we want to extract small tracks from tractograms.
Parameters: 


Returns: 

References
[Garyfallidis17]  Garyfallidis et al. Recognition of white matter bundles using local and global streamlinebased registration and clustering, Neuroimage, 2017. 
StreamlineLinearRegistration
dipy.segment.bundles.
StreamlineLinearRegistration
(metric=None, x0='rigid', method='LBFGSB', bounds=None, verbose=False, options=None, evolution=False, num_threads=None)Bases: object
Methods
optimize (static, moving[, mat]) 
Find the minimum of the provided metric. 
__init__
(metric=None, x0='rigid', method='LBFGSB', bounds=None, verbose=False, options=None, evolution=False, num_threads=None)Linear registration of 2 sets of streamlines [Garyfallidis15].
Parameters: 


References
[Garyfallidis15]  (1, 2) Garyfallidis et al. “Robust and efficient linear registration of whitematter fascicles in the space of streamlines”, NeuroImage, 117, 124–140, 2015 
[Garyfallidis14]  Garyfallidis et al., “Direct nativespace fiber bundle alignment for group comparisons”, ISMRM, 2014. 
[Garyfallidis17]  Garyfallidis et al. Recognition of white matter bundles using local and global streamlinebased registration and clustering, Neuroimage, 2017. 
optimize
(static, moving, mat=None)Find the minimum of the provided metric.
Parameters: 


Returns: 

chain
dipy.segment.bundles.
chain
Bases: object
chain(*iterables) –> chain object
Return a chain object whose .__next__() method returns elements from the first iterable until it is exhausted, then elements from the next iterable, until all of the iterables are exhausted.
Methods
from_iterable 
chain.from_iterable(iterable) –> chain object 
dipy.segment.bundles.
afq_profile
(data, bundle, affine=None, n_points=100, orient_by=None, weights=None, **weights_kwarg)Calculates a summarized profile of data for a bundle or tract along its length.
Follows the approach outlined in [Yeatman2012].
Parameters: 


Returns: 

References
[Yeatman2012]  (1, 2) Yeatman, Jason D., Robert F. Dougherty, Nathaniel J. Myall, Brian A. Wandell, and Heidi M. Feldman. 2012. “Tract Profiles of White Matter Properties: Automating FiberTract Quantification” PloS One 7 (11): e49790. 
dipy.segment.bundles.
apply_affine
(aff, pts)Apply affine matrix aff to points pts
Returns result of application of aff to the right of pts. The coordinate dimension of pts should be the last.
For the 3D case, aff will be shape (4,4) and pts will have final axis length 3  maybe it will just be N by 3. The return value is the transformed points, in this case:
res = np.dot(aff[:3,:3], pts.T) + aff[:3,3:4]
transformed_pts = res.T
This routine is more general than 3D, in that aff can have any shape (N,N), and pts can have any shape, as long as the last dimension is for the coordinates, and is therefore length N1.
Parameters: 


Returns: 

Examples
>>> aff = np.array([[0,2,0,10],[3,0,0,11],[0,0,4,12],[0,0,0,1]])
>>> pts = np.array([[1,2,3],[2,3,4],[4,5,6],[6,7,8]])
>>> apply_affine(aff, pts)
array([[14, 14, 24],
[16, 17, 28],
[20, 23, 36],
[24, 29, 44]]...)
Just to show that in the simple 3D case, it is equivalent to:
>>> (np.dot(aff[:3,:3], pts.T) + aff[:3,3:4]).T
array([[14, 14, 24],
[16, 17, 28],
[20, 23, 36],
[24, 29, 44]]...)
But pts can be a more complicated shape:
>>> pts = pts.reshape((2,2,3))
>>> apply_affine(aff, pts)
array([[[14, 14, 24],
[16, 17, 28]],
[[20, 23, 36],
[24, 29, 44]]]...)
dipy.segment.bundles.
bundle_adjacency
(dtracks0, dtracks1, threshold)Find bundle adjacency between two given tracks/bundles
Parameters: 


dipy.segment.bundles.
bundles_distances_mam
()Calculate distances between list of tracks A and list of tracks B
Parameters: 


Returns: 

dipy.segment.bundles.
bundles_distances_mdf
()Calculate distances between list of tracks A and list of tracks B
All tracks need to have the same number of points
Parameters: 


Returns: 

See also
dipy.metrics.downsample
dipy.segment.bundles.
gaussian_weights
(bundle, n_points=100, return_mahalnobis=False, stat=<function mean>)Calculate weights for each streamline/node in a bundle, based on a Mahalanobis distance from the core the bundle, at that node (mean, per default).
Parameters: 


Returns: 

dipy.segment.bundles.
length
()Euclidean length of streamlines
Length is in mm only if streamlines are expressed in world coordinates.
Parameters: 


Returns: 

Examples
>>> from dipy.tracking.streamline import length
>>> import numpy as np
>>> streamline = np.array([[1, 1, 1], [2, 3, 4], [0, 0, 0]])
>>> expected_length = np.sqrt([1+2**2+3**2, 2**2+3**2+4**2]).sum()
>>> length(streamline) == expected_length
True
>>> streamlines = [streamline, np.vstack([streamline, streamline[::1]])]
>>> expected_lengths = [expected_length, 2*expected_length]
>>> lengths = [length(streamlines[0]), length(streamlines[1])]
>>> np.allclose(lengths, expected_lengths)
True
>>> length([])
0.0
>>> length(np.array([[1, 2, 3]]))
0.0
dipy.segment.bundles.
mahalanobis
(u, v, VI)Compute the Mahalanobis distance between two 1D arrays.
The Mahalanobis distance between 1D arrays u and v, is defined as
where V
is the covariance matrix. Note that the argument VI
is the inverse of V
.
Parameters: 


Returns: 

Examples
>>> from scipy.spatial import distance
>>> iv = [[1, 0.5, 0.5], [0.5, 1, 0.5], [0.5, 0.5, 1]]
>>> distance.mahalanobis([1, 0, 0], [0, 1, 0], iv)
1.0
>>> distance.mahalanobis([0, 2, 0], [0, 1, 0], iv)
1.0
>>> distance.mahalanobis([2, 0, 0], [0, 1, 0], iv)
1.7320508075688772
dipy.segment.bundles.
orient_by_streamline
(streamlines, standard, n_points=12, in_place=False, as_generator=False, affine=None)Orient a bundle of streamlines to a standard streamline.
Parameters: 


Returns: 

dipy.segment.bundles.
qbx_and_merge
(streamlines, thresholds, nb_pts=20, select_randomly=None, rng=None, verbose=True)Run QuickBundlesX and then run again on the centroids of the last layer
Running again QuickBundles at a layer has the effect of merging some of the clusters that maybe originally devided because of branching. This function help obtain a result at a QuickBundles quality but with QuickBundlesX speed. The merging phase has low cost because it is applied only on the centroids rather than the entire dataset.
Parameters: 


Returns: 

References
[Garyfallidis12]  Garyfallidis E. et al., QuickBundles a method for tractography simplification, Frontiers in Neuroscience, vol 6, no 175, 2012. 
[Garyfallidis16]  Garyfallidis E. et al. QuickBundlesX: Sequential clustering of millions of streamlines in multiple levels of detail at record execution time. Proceedings of the, International Society of Magnetic Resonance in Medicine (ISMRM). Singapore, 4187, 2016. 
dipy.segment.bundles.
select_random_set_of_streamlines
(streamlines, select, rng=None)Select a random set of streamlines
Parameters: 


Returns: 

Notes
The same streamline will not be selected twice.
dipy.segment.bundles.
set_number_of_points
()Change the number of points of streamlines in order to obtain nb_points1 segments of equal length. Points of streamlines will be modified along the curve.
Parameters: 


Returns: 

Examples
>>> from dipy.tracking.streamline import set_number_of_points
>>> import numpy as np
One streamline, a semicircle:
>>> theta = np.pi*np.linspace(0, 1, 100)
>>> x = np.cos(theta)
>>> y = np.sin(theta)
>>> z = 0 * x
>>> streamline = np.vstack((x, y, z)).T
>>> modified_streamline = set_number_of_points(streamline, 3)
>>> len(modified_streamline)
3
Multiple streamlines:
>>> streamlines = [streamline, streamline[::2]]
>>> new_streamlines = set_number_of_points(streamlines, 10)
>>> [len(s) for s in streamlines]
[100, 50]
>>> [len(s) for s in new_streamlines]
[10, 10]
dipy.segment.bundles.
values_from_volume
(data, streamlines, affine=None)Extract values of a scalar/vector along each streamline from a volume.
Parameters: 


Notes
Values are extracted from the image based on the 3D coordinates of the nodes that comprise the points in the streamline, without any interpolation into segments between the nodes. Using this function with streamlines that have been resampled into a very small number of nodes will result in very few values.
ABCMeta
dipy.segment.clustering.
ABCMeta
Bases: type
Metaclass for defining Abstract Base Classes (ABCs).
Use this metaclass to create an ABC. An ABC can be subclassed directly, and then acts as a mixin class. You can also register unrelated concrete classes (even builtin classes) and unrelated ABCs as ‘virtual subclasses’ – these and their descendants will be considered subclasses of the registering ABC by the builtin issubclass() function, but the registering ABC won’t show up in their MRO (Method Resolution Order) nor will method implementations defined by the registering ABC be callable (not even via super()).
Methods
__call__ ($self, /, *args, **kwargs) 
Call self as a function. 
mro () 
return a type’s method resolution order 
register (subclass) 
Register a virtual subclass of an ABC. 
AveragePointwiseEuclideanMetric
dipy.segment.clustering.
AveragePointwiseEuclideanMetric
Bases: dipy.segment.metricspeed.SumPointwiseEuclideanMetric
Computes the average of pointwise Euclidean distances between two sequential data.
A sequence of Ndimensional points is represented as a 2D array with shape (nb_points, nb_dimensions). A feature object can be specified in order to calculate the distance between the features, rather than directly between the sequential data.
Parameters: 


Notes
The distance between two 2D sequential data:
s1 s2
0* a *0
\ 
\ 
1* 
 b *1
 \
2* \
c *2
is equal to \((a+b+c)/3\) where \(a\) is the Euclidean distance between s1[0] and s2[0], \(b\) between s1[1] and s2[1] and \(c\) between s1[2] and s2[2].
Attributes: 


Methods
are_compatible 
Checks if features can be used by metric.dist based on their shape. 
dist 
Computes a distance between two data points based on their features. 
Cluster
dipy.segment.clustering.
Cluster
(id=0, indices=None, refdata=<dipy.segment.clustering.Identity object>)Bases: object
Provides functionalities for interacting with a cluster.
Useful container to retrieve index of elements grouped together. If a reference to the data is provided to cluster_map, elements will be returned instead of their index when possible.
Parameters: 


Notes
A cluster does not contain actual data but instead knows how to retrieve them using its ClusterMap object.
Methods
assign (*indices) 
Assigns indices to this cluster. 
ClusterCentroid
dipy.segment.clustering.
ClusterCentroid
(centroid, id=0, indices=None, refdata=<dipy.segment.clustering.Identity object>)Bases: dipy.segment.clustering.Cluster
Provides functionalities for interacting with a cluster.
Useful container to retrieve the indices of elements grouped together and the cluster’s centroid. If a reference to the data is provided to cluster_map, elements will be returned instead of their index when possible.
Parameters: 


Notes
A cluster does not contain actual data but instead knows how to retrieve them using its ClusterMapCentroid object.
Methods
assign (id_datum, features) 
Assigns a data point to this cluster. 
update () 
Update centroid of this cluster. 
__init__
(centroid, id=0, indices=None, refdata=<dipy.segment.clustering.Identity object>)Initialize self. See help(type(self)) for accurate signature.
ClusterMap
dipy.segment.clustering.
ClusterMap
(refdata=<dipy.segment.clustering.Identity object>)Bases: object
Provides functionalities for interacting with clustering outputs.
Useful container to create, remove, retrieve and filter clusters. If refdata is given, elements will be returned instead of their index when using Cluster objects.
Parameters: 


Attributes: 

Methods
add_cluster (*clusters) 
Adds one or multiple clusters to this cluster map. 
clear () 
Remove all clusters from this cluster map. 
clusters_sizes () 
Gets the size of every cluster contained in this cluster map. 
get_large_clusters (min_size) 
Gets clusters which contains at least min_size elements. 
get_small_clusters (max_size) 
Gets clusters which contains at most max_size elements. 
remove_cluster (*clusters) 
Remove one or multiple clusters from this cluster map. 
size () 
Gets number of clusters contained in this cluster map. 
__init__
(refdata=<dipy.segment.clustering.Identity object>)Initialize self. See help(type(self)) for accurate signature.
add_cluster
(*clusters)Adds one or multiple clusters to this cluster map.
Parameters: 


clusters_sizes
()Gets the size of every cluster contained in this cluster map.
Returns: 


get_large_clusters
(min_size)Gets clusters which contains at least min_size elements.
Parameters: 


Returns: 

get_small_clusters
(max_size)Gets clusters which contains at most max_size elements.
Parameters: 


Returns: 

ClusterMapCentroid
dipy.segment.clustering.
ClusterMapCentroid
(refdata=<dipy.segment.clustering.Identity object>)Bases: dipy.segment.clustering.ClusterMap
Provides functionalities for interacting with clustering outputs that have centroids.
Allows to retrieve easely the centroid of every cluster. Also, it is a useful container to create, remove, retrieve and filter clusters. If refdata is given, elements will be returned instead of their index when using ClusterCentroid objects.
Parameters: 


Attributes: 

Methods
add_cluster (*clusters) 
Adds one or multiple clusters to this cluster map. 
clear () 
Remove all clusters from this cluster map. 
clusters_sizes () 
Gets the size of every cluster contained in this cluster map. 
get_large_clusters (min_size) 
Gets clusters which contains at least min_size elements. 
get_small_clusters (max_size) 
Gets clusters which contains at most max_size elements. 
remove_cluster (*clusters) 
Remove one or multiple clusters from this cluster map. 
size () 
Gets number of clusters contained in this cluster map. 
Clustering
dipy.segment.clustering.
Clustering
Bases: object
Methods
cluster (data[, ordering]) 
Clusters data. 
cluster
(data, ordering=None)Clusters data.
Subclasses will perform their clustering algorithm here.
Parameters: 


Returns: 

Identity
dipy.segment.clustering.
Identity
Bases: object
Provides identity indexing functionality.
This can replace any class supporting indexing used for referencing (e.g. list, tuple). Indexing an instance of this class will return the index provided instead of the element. It does not support slicing.
Metric
dipy.segment.clustering.
Metric
Bases: object
Computes a distance between two sequential data.
A sequence of Ndimensional points is represented as a 2D array with shape (nb_points, nb_dimensions). A feature object can be specified in order to calculate the distance between extracted features, rather than directly between the sequential data.
Parameters: 


Notes
When subclassing Metric, one only needs to override the dist and are_compatible methods.
Attributes: 


Methods
are_compatible 
Checks if features can be used by metric.dist based on their shape. 
dist 
Computes a distance between two data points based on their features. 
are_compatible
()Checks if features can be used by metric.dist based on their shape.
Basically this method exists so we don’t have to do this check inside the metric.dist function (speedup).
Parameters: 


Returns: 

MinimumAverageDirectFlipMetric
dipy.segment.clustering.
MinimumAverageDirectFlipMetric
Bases: dipy.segment.metricspeed.AveragePointwiseEuclideanMetric
Computes the MDF distance (minimum average directflip) between two sequential data.
A sequence of Ndimensional points is represented as a 2D array with shape (nb_points, nb_dimensions).
Notes
The distance between two 2D sequential data:
s1 s2
0* a *0
\ 
\ 
1* 
 b *1
 \
2* \
c *2
is equal to \(\min((a+b+c)/3, (a'+b'+c')/3)\) where \(a\) is the Euclidean distance between s1[0] and s2[0], \(b\) between s1[1] and s2[1], \(c\) between s1[2] and s2[2], \(a'\) between s1[0] and s2[2], \(b'\) between s1[1] and s2[1] and \(c'\) between s1[2] and s2[0].
Attributes: 


Methods
are_compatible 
Checks if features can be used by metric.dist based on their shape. 
dist 
Computes a distance between two data points based on their features. 
QuickBundles
dipy.segment.clustering.
QuickBundles
(threshold, metric='MDF_12points', max_nb_clusters=2147483647)Bases: dipy.segment.clustering.Clustering
Clusters streamlines using QuickBundles [Garyfallidis12].
Given a list of streamlines, the QuickBundles algorithm sequentially assigns each streamline to its closest bundle in \(\mathcal{O}(Nk)\) where \(N\) is the number of streamlines and \(k\) is the final number of bundles. If for a given streamline its closest bundle is farther than threshold, a new bundle is created and the streamline is assigned to it except if the number of bundles has already exceeded max_nb_clusters.
Parameters: 


References
[Garyfallidis12]  (1, 2, 3, 4) Garyfallidis E. et al., QuickBundles a method for tractography simplification, Frontiers in Neuroscience, vol 6, no 175, 2012. 
Examples
>>> from dipy.segment.clustering import QuickBundles
>>> from dipy.data import get_fnames
>>> from nibabel import trackvis as tv
>>> streams, hdr = tv.read(get_fnames('fornix'))
>>> streamlines = [i[0] for i in streams]
>>> # Segment fornix with a treshold of 10mm and streamlines resampled
>>> # to 12 points.
>>> qb = QuickBundles(threshold=10.)
>>> clusters = qb.cluster(streamlines)
>>> len(clusters)
4
>>> list(map(len, clusters))
[61, 191, 47, 1]
>>> # Resampling streamlines differently is done explicitly as follows.
>>> # Note this has an impact on the speed and the accuracy (tradeoff).
>>> from dipy.segment.metric import ResampleFeature
>>> from dipy.segment.metric import AveragePointwiseEuclideanMetric
>>> feature = ResampleFeature(nb_points=2)
>>> metric = AveragePointwiseEuclideanMetric(feature)
>>> qb = QuickBundles(threshold=10., metric=metric)
>>> clusters = qb.cluster(streamlines)
>>> len(clusters)
4
>>> list(map(len, clusters))
[58, 142, 72, 28]
Methods
cluster (streamlines[, ordering]) 
Clusters streamlines into bundles. 
__init__
(threshold, metric='MDF_12points', max_nb_clusters=2147483647)Initialize self. See help(type(self)) for accurate signature.
cluster
(streamlines, ordering=None)Clusters streamlines into bundles.
Performs quickbundles algorithm using predefined metric and threshold.
Parameters: 


Returns: 

QuickBundlesX
dipy.segment.clustering.
QuickBundlesX
(thresholds, metric='MDF_12points')Bases: dipy.segment.clustering.Clustering
Clusters streamlines using QuickBundlesX.
Parameters: 


References
[Garyfallidis12]  (1, 2) Garyfallidis E. et al., QuickBundles a method for tractography simplification, Frontiers in Neuroscience, vol 6, no 175, 2012. 
[Garyfallidis16]  Garyfallidis E. et al. QuickBundlesX: Sequential clustering of millions of streamlines in multiple levels of detail at record execution time. Proceedings of the, International Society of Magnetic Resonance in Medicine (ISMRM). Singapore, 4187, 2016. 
Methods
cluster (streamlines[, ordering]) 
Clusters streamlines into bundles. 
__init__
(thresholds, metric='MDF_12points')Initialize self. See help(type(self)) for accurate signature.
cluster
(streamlines, ordering=None)Clusters streamlines into bundles.
Performs QuickbundleX using a predefined metric and thresholds.
Parameters: 


Returns: 

ResampleFeature
dipy.segment.clustering.
ResampleFeature
Bases: dipy.segment.featurespeed.CythonFeature
Extracts features from a sequential datum.
A sequence of Ndimensional points is represented as a 2D array with shape (nb_points, nb_dimensions).
The features being extracted are the points of the sequence once resampled. This is useful for metrics requiring a constant number of points for all
streamlines.
Attributes: 


Methods
extract 
Extracts features from a sequential datum. 
infer_shape 
Infers the shape of features extracted from a sequential datum. 
TreeCluster
dipy.segment.clustering.
TreeCluster
(threshold, centroid, indices=None)Bases: dipy.segment.clustering.ClusterCentroid
Attributes: 


Methods
assign (id_datum, features) 
Assigns a data point to this cluster. 
update () 
Update centroid of this cluster. 
add 
TreeClusterMap
dipy.segment.clustering.
TreeClusterMap
(root)Bases: dipy.segment.clustering.ClusterMap
Attributes: 


Methods
add_cluster (*clusters) 
Adds one or multiple clusters to this cluster map. 
clear () 
Remove all clusters from this cluster map. 
clusters_sizes () 
Gets the size of every cluster contained in this cluster map. 
get_large_clusters (min_size) 
Gets clusters which contains at least min_size elements. 
get_small_clusters (max_size) 
Gets clusters which contains at most max_size elements. 
remove_cluster (*clusters) 
Remove one or multiple clusters from this cluster map. 
size () 
Gets number of clusters contained in this cluster map. 
get_clusters  
iter_preorder  
traverse_postorder 
dipy.segment.clustering.
abstractmethod
(funcobj)A decorator indicating abstract methods.
Requires that the metaclass is ABCMeta or derived from it. A class that has a metaclass derived from ABCMeta cannot be instantiated unless all of its abstract methods are overridden. The abstract methods can be called using any of the normal ‘super’ call mechanisms.
Usage:
 class C(metaclass=ABCMeta):
@abstractmethod def my_abstract_method(self, …):
…
dipy.segment.clustering.
qbx_and_merge
(streamlines, thresholds, nb_pts=20, select_randomly=None, rng=None, verbose=True)Run QuickBundlesX and then run again on the centroids of the last layer
Running again QuickBundles at a layer has the effect of merging some of the clusters that maybe originally devided because of branching. This function help obtain a result at a QuickBundles quality but with QuickBundlesX speed. The merging phase has low cost because it is applied only on the centroids rather than the entire dataset.
Parameters: 


Returns: 

References
[Garyfallidis12]  Garyfallidis E. et al., QuickBundles a method for tractography simplification, Frontiers in Neuroscience, vol 6, no 175, 2012. 
[Garyfallidis16]  Garyfallidis E. et al. QuickBundlesX: Sequential clustering of millions of streamlines in multiple levels of detail at record execution time. Proceedings of the, International Society of Magnetic Resonance in Medicine (ISMRM). Singapore, 4187, 2016. 
dipy.segment.clustering.
set_number_of_points
()Change the number of points of streamlines in order to obtain nb_points1 segments of equal length. Points of streamlines will be modified along the curve.
Parameters: 


Returns: 

Examples
>>> from dipy.tracking.streamline import set_number_of_points
>>> import numpy as np
One streamline, a semicircle:
>>> theta = np.pi*np.linspace(0, 1, 100)
>>> x = np.cos(theta)
>>> y = np.sin(theta)
>>> z = 0 * x
>>> streamline = np.vstack((x, y, z)).T
>>> modified_streamline = set_number_of_points(streamline, 3)
>>> len(modified_streamline)
3
Multiple streamlines:
>>> streamlines = [streamline, streamline[::2]]
>>> new_streamlines = set_number_of_points(streamlines, 10)
>>> [len(s) for s in streamlines]
[100, 50]
>>> [len(s) for s in new_streamlines]
[10, 10]
dipy.segment.mask.
applymask
(vol, mask)Mask vol with mask.
Parameters: 


Returns: 

dipy.segment.mask.
binary_dilation
(input, structure=None, iterations=1, mask=None, output=None, border_value=0, origin=0, brute_force=False)Multidimensional binary dilation with the given structuring element.
Parameters: 


Returns: 

See also
grey_dilation
, binary_erosion
, binary_closing
, binary_opening
, generate_binary_structure
Notes
Dilation [1] is a mathematical morphology operation [2] that uses a structuring element for expanding the shapes in an image. The binary dilation of an image by a structuring element is the locus of the points covered by the structuring element, when its center lies within the nonzero points of the image.
References
[1]  (1, 2) http://en.wikipedia.org/wiki/Dilation_%28morphology%29 
[2]  (1, 2) http://en.wikipedia.org/wiki/Mathematical_morphology 
Examples
>>> from scipy import ndimage
>>> a = np.zeros((5, 5))
>>> a[2, 2] = 1
>>> a
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 1., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.]])
>>> ndimage.binary_dilation(a)
array([[False, False, False, False, False],
[False, False, True, False, False],
[False, True, True, True, False],
[False, False, True, False, False],
[False, False, False, False, False]], dtype=bool)
>>> ndimage.binary_dilation(a).astype(a.dtype)
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 1., 0., 0.],
[ 0., 1., 1., 1., 0.],
[ 0., 0., 1., 0., 0.],
[ 0., 0., 0., 0., 0.]])
>>> # 3x3 structuring element with connectivity 1, used by default
>>> struct1 = ndimage.generate_binary_structure(2, 1)
>>> struct1
array([[False, True, False],
[ True, True, True],
[False, True, False]], dtype=bool)
>>> # 3x3 structuring element with connectivity 2
>>> struct2 = ndimage.generate_binary_structure(2, 2)
>>> struct2
array([[ True, True, True],
[ True, True, True],
[ True, True, True]], dtype=bool)
>>> ndimage.binary_dilation(a, structure=struct1).astype(a.dtype)
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 1., 0., 0.],
[ 0., 1., 1., 1., 0.],
[ 0., 0., 1., 0., 0.],
[ 0., 0., 0., 0., 0.]])
>>> ndimage.binary_dilation(a, structure=struct2).astype(a.dtype)
array([[ 0., 0., 0., 0., 0.],
[ 0., 1., 1., 1., 0.],
[ 0., 1., 1., 1., 0.],
[ 0., 1., 1., 1., 0.],
[ 0., 0., 0., 0., 0.]])
>>> ndimage.binary_dilation(a, structure=struct1,\
... iterations=2).astype(a.dtype)
array([[ 0., 0., 1., 0., 0.],
[ 0., 1., 1., 1., 0.],
[ 1., 1., 1., 1., 1.],
[ 0., 1., 1., 1., 0.],
[ 0., 0., 1., 0., 0.]])
dipy.segment.mask.
color_fa
(fa, evecs)Color fractional anisotropy of diffusion tensor
Parameters: 


Returns: 

ec{e})) imes fa
dipy.segment.mask.
fractional_anisotropy
(evals, axis=1)Fractional anisotropy (FA) of a diffusion tensor.
Parameters: 


Returns: 

Notes
FA is calculated using the following equation:
dipy.segment.mask.
generate_binary_structure
(rank, connectivity)Generate a binary structure for binary morphological operations.
Parameters: 


Returns: 

See also
iterate_structure
, binary_dilation
, binary_erosion
Notes
generate_binary_structure can only create structuring elements with dimensions equal to 3, i.e. minimal dimensions. For larger structuring elements, that are useful e.g. for eroding large objects, one may either use iterate_structure, or create directly custom arrays with numpy functions such as numpy.ones.
Examples
>>> from scipy import ndimage
>>> struct = ndimage.generate_binary_structure(2, 1)
>>> struct
array([[False, True, False],
[ True, True, True],
[False, True, False]], dtype=bool)
>>> a = np.zeros((5,5))
>>> a[2, 2] = 1
>>> a
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 1., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.]])
>>> b = ndimage.binary_dilation(a, structure=struct).astype(a.dtype)
>>> b
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 1., 0., 0.],
[ 0., 1., 1., 1., 0.],
[ 0., 0., 1., 0., 0.],
[ 0., 0., 0., 0., 0.]])
>>> ndimage.binary_dilation(b, structure=struct).astype(a.dtype)
array([[ 0., 0., 1., 0., 0.],
[ 0., 1., 1., 1., 0.],
[ 1., 1., 1., 1., 1.],
[ 0., 1., 1., 1., 0.],
[ 0., 0., 1., 0., 0.]])
>>> struct = ndimage.generate_binary_structure(2, 2)
>>> struct
array([[ True, True, True],
[ True, True, True],
[ True, True, True]], dtype=bool)
>>> struct = ndimage.generate_binary_structure(3, 1)
>>> struct # no diagonal elements
array([[[False, False, False],
[False, True, False],
[False, False, False]],
[[False, True, False],
[ True, True, True],
[False, True, False]],
[[False, False, False],
[False, True, False],
[False, False, False]]], dtype=bool)
dipy.segment.mask.
median_filter
(input, size=None, footprint=None, output=None, mode='reflect', cval=0.0, origin=0)Calculate a multidimensional median filter.
Parameters: 


Returns: 

Examples
>>> from scipy import ndimage, misc
>>> import matplotlib.pyplot as plt
>>> fig = plt.figure()
>>> plt.gray() # show the filtered result in grayscale
>>> ax1 = fig.add_subplot(121) # left side
>>> ax2 = fig.add_subplot(122) # right side
>>> ascent = misc.ascent()
>>> result = ndimage.median_filter(ascent, size=20)
>>> ax1.imshow(ascent)
>>> ax2.imshow(result)
>>> plt.show()
dipy.segment.mask.
median_otsu
(input_volume, median_radius=4, numpass=4, autocrop=False, vol_idx=None, dilate=None)Simple brain extraction tool method for images from DWI data.
It uses a median filter smoothing of the input_volumes vol_idx and an automatic histogram Otsu thresholding technique, hence the name median_otsu.
This function is inspired from Mrtrix’s bet which has default values
median_radius=3
, numpass=2
. However, from tests on multiple 1.5T
and 3T data from GE, Philips, Siemens, the most robust choice is
median_radius=4
, numpass=4
.
Parameters: 


Returns: 

Notes
Copyright (C) 2011, the scikitimage team All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 Neither the name of skimage nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS’’ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
dipy.segment.mask.
multi_median
(input, median_radius, numpass)Applies median filter multiple times on input data.
Parameters: 


Returns: 

dipy.segment.mask.
otsu
(image, nbins=256)Return threshold value based on Otsu’s method.
Parameters: 


Returns: 

Raises: 

Notes
The input image must be grayscale.
References
[1]  Wikipedia, http://en.wikipedia.org/wiki/Otsu’s_Method 
Examples
>>> from skimage.data import camera
>>> image = camera()
>>> thresh = threshold_otsu(image)
>>> binary = image <= thresh
dipy.segment.mask.
segment_from_cfa
(tensor_fit, roi, threshold, return_cfa=False)Segment the cfa inside roi using the values from threshold as bounds.
Parameters: 


Returns: 

ArcLengthFeature
dipy.segment.metric.
ArcLengthFeature
Bases: dipy.segment.featurespeed.CythonFeature
Extracts features from a sequential datum.
A sequence of Ndimensional points is represented as a 2D array with shape (nb_points, nb_dimensions).
The feature being extracted consists of one scalar representing the arc length of the sequence (i.e. the sum of the length of all segments).
Attributes: 


Methods
extract 
Extracts features from a sequential datum. 
infer_shape 
Infers the shape of features extracted from a sequential datum. 
AveragePointwiseEuclideanMetric
dipy.segment.metric.
AveragePointwiseEuclideanMetric
Bases: dipy.segment.metricspeed.SumPointwiseEuclideanMetric
Computes the average of pointwise Euclidean distances between two sequential data.
A sequence of Ndimensional points is represented as a 2D array with shape (nb_points, nb_dimensions). A feature object can be specified in order to calculate the distance between the features, rather than directly between the sequential data.
Parameters: 


Notes
The distance between two 2D sequential data:
s1 s2
0* a *0
\ 
\ 
1* 
 b *1
 \
2* \
c *2
is equal to \((a+b+c)/3\) where \(a\) is the Euclidean distance between s1[0] and s2[0], \(b\) between s1[1] and s2[1] and \(c\) between s1[2] and s2[2].
Attributes: 


Methods
are_compatible 
Checks if features can be used by metric.dist based on their shape. 
dist 
Computes a distance between two data points based on their features. 
CenterOfMassFeature
dipy.segment.metric.
CenterOfMassFeature
Bases: dipy.segment.featurespeed.CythonFeature
Extracts features from a sequential datum.
A sequence of Ndimensional points is represented as a 2D array with shape (nb_points, nb_dimensions).
The feature being extracted consists of one Ndimensional point representing the mean of the points, i.e. the center of mass.
Attributes: 


Methods
extract 
Extracts features from a sequential datum. 
infer_shape 
Infers the shape of features extracted from a sequential datum. 
CosineMetric
dipy.segment.metric.
CosineMetric
Bases: dipy.segment.metricspeed.CythonMetric
Computes the cosine distance between two vectors.
A vector (i.e. a Ndimensional point) is represented as a 2D array with shape (1, nb_dimensions).
Notes
The distance between two vectors \(v_1\) and \(v_2\) is equal to \(\frac{1}{\pi} \arccos\left(\frac{v_1 \cdot v_2}{\v_1\ \v_2\}\right)\) and is bounded within \([0,1]\).
Attributes: 


Methods
are_compatible 
Checks if features can be used by metric.dist based on their shape. 
dist 
Computes a distance between two data points based on their features. 
Feature
dipy.segment.metric.
Feature
Bases: object
Extracts features from a sequential datum.
A sequence of Ndimensional points is represented as a 2D array with shape (nb_points, nb_dimensions).
Parameters: 


Notes
When subclassing Feature, one only needs to override the extract and infer_shape methods.
Attributes: 


Methods
extract 
Extracts features from a sequential datum. 
infer_shape 
Infers the shape of features extracted from a sequential datum. 
extract
()Extracts features from a sequential datum.
Parameters: 


Returns: 

IdentityFeature
dipy.segment.metric.
IdentityFeature
Bases: dipy.segment.featurespeed.CythonFeature
Extracts features from a sequential datum.
A sequence of Ndimensional points is represented as a 2D array with shape (nb_points, nb_dimensions).
The features being extracted are the actual sequence’s points. This is useful for metric that does not require any preprocessing.
Attributes: 


Methods
extract 
Extracts features from a sequential datum. 
infer_shape 
Infers the shape of features extracted from a sequential datum. 
Metric
dipy.segment.metric.
Metric
Bases: object
Computes a distance between two sequential data.
A sequence of Ndimensional points is represented as a 2D array with shape (nb_points, nb_dimensions). A feature object can be specified in order to calculate the distance between extracted features, rather than directly between the sequential data.
Parameters: 


Notes
When subclassing Metric, one only needs to override the dist and are_compatible methods.
Attributes: 


Methods
are_compatible 
Checks if features can be used by metric.dist based on their shape. 
dist 
Computes a distance between two data points based on their features. 
are_compatible
()Checks if features can be used by metric.dist based on their shape.
Basically this method exists so we don’t have to do this check inside the metric.dist function (speedup).
Parameters: 


Returns: 

MidpointFeature
dipy.segment.metric.
MidpointFeature
Bases: dipy.segment.featurespeed.CythonFeature
Extracts features from a sequential datum.
A sequence of Ndimensional points is represented as a 2D array with shape (nb_points, nb_dimensions).
The feature being extracted consists of one Ndimensional point representing the middle point of the sequence (i.e. `nb_points//2`th point).
Attributes: 


Methods
extract 
Extracts features from a sequential datum. 
infer_shape 
Infers the shape of features extracted from a sequential datum. 
MinimumAverageDirectFlipMetric
dipy.segment.metric.
MinimumAverageDirectFlipMetric
Bases: dipy.segment.metricspeed.AveragePointwiseEuclideanMetric
Computes the MDF distance (minimum average directflip) between two sequential data.
A sequence of Ndimensional points is represented as a 2D array with shape (nb_points, nb_dimensions).
Notes
The distance between two 2D sequential data:
s1 s2
0* a *0
\ 
\ 
1* 
 b *1
 \
2* \
c *2
is equal to \(\min((a+b+c)/3, (a'+b'+c')/3)\) where \(a\) is the Euclidean distance between s1[0] and s2[0], \(b\) between s1[1] and s2[1], \(c\) between s1[2] and s2[2], \(a'\) between s1[0] and s2[2], \(b'\) between s1[1] and s2[1] and \(c'\) between s1[2] and s2[0].
Attributes: 


Methods
are_compatible 
Checks if features can be used by metric.dist based on their shape. 
dist 
Computes a distance between two data points based on their features. 
ResampleFeature
dipy.segment.metric.
ResampleFeature
Bases: dipy.segment.featurespeed.CythonFeature
Extracts features from a sequential datum.
A sequence of Ndimensional points is represented as a 2D array with shape (nb_points, nb_dimensions).
The features being extracted are the points of the sequence once resampled. This is useful for metrics requiring a constant number of points for all
streamlines.
Attributes: 


Methods
extract 
Extracts features from a sequential datum. 
infer_shape 
Infers the shape of features extracted from a sequential datum. 
SumPointwiseEuclideanMetric
dipy.segment.metric.
SumPointwiseEuclideanMetric
Bases: dipy.segment.metricspeed.CythonMetric
Computes the sum of pointwise Euclidean distances between two sequential data.
A sequence of Ndimensional points is represented as a 2D array with shape (nb_points, nb_dimensions). A feature object can be specified in order to calculate the distance between the features, rather than directly between the sequential data.
Parameters: 


Notes
The distance between two 2D sequential data:
s1 s2
0* a *0
\ 
\ 
1* 
 b *1
 \
2* \
c *2
is equal to \(a+b+c\) where \(a\) is the Euclidean distance between s1[0] and s2[0], \(b\) between s1[1] and s2[1] and \(c\) between s1[2] and s2[2].
Attributes: 


Methods
are_compatible 
Checks if features can be used by metric.dist based on their shape. 
dist 
Computes a distance between two data points based on their features. 
VectorOfEndpointsFeature
dipy.segment.metric.
VectorOfEndpointsFeature
Bases: dipy.segment.featurespeed.CythonFeature
Extracts features from a sequential datum.
A sequence of Ndimensional points is represented as a 2D array with shape (nb_points, nb_dimensions).
The feature being extracted consists of one vector in the Ndimensional space pointing from one endpoint of the sequence to the other (i.e. S[1]S[0]).
Attributes: 


Methods
extract 
Extracts features from a sequential datum. 
infer_shape 
Infers the shape of features extracted from a sequential datum. 
dipy.segment.metric.
dist
()Computes a distance between datum1 and datum2.
A sequence of Ndimensional points is represented as a 2D array with shape (nb_points, nb_dimensions).
Parameters: 


Returns: 

dipy.segment.metric.
distance_matrix
()Computes the distance matrix between two lists of sequential data.
The distance matrix is obtained by computing the pairwise distance of all tuples spawn by the Cartesian product of data1 with data2. If data2 is not provided, the Cartesian product of data1 with itself is used instead. A sequence of Ndimensional points is represented as a 2D array with shape (nb_points, nb_dimensions).
Parameters: 


Returns: 

dipy.segment.metric.
mdf
(s1, s2)Computes the MDF (Minimum average DirectFlip) distance [Garyfallidis12] between two streamlines.
Streamlines must have the same number of points.
Parameters: 


Returns: 

References
[Garyfallidis12]  (1, 2, 3) Garyfallidis E. et al., QuickBundles a method for tractography simplification, Frontiers in Neuroscience, vol 6, no 175, 2012. 
QuickBundles
dipy.segment.quickbundles.
QuickBundles
(tracks, dist_thr=4.0, pts=12)Bases: object
Attributes: 


Methods
remove_small_clusters (size) 
Remove clusters with small size 
clusters  
clusters_sizes  
downsampled_tracks  
exemplars  
label2cluster  
label2tracks  
label2tracksids  
partitions  
points_per_track  
remove_cluster  
remove_clusters  
remove_tracks  
virtuals 
__init__
(tracks, dist_thr=4.0, pts=12)Highly efficient trajectory clustering [Garyfallidis12].
Parameters: 


References
[Garyfallidis12]  (1, 2) Garyfallidis E. et al., QuickBundles a method for tractography simplification, Frontiers in Neuroscience, vol 6, no 175, 2012. 
Methods
clustering() returns a dict holding with the clustering result  
virtuals() gives the virtuals (track centroids) of the clusters  
exemplars() gives the exemplars (track medoids) of the clusters 
dipy.segment.quickbundles.
bundles_distances_mdf
()Calculate distances between list of tracks A and list of tracks B
All tracks need to have the same number of points
Parameters: 


Returns: 

See also
dipy.metrics.downsample
dipy.segment.quickbundles.
downsample
(xyz, n_pols=3)downsample for a specific number of points along the curve/track
Uses the length of the curve. It works in a similar fashion to midpoint and arbitrarypoint but it also reduces the number of segments of a track.
Parameters: 


Returns: 

Examples
>>> import numpy as np
>>> # a semicircle
>>> theta=np.pi*np.linspace(0,1,100)
>>> x=np.cos(theta)
>>> y=np.sin(theta)
>>> z=0*x
>>> xyz=np.vstack((x,y,z)).T
>>> xyz2=downsample(xyz,3)
>>> # a cosine
>>> x=np.pi*np.linspace(0,1,100)
>>> y=np.cos(theta)
>>> z=0*y
>>> xyz=np.vstack((x,y,z)).T
>>> _= downsample(xyz,3)
>>> len(xyz2)
3
>>> xyz3=downsample(xyz,10)
>>> len(xyz3)
10
dipy.segment.quickbundles.
local_skeleton_clustering
()Efficient tractography clustering
Every track can needs to have the same number of points. Use dipy.tracking.metrics.downsample to restrict the number of points
Parameters: 


Returns: 

See also
Notes
The distance calculated between two tracks:
t_1 t_2
0* a *0
\ 
\ 
1* 
 b *1
 \
2* \
c *2
is equal to \((a+b+c)/3\) where \(a\) the euclidean distance between t_1[0]
and t_2[0]
, \(b\) between t_1[1]
and t_2[1]
and \(c\) between
t_1[2]
and t_2[2]
. Also the same with t2 flipped (so t_1[0]
compared to t_2[2]
etc).
Visualization:
It is possible to visualize the clustering C from the example above using the dipy.viz module:
from dipy.viz import window, actor
r=window.Renderer()
for c in C:
color=np.random.rand(3)
for i in C[c]['indices']:
r.add(actor.line(tracks[i],color))
window.show(r)
Examples
>>> tracks=[np.array([[0,0,0],[1,0,0,],[2,0,0]]),
... np.array([[3,0,0],[3.5,1,0],[4,2,0]]),
... np.array([[3.2,0,0],[3.7,1,0],[4.4,2,0]]),
... np.array([[3.4,0,0],[3.9,1,0],[4.6,2,0]]),
... np.array([[0,0.2,0],[1,0.2,0],[2,0.2,0]]),
... np.array([[2,0.2,0],[1,0.2,0],[0,0.2,0]]),
... np.array([[0,0,0],[0,1,0],[0,2,0]])]
>>> C = local_skeleton_clustering(tracks, d_thr=0.5)
dipy.segment.threshold.
otsu
(image, nbins=256)Return threshold value based on Otsu’s method. Copied from scikitimage to remove dependency.
Parameters: 


Returns: 

dipy.segment.threshold.
upper_bound_by_percent
(data, percent=1)Find the upper bound for visualization of medical images
Calculate the histogram of the image and go right to left until you find the bound that contains more than a percentage of the image.
Parameters: 


Returns: 

dipy.segment.threshold.
upper_bound_by_rate
(data, rate=0.05)Adjusts upper intensity boundary using rates
It calculates the image intensity histogram, and based on the rate value it decide what is the upperbound value for intensity normalization, usually lower bound is 0. The rate is the ratio between the amount of pixels in every bins and the bins with highest pixel amount
Parameters: 


Returns: 

ConstantObservationModel
dipy.segment.tissue.
ConstantObservationModel
Bases: object
Observation model assuming that the intensity of each class is constant. The model parameters are the means \(\mu_{k}\) and variances \(\sigma_{k}\) associated with each tissue class. According to this model, the observed intensity at voxel \(x\) is given by \(I(x) = \mu_{k} + \eta_{k}\) where \(k\) is the tissue class of voxel \(x\), and \(\eta_{k}\) is a Gaussian random variable with zero mean and variance \(\sigma_{k}^{2}\). The observation model is responsible for computing the negative loglikelihood of observing any given intensity \(z\) at each voxel \(x\) assuming the voxel belongs to each class \(k\). It also provides a default parameter initialization.
Methods
initialize_param_uniform 
Initializes the means and variances uniformly 
negloglikelihood 
Computes the gaussian negative loglikelihood of each class at each voxel of image assuming a gaussian distribution with means and variances given by mu and sigmasq, respectively (constant models along the full volume). 
prob_image 
Conditional probability of the label given the image 
seg_stats 
Mean and standard variation for N desired tissue classes 
update_param 
Updates the means and the variances in each iteration for all the labels. 
update_param_new 
Updates the means and the variances in each iteration for all the labels. 
initialize_param_uniform
Initializes the means and variances uniformly
The means are initialized uniformly along the dynamic range of image. The variances are set to 1 for all classes
Parameters: 


Returns: 

negloglikelihood
Computes the gaussian negative loglikelihood of each class at each voxel of image assuming a gaussian distribution with means and variances given by mu and sigmasq, respectively (constant models along the full volume). The negative loglikelihood will be written in nloglike.
Parameters: 


Returns: 

prob_image
Conditional probability of the label given the image
Parameters: 


Returns: 

seg_stats
Mean and standard variation for N desired tissue classes
Parameters: 


Returns: 

update_param
Updates the means and the variances in each iteration for all the labels. This is for equations 25 and 26 of Zhang et. al., IEEE Trans. Med. Imag, Vol. 20, No. 1, Jan 2001.
Parameters: 


Returns: 

update_param_new
Updates the means and the variances in each iteration for all the labels. This is for equations 25 and 26 of the Zhang et al. paper
Parameters: 


Returns: 

IteratedConditionalModes
dipy.segment.tissue.
IteratedConditionalModes
Bases: object
Methods
icm_ising 
Executes one iteration of the ICM algorithm for MRF MAP estimation. 
initialize_maximum_likelihood 
Initializes the segmentation of an image with given 
prob_neighborhood 
Conditional probability of the label given the neighborhood Equation 2.18 of the Stan Z. 
icm_ising
Executes one iteration of the ICM algorithm for MRF MAP estimation. The prior distribution of the MRF is a Gibbs distribution with the Potts/Ising model with parameter beta:
https://en.wikipedia.org/wiki/Potts_model
Parameters: 


Returns: 

initialize_maximum_likelihood
Initializes the segmentation of an image with negloglikelihood field given by nloglike. The class of each voxel is selected as the one with the minimum negloglikelihood (i.e. maximumlikelihood segmentation).
Parameters: 


Returns: 

prob_neighborhood
Conditional probability of the label given the neighborhood Equation 2.18 of the Stan Z. Li book (Stan Z. Li, Markov Random Field Modeling in Image Analysis, 3rd ed., Advances in Pattern Recognition Series, Springer Verlag 2009.)
Parameters: 


Returns: 

TissueClassifierHMRF
dipy.segment.tissue.
TissueClassifierHMRF
(save_history=False, verbose=True)Bases: object
This class contains the methods for tissue classification using the Markov Random Fields modeling approach
Methods
classify (image, nclasses, beta[, tolerance, …]) 
This method uses the Maximum a posteriori  Markov Random Field approach for segmentation by using the Iterative Conditional Modes and Expectation Maximization to estimate the parameters. 
__init__
(save_history=False, verbose=True)Initialize self. See help(type(self)) for accurate signature.
classify
(image, nclasses, beta, tolerance=None, max_iter=None)This method uses the Maximum a posteriori  Markov Random Field approach for segmentation by using the Iterative Conditional Modes and Expectation Maximization to estimate the parameters.
Parameters: 


Returns: 

dipy.segment.tissue.
add_noise
(signal, snr, S0, noise_type='rician')Add noise of specified distribution to the signal from a single voxel.
Parameters: 


Returns: 

Notes
SNR is defined here, following [1], as S0 / sigma
, where sigma
is
the standard deviation of the two Gaussian distributions forming the real
and imaginary components of the Rician noise distribution (see [2]).
References
[1]  (1, 2) Descoteaux, Angelino, Fitzgibbons and Deriche (2007) Regularized, fast and robust qball imaging. MRM, 58: 497510 
[2]  (1, 2) Gudbjartson and Patz (2008). The Rician distribution of noisy MRI data. MRM 34: 910914. 
Examples
>>> signal = np.arange(800).reshape(2, 2, 2, 100)
>>> signal_w_noise = add_noise(signal, 10., 100., noise_type='rician')