# `segment`

## Module: `segment.bundles`

`RecoBundles`(streamlines, *[, greater_than, ...]) |
`check_range`(streamline, gt, lt) |
`bundle_adjacency`(dtracks0, dtracks1, threshold) | Find bundle adjacency between two given tracks/bundles
`ba_analysis`(recognized_bundle, expert_bundle, *) | Calculates bundle adjacency score between two given bundles
`cluster_bundle`(bundle, clust_thr, rng, *[, ...]) | Clusters bundles
`bundle_shape_similarity`(bundle1, bundle2, rng, *) | Calculates bundle shape similarity between two given bundles using bundle adjacency (BA) metric

## Module: `segment.clustering`

`Identity`() | Provides identity indexing functionality.
`Cluster`(*[, id, indices, refdata]) | Provides functionalities for interacting with a cluster.
`ClusterCentroid`(centroid, *[, id, indices, ...]) | 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`() |
`QuickBundles`(threshold, *[, metric, ...]) | Clusters streamlines using QuickBundles.
`QuickBundlesX`(thresholds, *[, metric]) | Clusters streamlines using QuickBundlesX.
`TreeCluster`(threshold, centroid, *[, indices]) |
`TreeClusterMap`(root) |
`qbx_and_merge`(streamlines, thresholds, *[, ...]) | Run QuickBundlesX and then run again on the centroids of the last layer.

## Module: `segment.fss`

`FastStreamlineSearch`(ref_streamlines, ...[, ...]) |
`nearest_from_matrix_row`(coo_array) | Return the nearest (smallest) for each row given an coup sparse matrix
`nearest_from_matrix_col`(coo_array) | Return the nearest (smallest) for each column given an coup sparse matrix

## Module: `segment.mask`

`multi_median`(data, median_radius, numpass) | Applies median filter multiple times on input data.
`applymask`(vol, mask) | Mask vol with mask.
`bounding_box`(vol) | Compute the bounding box of nonzero intensity voxels in the volume.
`crop`(vol, mins, maxs) | Crops the input volume.
`median_otsu`(input_volume, *[, vol_idx, ...]) | Simple brain extraction tool method for images from DWI data.
`segment_from_cfa`(tensor_fit, roi, threshold, *) | Segment the cfa inside roi using the values from threshold as bounds.
`clean_cc_mask`(mask) | Cleans a segmentation of the corpus callosum so no random pixels are included.

## Module: `segment.metric`

`mdf`(s1, s2) | Computes the MDF (Minimum average Direct-Flip) distance between two streamlines.
`mean_manhattan_distance`(a, b) | Compute the average Manhattan-L1 distance (MDF without flip)
`mean_euclidean_distance`(a, b) | Compute the average Euclidean-L2 distance (MDF without flip)

## Module: `segment.threshold`

`otsu`(image, *[, nbins]) | Return threshold value based on Otsu's method.
`upper_bound_by_rate`(data, *[, rate]) | Adjusts upper intensity boundary using rates
`upper_bound_by_percent`(data, *[, percent]) | Find the upper bound for visualization of medical images

## Module: `segment.tissue`

`TissueClassifierHMRF`(*[, save_history, verbose]) | This class contains the methods for tissue classification using the Markov Random Fields modeling approach.
`compute_directional_average`(data, bvals, *) | Compute the mean signal for each unique b-value shell and fit a linear model.
`dam_classifier`(data, bvals, wm_threshold, *) | Computes the P-map (fitting slope) on data to extract white and grey matter.

## Module: `segment.utils`

`remove_holes_and_islands`(binary_img, *[, ...]) | Remove any small mask chunks or holes that could be in the segmentation output.

### `RecoBundles`

class dipy.segment.bundles.RecoBundles(streamlines, *, greater_than=50, less_than=1000000, cluster_map=None, clust_thr=15, nb_pts=20, rng=None, verbose=False)

  Bases: `object`

  Methods

  `evaluate_results`(model_bundle, ...) | Compare the similarity 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.

  evaluate_results(model_bundle, pruned_streamlines, slr_select)

    Compare the similarity between two given bundles, model bundle, and extracted bundle.

    Parameters:
      model_bundle Streamlines

        Model bundle streamlines.

      pruned_streamlines Streamlines

        Pruned bundle streamlines.

      slr_select tuple

        Select the number of streamlines from model to neighborhood of model to perform the local SLR.

    Returns:
      ba_value float

        bundle adjacency value between model bundle and pruned bundle

      bmd_value float

        bundle minimum distance value between model bundle and pruned bundle

  recognize(model_bundle, model_clust_thr, *, reduction_thr=10, reduction_distance='mdf', slr=True, num_threads=None, slr_metric=None, slr_x0=None, slr_bounds=None, slr_select=(400, 600), slr_method='L-BFGS-B', pruning_thr=5, pruning_distance='mdf')

    Recognize the model_bundle in self.streamlines

    See [1] for further details about the method.

    Parameters:
      model_bundle Streamlines

        model bundle streamlines used as a reference to extract similar streamlines from input tractogram

      model_clust_thr float

        MDF distance threshold for the model bundles

      reduction_thr float, optional

        Reduce search space in the target tractogram by (mm) (default 10)

      reduction_distance string, optional

        Reduction distance type can be mdf or mam (default mdf)

      slr bool, optional

        Use Streamline-based Linear Registration (SLR) locally (default True)

      num_threads int, optional

        Number of threads to be used for OpenMP parallelization. If None (default) the value of OMP_NUM_THREADS environment variable is used if it is set, otherwise all available threads are used. If < 0 the maximal number of threads minus \(|num_threads + 1|\) is used (enter -1 to use as many threads as possible). 0 raises an error.

      slr_metric BundleMinDistanceMetric
      slr_x0 array or int or str, optional

        Transformation allowed. translation, rigid, similarity or scaling Initial parametrization for the optimization.

        If 1D array with:

          a) 6 elements then only rigid registration is performed with the 3 first elements for translation and 3 for rotation. b) 7 elements also isotropic scaling is performed (similarity). c) 12 elements then translation, rotation (in degrees), scaling and shearing are performed (affine).

          Here is an example of x0 with 12 elements: `x0=np.array([0, 10, 0, 40, 0, 0, 2., 1.5, 1, 0.1, -0.5, 0])`

          This has translation (0, 10, 0), rotation (40, 0, 0) in degrees, scaling (2., 1.5, 1) and shearing (0.1, -0.5, 0).

        If int:
          1. 6

               `x0 = np.array([0, 0, 0, 0, 0, 0])`

          2. 7

               `x0 = np.array([0, 0, 0, 0, 0, 0, 1.])`

          3. 12

               `x0 = np.array([0, 0, 0, 0, 0, 0, 1., 1., 1, 0, 0, 0])`

        If str:
          1. “rigid”

               `x0 = np.array([0, 0, 0, 0, 0, 0])`

          2. “similarity”

               `x0 = np.array([0, 0, 0, 0, 0, 0, 1.])`

          3. “affine”

               `x0 = np.array([0, 0, 0, 0, 0, 0, 1., 1., 1, 0, 0, 0])`

      slr_bounds array, optional

        SLR bounds.

      slr_select tuple, optional

        Select the number of streamlines from model to neighborhood of model to perform the local SLR.

      slr_method string, optional

        Optimization method ‘L_BFGS_B’ or ‘Powell’ optimizers can be used. (default ‘L-BFGS-B’)

      pruning_thr float, optional

        Pruning after reducing the search space.

      pruning_distance string, optional

        Pruning distance type can be mdf or mam.

    Returns:
      recognized_transf Streamlines

        Recognized bundle in the space of the model tractogram

      recognized_labels array

        Indices of recognized bundle in the original tractogram

    References

    [1] (1,2)

    Eleftherios Garyfallidis, Marc-Alexandre Côté, François Rheault, Jasmeen Sidhu, Janice Hau, Laurent Petit, David Fortin, Stephen Cunanne, and Maxime Descoteaux. Recognition of white matter bundles using local and global streamline-based registration and clustering. NeuroImage, 170:283–295, April 2018. Segmenting the Brain. URL: https://doi.org/10.1016/j.neuroimage.2017.07.015, doi:10.1016/j.neuroimage.2017.07.015.

  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='L-BFGS-B', 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 output of RecoBundles 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. This time, search space is created using pruned bundle and not model bundle.

    See [1], [2] for further details about the method.

    Parameters:
      model_bundle Streamlines

        model bundle streamlines used as a reference to extract similar streamlines from input tractogram

      pruned_streamlines Streamlines

        Recognized bundle from target tractogram by RecoBundles.

      model_clust_thr float

        MDF distance threshold for the model bundles

      reduction_thr float

        Reduce search space by (mm) (default 14)

      reduction_distance string

        Reduction distance type can be mdf or mam (default mdf)

      slr bool

        Use Streamline-based Linear Registration (SLR) locally.

      slr_metric BundleMinDistanceMetric

        Bundle distance metric.

      slr_x0 array or int or str

        Transformation allowed. translation, rigid, similarity or scaling Initial parametrization for the optimization.

        If 1D array with:

          1. 6 elements then only rigid registration is performed with the 3 first elements for translation and 3 for rotation.

          2. 7 elements also isotropic scaling is performed (similarity).

          3. 12 elements then translation, rotation (in degrees), scaling and shearing are performed (affine).

          Here is an example of x0 with 12 elements: `x0=np.array([0, 10, 0, 40, 0, 0, 2., 1.5, 1, 0.1, -0.5, 0])`

          This has translation (0, 10, 0), rotation (40, 0, 0) in degrees, scaling (2., 1.5, 1) and shearing (0.1, -0.5, 0).

        If int:
          1. 6

               `x0 = np.array([0, 0, 0, 0, 0, 0])`

          2. 7

               `x0 = np.array([0, 0, 0, 0, 0, 0, 1.])`

          3. 12

               `x0 = np.array([0, 0, 0, 0, 0, 0, 1., 1., 1, 0, 0, 0])`

        If str:
          1. “rigid”

               `x0 = np.array([0, 0, 0, 0, 0, 0])`

          2. “similarity”

               `x0 = np.array([0, 0, 0, 0, 0, 0, 1.])`

          3. “affine”

               `x0 = np.array([0, 0, 0, 0, 0, 0, 1., 1., 1, 0, 0, 0])`

      slr_bounds array

        SLR bounds.

      slr_select tuple

        Select the number of streamlines from model to neighborhood of model to perform the local SLR.

      slr_method string

        Optimization method ‘L_BFGS_B’ or ‘Powell’ optimizers can be used.

      pruning_thr float

        Pruning after reducing the search space.

      pruning_distance string

        Pruning distance type can be mdf or mam.

    Returns:
      recognized_transf Streamlines

        Recognized bundle in the space of the model tractogram

      recognized_labels array

        Indices of recognized bundle in the original tractogram

    References

    [2] (1,2)

    Bramsh Qamar Chandio, Shannon Leigh Risacher, Franco Pestilli, Daniel Bullock, Fang-Cheng Yeh, Serge Koudoro, Ariel Rokem, Jaroslaw Harezlak, and Eleftherios Garyfallidis. Bundle analytics, a computational framework for investigating the shapes and profiles of brain pathways across populations. Scientific Reports, 10:17149, October 2020. URL: https://doi.org/10.1038/s41598-020-74054-4, doi:10.1038/s41598-020-74054-4.

### check_range

dipy.segment.bundles.check_range(streamline, gt, lt)

### bundle_adjacency

dipy.segment.bundles.bundle_adjacency(dtracks0, dtracks1, threshold)

  Find bundle adjacency between two given tracks/bundles

  See [3] for further details about the method.

  Parameters:
    dtracks0 Streamlines

      White matter tract from one subject

    dtracks1 Streamlines

      White matter tract from another subject

    threshold float

      Threshold controls how much strictness user wants while calculating bundle adjacency between two bundles. Smaller threshold means bundles should be strictly adjacent to get higher BA score.

  Returns:
    res Float

      Bundle adjacency score between two tracts

  References

  [3] (1,2,3,4,5,6,7,8,9)

  Eleftherios Garyfallidis, Matthew Brett, Marta M. Correia, Guy B. Williams, and Ian Nimmo-Smith. QuickBundles, a Method for Tractography Simplification. Frontiers in Neuroscience, 6():175, December 2012. URL: https://doi.org/10.3389/fnins.2012.00175, doi:10.3389/fnins.2012.00175.

### ba_analysis

dipy.segment.bundles.ba_analysis(recognized_bundle, expert_bundle, *, nb_pts=20, threshold=6.0)

  Calculates bundle adjacency score between two given bundles

  See [3] for further details about the method.

  Parameters:
    recognized_bundle Streamlines

      Extracted bundle from the whole brain tractogram (eg: AF_L)

    expert_bundle Streamlines

      Model bundle used as reference while extracting similar type bundle from input tractogram

    nb_pts integer, optional

      Discretizing streamlines to have nb_pts number of points

    threshold float, optional

      Threshold used for in computing bundle adjacency. Threshold controls how much strictness user wants while calculating bundle adjacency between two bundles. Smaller threshold means bundles should be strictly adjacent to get higher BA score.

  Returns:
    Bundle adjacency score between two tracts

  References

### cluster_bundle

dipy.segment.bundles.cluster_bundle(bundle, clust_thr, rng, *, nb_pts=20, select_randomly=500000)

  Clusters bundles

  See [3] for further details about the method.

  Parameters:
    bundle Streamlines

      White matter tract

    clust_thr float

      clustering threshold used in quickbundlesX

    rng np.random.Generator

      numpy’s random generator for generating random values.

    nb_pts: integer, optional

      Discretizing streamlines to have nb_points number of points

    select_randomly: integer, optional

      Randomly select streamlines from the input bundle

  Returns:
    centroids Streamlines

      clustered centroids of the input bundle

  References

### bundle_shape_similarity

dipy.segment.bundles.bundle_shape_similarity(bundle1, bundle2, rng, *, clust_thr=(5, 3, 1.5), threshold=6)

  Calculates bundle shape similarity between two given bundles using bundle adjacency (BA) metric

  See [3], [2] for further details about the method.

  Parameters:
    bundle1 Streamlines

      White matter tract from one subject (eg: AF_L)

    bundle2 Streamlines

      White matter tract from another subject (eg: AF_L)

    rng np.random.Generator

      Random number generator.

    clust_thr array-like, optional

      list of clustering thresholds used in quickbundlesX

    threshold float, optional

      Threshold used for in computing bundle adjacency. Threshold controls how much strictness user wants while calculating shape similarity between two bundles. Smaller threshold means bundles should be strictly similar to get higher shape similarity score.

  Returns:
    ba_value float

      Bundle similarity score between two tracts

  References

### `Identity`

class 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.

### `Cluster`

class dipy.segment.clustering.Cluster(*, id=0, indices=None, refdata=None)

  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:
    cluster_map ClusterMap object

      Reference to the set of clusters this cluster is being part of.

    id int, optional

      Id of this cluster in its associated cluster_map object.

    refdata list, optional

      Actual elements that clustered indices refer to.

  Methods

  `assign`(*indices) | Assigns indices to this cluster.

  Notes

  A cluster does not contain actual data but instead knows how to retrieve them using its ClusterMap object.

  assign(*indices)

    Assigns indices to this cluster.

    Parameters:
      *indices list of indices

        Indices to add to this cluster.

### `ClusterCentroid`

class dipy.segment.clustering.ClusterCentroid(centroid, *, id=0, indices=None, refdata=None)

  Bases: `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:
    cluster_map ClusterMapCentroid object

      Reference to the set of clusters this cluster is being part of.

    id int, optional

      Id of this cluster in its associated cluster_map object.

    refdata list, optional

      Actual elements that clustered indices refer to.

  Methods

  `assign`(id_datum, features) | Assigns a data point to this cluster.
  `update`() | Update centroid of this cluster.

  Notes

  A cluster does not contain actual data but instead knows how to retrieve them using its ClusterMapCentroid object.

  assign(id_datum, features)

    Assigns a data point to this cluster.

    Parameters:
      id_datum int

        Index of the data point to add to this cluster.

      features 2D array

        Data point’s features to modify this cluster’s centroid.

  update()

    Update centroid of this cluster.

    Returns:
      converged bool

        Tells if the centroid has moved.

### `ClusterMap`

class dipy.segment.clustering.ClusterMap(*, refdata=None)

  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:
    refdata list

      Actual elements that clustered indices refer to.

  Attributes:
    clusters
    refdata

  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.

  add_cluster(*clusters)

    Adds one or multiple clusters to this cluster map.

    Parameters:
      *clusters Cluster object, …

        Cluster(s) to be added in this cluster map.

  clear()

    Remove all clusters from this cluster map.

  clusters_sizes()

    Gets the size of every cluster contained in this cluster map.

    Returns:
      list of int

        Sizes of every cluster in this cluster map.

  get_large_clusters(min_size)

    Gets clusters which contains at least min_size elements.

    Parameters:
      min_size int

        Minimum number of elements a cluster needs to have to be selected.

    Returns:
      list of Cluster objects

        Clusters having at least min_size elements.

  get_small_clusters(max_size)

    Gets clusters which contains at most max_size elements.

    Parameters:
      max_size int

        Maximum number of elements a cluster can have to be selected.

    Returns:
      list of Cluster objects

        Clusters having at most max_size elements.

  remove_cluster(*clusters)

    Remove one or multiple clusters from this cluster map.

    Parameters:
      *clusters Cluster object, …

        Cluster(s) to be removed from this cluster map.

  size()

    Gets number of clusters contained in this cluster map.

### `ClusterMapCentroid`

class dipy.segment.clustering.ClusterMapCentroid(*, refdata=None)

  Bases: `ClusterMap`

  Provides functionalities for interacting with clustering outputs that have centroids.

  Allows to retrieve easily 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:
    refdata list

      Actual elements that clustered indices refer to.

  Attributes:
    centroids
    clusters
    refdata

  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`

class dipy.segment.clustering.Clustering

  Bases: `object`

  Methods

  `cluster`(data, *[, ordering]) | Clusters data.

  abstractmethod cluster(data, *, ordering=None)

    Clusters data.

    Subclasses will perform their clustering algorithm here.

    Parameters:
      data list of N-dimensional arrays

        Each array represents a data point.

      ordering iterable of indices, optional

        Specifies the order in which data points will be clustered.

    Returns:
      ClusterMap object

        Result of the clustering.

### `QuickBundles`

class dipy.segment.clustering.QuickBundles(threshold, *, metric='MDF_12points', max_nb_clusters=None)

  Bases: `Clustering`

  Clusters streamlines using QuickBundles.

  Given a list of streamlines, the QuickBundles algorithm [3] 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:
    threshold float

      The maximum distance from a bundle for a streamline to be still considered as part of it.

    metric str or Metric object, optional

      The distance metric to use when comparing two streamlines. By default, the Minimum average Direct-Flip (MDF) distance [3] is used and streamlines are automatically resampled so they have 12 points.

    max_nb_clusters int, optional

      Limits the creation of bundles.

  Methods

  `cluster`(streamlines, *[, ordering]) | Clusters streamlines into bundles.

  References

  Examples

      >>> from dipy.segment.clustering import QuickBundles
      >>> from dipy.data import get_fnames
      >>> from dipy.io.streamline import load_tractogram
      >>> from dipy.tracking.streamline import Streamlines
      >>> fname = get_fnames(name='fornix')
      >>> fornix = load_tractogram(fname, 'same',
      ...                          bbox_valid_check=False).streamlines
      >>> streamlines = Streamlines(fornix)
      >>> # Segment fornix with a threshold 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.featurespeed import ResampleFeature
      >>> from dipy.segment.metricspeed 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]

  cluster(streamlines, *, ordering=None)

    Clusters streamlines into bundles.

    Performs quickbundles algorithm using predefined metric and threshold.

    Parameters:
      streamlines list of 2D arrays

        Each 2D array represents a sequence of 3D points (points, 3).

      ordering iterable of indices, optional

        Specifies the order in which data points will be clustered.

    Returns:
      ClusterMapCentroid object

        Result of the clustering.

### `QuickBundlesX`

class dipy.segment.clustering.QuickBundlesX(thresholds, *, metric='MDF_12points')

  Bases: `Clustering`

  Clusters streamlines using QuickBundlesX.

  See [4] for further details about the method.

  Parameters:
    thresholds list of float

      Thresholds to use for each clustering layer. A threshold represents the maximum distance from a cluster for a streamline to be still considered as part of it.

    metric str or Metric object, optional

      The distance metric to use when comparing two streamlines. By default, the Minimum average Direct-Flip (MDF) distance [3] is used and streamlines are automatically resampled so they have 12 points.

  Methods

  `cluster`(streamlines, *[, ordering]) | Clusters streamlines into bundles.

  References

  [4] (1,2)

  Eleftherios Garyfallidis, Marc-Alexandre Côté, François Rheault, and Maxime Descoteaux. QuickBundlesX: Sequential clustering of millions of streamlines in multiple levels of detail at record execution time. In ISMRM 24th Annual Meeting & Exhibition SMRT 25th Annual Meeting, volume. Singapore, 2016. International Society for Magnetic Resonance in Medicine (ISMRM).

  cluster(streamlines, *, ordering=None)

    Clusters streamlines into bundles.

    Performs QuickbundleX using a predefined metric and thresholds.

    Parameters:
      streamlines list of 2D arrays

        Each 2D array represents a sequence of 3D points (points, 3).

      ordering iterable of indices

        Specifies the order in which data points will be clustered.

    Returns:
      TreeClusterMap object

        Result of the clustering.

### `TreeCluster`

class dipy.segment.clustering.TreeCluster(threshold, centroid, *, indices=None)

  Bases: `ClusterCentroid`

  Attributes:
    is_leaf

  Methods

  `assign`(id_datum, features) | Assigns a data point to this cluster.
  `update`() | Update centroid of this cluster.

  add |
  return_indices |

### `TreeClusterMap`

class dipy.segment.clustering.TreeClusterMap(root)

  Bases: `ClusterMap`

  Attributes:
    clusters
    refdata

  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 |

### qbx_and_merge

dipy.segment.clustering.qbx_and_merge(streamlines, thresholds, *, nb_pts=20, select_randomly=None, rng=None, verbose=False)

  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 may be originally divided 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.

  See [3] and [4] for further details about the method.

  Parameters:
    streamlines Streamlines

      Streamlines.

    thresholds sequence

      List of distance thresholds for QuickBundlesX.

    nb_pts int

      Number of points for discretizing each streamline

    select_randomly int

      Randomly select a specific number of streamlines. If None all the streamlines are used.

    rng numpy.random.Generator

      If None then generator is initialized internally.

    verbose bool, optional.

      If True, log information. Default False.

  Returns:
    clusters obj

      Contains the clusters of the last layer of QuickBundlesX after merging.

  References

### `FastStreamlineSearch`

class dipy.segment.fss.FastStreamlineSearch(ref_streamlines, max_radius, *, nb_mpts=4, bin_size=20.0, resampling=24, bidirectional=True)

  Bases: `object`

  Methods

  `radius_search`(streamlines, radius, *[, ...]) | Radius Search using Fast Streamline Search

  radius_search(streamlines, radius, *, use_negative=True)

    Radius Search using Fast Streamline Search

    For each given streamlines, return all reference streamlines within the given radius. See [5] for further details.

    Parameters:
      streamlines Streamlines

        Streamlines to generate the tree structure.

      radius float

        Search radius (with MDF / average L2 distance) must be smaller than max_radius when FFS was initialized.

      use_negative bool, optional

        When used with bidirectional, negative values are returned for reversed order neighbors.

    Returns:
      res scipy COOrdinates sparse matrix (nb_slines x nb_slines_ref)

        Adjacency matrix containing all neighbors within the given radius

    Notes

    Given streamlines should be already aligned with ref streamlines. Preferably in millimeter space (voxmm or rasmm).

    References

    [5]

    Etienne St-Onge, Eleftherios Garyfallidis, and D. Louis Collins. Fast Streamline Search: An Exact Technique for Diffusion MRI Tractography. Neuroinformatics, 20(4):1093–1104, 2022. URL: https://doi.org/10.1007/s12021-022-09590-7, doi:10.1007/s12021-022-09590-7.

### nearest_from_matrix_row

dipy.segment.fss.nearest_from_matrix_row(coo_array)

  Return the nearest (smallest) for each row given an coup sparse matrix

  Parameters:
    coo_array scipy COOrdinates sparse array (nb_slines x nb_slines_ref)

      Adjacency matrix containing all neighbors within the given radius

  Returns:
    non_zero_ids numpy array (nb_non_empty_row x 1)

      Indices of each non-empty slines (row)

    nearest_id numpy array (nb_non_empty_row x 1)

      Indices of the nearest reference match (column)

    nearest_dist numpy array (nb_non_empty_row x 1)

      Distance for each nearest match

### nearest_from_matrix_col

dipy.segment.fss.nearest_from_matrix_col(coo_array)

  Return the nearest (smallest) for each column given an coup sparse matrix

  Parameters:
    coo_array scipy COOrdinates sparse matrix (nb_slines x nb_slines_ref)

      Adjacency matrix containing all neighbors within the given radius

  Returns:
    non_zero_ids numpy array (nb_non_empty_col x 1)

      Indices of each non-empty reference (column)

    nearest_id numpy array (nb_non_empty_col x 1)

      Indices of the nearest slines match (row)

    nearest_dist numpy array (nb_non_empty_col x 1)

      Distance for each nearest match

### multi_median

dipy.segment.mask.multi_median(data, median_radius, numpass)

  Applies median filter multiple times on input data.

  Parameters:
    data ndarray

      The input volume to apply filter on.

    median_radius int

      Radius (in voxels) of the applied median filter

    numpass: int

      Number of pass of the median filter

  Returns:
    data ndarray

      Filtered input volume.

### applymask

dipy.segment.mask.applymask(vol, mask)

  Mask vol with mask.

  Parameters:
    vol ndarray

      Array with \(V\) dimensions

    mask ndarray

      Binary mask. Has \(M\) dimensions where \(M <= V\). When \(M < V\), we append \(V - M\) dimensions with axis length 1 to mask so that mask will broadcast against vol. In the typical case vol can be 4D, mask can be 3D, and we append a 1 to the mask shape which (via numpy broadcasting) has the effect of applying the 3D mask to each 3D slice in vol (`vol[..., 0]` to `vol[..., -1`).

  Returns:
    masked_vol ndarray

      vol multiplied by mask where mask may have been extended to match extra dimensions in vol

### bounding_box

dipy.segment.mask.bounding_box(vol)

  Compute the bounding box of nonzero intensity voxels in the volume.

  Parameters:
    vol ndarray

      Volume to compute bounding box on.

  Returns:
    npmins list

      Array containing minimum index of each dimension

    npmaxs list

      Array containing maximum index of each dimension

### crop

dipy.segment.mask.crop(vol, mins, maxs)

  Crops the input volume.

  Parameters:
    vol ndarray

      Volume to crop.

    mins array

      Array containing minimum index of each dimension.

    maxs array

      Array containing maximum index of each dimension.

  Returns:
    vol ndarray

      The cropped volume.

### median_otsu

dipy.segment.mask.median_otsu(input_volume, *, vol_idx=None, median_radius=4, numpass=4, autocrop=False, dilate=None, finalize_mask=False)

  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:
    input_volume ndarray

      3D or 4D array of the brain volume.

    vol_idx None or array, optional

      1D array representing indices of `axis=3` of a 4D input_volume. None is only an acceptable input if `input_volume` is 3D.

    median_radius int, optional

      Radius (in voxels) of the applied median filter.

    numpass: int, optional

      Number of pass of the median filter.

    autocrop: bool, optional

      Deprecated since version 1.11.0: This parameter is deprecated and will be removed in 1.13.0.

      if True, the masked input_volume will also be cropped using the bounding box defined by the masked data. Should be on if DWI is upsampled to 1x1x1 resolution.

    dilate None or int, optional

      number of iterations for binary dilation

    finalize_mask bool, optional

      Whether to remove potential holes or islands. Useful for solving minor errors.

  Returns:
    maskedvolume ndarray

      Masked input_volume

    mask 3D ndarray

      The binary brain mask

  Notes

  Copyright (C) 2011, the scikit-image 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:

  > 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

  > 2. 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.

  > 3. 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.

### segment_from_cfa

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:
    tensor_fit TensorFit object

      TensorFit object

    roi ndarray

      A binary mask, which contains the bounding box for the segmentation.

    threshold array-like

      An iterable that defines the min and max values to use for the thresholding. The values are specified as (R_min, R_max, G_min, G_max, B_min, B_max)

    return_cfa bool, optional

      If True, the cfa is also returned.

  Returns:
    mask ndarray

      Binary mask of the segmentation.

    cfa ndarray, optional

      Array with shape = (…, 3), where … is the shape of tensor_fit. The color fractional anisotropy, ordered as a nd array with the last dimension of size 3 for the R, G and B channels.

### clean_cc_mask

dipy.segment.mask.clean_cc_mask(mask)

  Cleans a segmentation of the corpus callosum so no random pixels are included.

  Parameters:
    mask ndarray

      Binary mask of the coarse segmentation.

  Returns:
    new_cc_mask ndarray

      Binary mask of the cleaned segmentation.

### mdf

dipy.segment.metric.mdf(s1, s2)

  Computes the MDF (Minimum average Direct-Flip) distance between two streamlines.

  Streamlines must have the same number of points.

  See [3] for a definition of the distance.

  Parameters:
    s1 2D array

      A streamline (sequence of N-dimensional points).

    s2 2D array

      A streamline (sequence of N-dimensional points).

  Returns:
    double

      Distance between two streamlines.

  References

### mean_manhattan_distance

dipy.segment.metric.mean_manhattan_distance(a, b)

  Compute the average Manhattan-L1 distance (MDF without flip)

  Arrays are representing a single streamline or a list of streamlines that have the same number of N-dimensional points (two last axis).

  Parameters:
    a 2D or 3D array

      A streamline or concatenated streamlines (array of S streamlines by P points in N dimension).

    b 2D or 3D array

      A streamline or concatenated streamlines (array of S streamlines by P points in N dimension).

  Returns:
    1D array

      Distance between each S streamlines

### mean_euclidean_distance

dipy.segment.metric.mean_euclidean_distance(a, b)

  Compute the average Euclidean-L2 distance (MDF without flip)

  Arrays are representing a single streamline or a list of streamlines that have the same number of N-dimensional points (two last axis).

  Parameters:
    a 2D or 3D array

      A streamline or concatenated streamlines (array of S streamlines by P points in N dimension).

    b 2D or 3D array

      A streamline or concatenated streamlines (array of S streamlines by P points in N dimension).

  Returns:
    1D array

      Distance between each S streamlines

### otsu

dipy.segment.threshold.otsu(image, *, nbins=256)

  Return threshold value based on Otsu’s method. Copied from scikit-image to remove dependency.

  Parameters:
    image array

      Input image.

    nbins int

      Number of bins used to calculate histogram. This value is ignored for integer arrays.

  Returns:
    threshold float

      Threshold value.

### upper_bound_by_rate

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:
    data float

      Input intensity value data

    rate float

      representing the threshold whether a specific histogram bin that should be count in the normalization range

  Returns:
    high float

      the upper_bound value for normalization

### upper_bound_by_percent

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:
    data ndarray
    percent float
  Returns:
    upper_bound float

### `TissueClassifierHMRF`

class 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, *[, ...]) | 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.

  classify(image, nclasses, beta, *, tolerance=1e-05, max_iter=100)

    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:
      image ndarray,

        3D structural image.

      nclasses int,

        Number of desired classes.

      beta float,

        Smoothing parameter, the higher this number the smoother the output will be.

      tolerance: float, optional

        Value that defines the percentage of change tolerated to prevent the ICM loop to stop. Default is 1e-05. If you want tolerance check to be disabled put ‘tolerance = 0’.

      max_iter int, optional

        Fixed number of desired iterations. Default is 100. This parameter defines the maximum number of iterations the algorithm will perform. The loop may terminate early if the change in energy sum between iterations falls below the threshold defined by tolerance. However, if tolerance is explicitly set to 0, this early stopping mechanism is disabled, and the algorithm will run for the specified number of iterations unless another stopping criterion is met.

    Returns:
      initial_segmentation ndarray,

        3D segmented image with all tissue types specified in nclasses.

      final_segmentation ndarray,

        3D final refined segmentation containing all tissue types.

      PVE ndarray,

        3D probability map of each tissue type.

### compute_directional_average

dipy.segment.tissue.compute_directional_average(data, bvals, *, s0_map=None, masks=None, b0_mask=None, b0_threshold=50, low_signal_threshold=50)

  Compute the mean signal for each unique b-value shell and fit a linear model.

  Parameters:
    data ndarray

      The diffusion MRI data.

    bvals ndarray

      The b-values corresponding to the diffusion data.

    s0_map ndarray, optional

      Precomputed mean signal map for b=0 images.

    masks ndarray, optional

      Precomputed masks for each unique b-value shell.

    b0_mask ndarray, optional

      Precomputed mask for b=0 images.

    b0_threshold float, optional

      The intensity threshold for a b=0 image.

    low_signal_threshold float, optional

      The threshold below which a voxel is considered to have low signal.

  Returns:
    P float

      The slope of the linear model.

    V float

      The intercept of the linear model.

### dam_classifier

dipy.segment.tissue.dam_classifier(data, bvals, wm_threshold, *, b0_threshold=50, low_signal_threshold=50)

  Computes the P-map (fitting slope) on data to extract white and grey matter.

  See [6] for further details about the method.

  Parameters:
    data ndarray

      The diffusion MRI data.

    bvals ndarray

      The b-values corresponding to the diffusion data.

    wm_threshold float

      The threshold below which a voxel is considered white matter.

    b0_threshold float, optional

      The intensity threshold for a b=0 image.

    low_signal_threshold float, optional

      The threshold below which a voxel is considered to have low signal.

  Returns:
    wm_mask ndarray

      A binary mask for white matter.

    gm_mask ndarray

      A binary mask for grey matter.

  References

  [6]

  Hu Cheng, Sharlene Newman, Maryam Afzali, Shreyas Fadnavis, and Eleftherios Garyfallidis. Segmentation of the brain using direction-averaged signal of DWI images. Magnetic Resonance Imaging, 69:1–7, June 2020. URL: https://doi.org/10.1016/j.mri.2020.02.010, doi:10.1016/j.mri.2020.02.010.

### remove_holes_and_islands

dipy.segment.utils.remove_holes_and_islands(binary_img, *, remove_holes=True, remove_islands=True, slice_wise=False)

  Remove any small mask chunks or holes that could be in the segmentation output.

  Parameters:
    binary_img np.ndarray

      Binary image

    slice_wise bool, optional

      Whether to run slice wise background correction as well

    remove_holes bool, optional

      Whether to remove holes from the binary image

    remove_islands bool, optional

      Whether to remove islands from the binary image

  Returns:
    largest_img np.ndarray