FastSurferCNN.segstats

class FastSurferCNN.segstats.HelpFormatter(prog, indent_increment=2, max_help_position=24, width=None)[source]

Help formatter that forces line breaks in texts where the text is <br>.

Methods

format_help()

start_section(heading)

add_argument

add_arguments

add_text

add_usage

end_section

FastSurferCNN.segstats.borders(_array, labels, max_label=None, six_connected=True, out=None)[source]

Handle to fast border computation.

Parameters:
_array_ArrayType

Input labeled array or binary image.

labelsIterable[np.int], bool

List of labels for which borders will be computed. If labels is True, _array is treated as a binary mask.

max_labelnp.int, optional

The maximum label ot consider. If None, the maximum label in the array is used.

six_connectedbool, default=True

If True, 6-connected borders are computed, otherwise 26-connected borders are computed.

out_ArrayType, optional

Output array to store the computed borders (Optional).

Returns:
_ArrayType

A binary image where borders are marked as True.

FastSurferCNN.segstats.crop_patch_to_mask(mask, sub_patch=None)[source]

Crop the patch to regions of the mask that are non-zero.

Assumes mask is always positive. Returns whether there is any mask>0 in the patch and a patch shrunk to mask>0 regions. The optional subpatch constrains this operation to the sub-region defined by a sequence of slicing operations.

Parameters:
masknpt.NDArray[_NumberType]

To crop to.

sub_patchOptional[Sequence[slice]]

Subregion of mask to only consider (default: full mask).

Returns:
bool

Whether there are mask-True voxels in the patch.

Sequence[slice]

Cropped patch.

Notes

This function requires device synchronization.

FastSurferCNN.segstats.global_stats(lab, norm, seg, out=None, robust_percentage=None)[source]

Compute Label, Number of voxels, ‘robust’ number of voxels, norm minimum, maximum, sum, sum of squares and 6-connected border of label lab (out references the border).

Parameters:
lab_IntType

Label to compute statistics for.

normpt.NDArray[_NumberType]

Normalized image.

segnpt.NDArray[_IntType]

Segmentation image.

outnpt.NDArray[bool], Optional

Output array to store the computed borders (Optional).

robust_percentagefloat, Optional

Percentage of values to keep for robust statistics (Default: None).

Returns:
_IntType and int

Label and number of voxels.

or _IntType, int, int, _NumberType, _NumberType, float, float, float and npt.NDArray[bool]

Label, number of voxels, ‘robust’ number of voxels, norm minimum, maximum, sum, sum of squares, volume and border.

FastSurferCNN.segstats.grow_patch(patch, whalf, img_size)[source]

Create two slicing tuples for indexing ndarrays/tensors that ‘grow’ and re-‘ungrow’ the patch patch by whalf (also considering the image shape).

Parameters:
patchSequence[slice]

A sequence of slices.

whalfint

Integer that specifies the amount to grow/ungrow the patch.

img_sizenp.ndarray, Sequence[float]

Size of the image.

Returns:
tuple[tuple[slice, …], tuple[slice, …]]

A tuple containing the grown patch and the ungrown patch.

FastSurferCNN.segstats.loadfile_full(file, name)[source]

Load full image and data.

Parameters:
filestr

Filename.

namestr

Subject name.

Returns:
Tuple[nib.analyze.SpatialImage, np.ndarray]

A tuple containing the loaded image and its corresponding data.

FastSurferCNN.segstats.main(args)[source]

Main function.

Parameters:
argsargparse.Namespace

Command-line arguments parsed using argparse.

Returns:
int

Exit code. Returns 0 upon successful execution.

FastSurferCNN.segstats.make_arguments(helpformatter=False)[source]

Create and configure the argparse.ArgumentParser.

Returns:
argparse.ArgumentParser

The configured argument parser.

FastSurferCNN.segstats.patch_filter(pos, mask, global_crop, patch_size=32)[source]

Return, whether there are mask-True voxels in the patch starting at pos with size patch_size and the resulting patch shrunk to mask-True regions.

Parameters:
posTuple[int, int, int]

Starting position of the patch.

masknpt.NDArray[bool]

Mask to crop to.

global_cropTuple[slice, …]

Global cropping context.

patch_sizeint, default=32

Size of patch. Defaults to 32.

Returns:
bool

Whether there are mask-True voxels in the patch.

Sequence[slice]

Cropped patch.

FastSurferCNN.segstats.patch_neighbors(labels, norm, seg, pat_border, loc_border, patch_grow7, patch_in_gc, patch_shrink6, ungrow1_patch, ungrow7_patch, ndarray_alloc, eps, legacy_freesurfer=False)[source]

Calculate the neighbor statistics of labels, etc..

Parameters:
labelsList[int]

List of unique labels.

normnp.ndarray

Array containing normalization values.

segnp.ndarray

Segmentation array.

pat_bordernp.ndarray

Array indicating whether each voxel in the patch is on the border.

loc_borderDict[int, np.ndarray]

Dictionary mapping labels to arrays indicating whether each voxel is on the global crop border.

patch_grow7Tuple[slice, …]

Grown patch for label detection.

patch_in_gcTuple[slice, …]

Patch within the global crop.

patch_shrink6Tuple[slice, …]

Shrunken patch for neighbor detection.

ungrow1_patchTuple[slice, …]

Ungrown patch for border detection.

ungrow7_patchTuple[slice, …]

Ungrown patch for label statistics.

ndarray_allocCallable[…, np.ndarray]

Function for allocating NumPy arrays.

epsfloat

Small value for numerical stability.

legacy_freesurferbool, optional

Whether to use legacy FreeSurfer mode. Defaults to False.

Returns:
Tuple of NumPy arrays:
  • pat_is_bordernp.ndarray

    Array indicating whether each label is on the patch border.

  • pat_is_nbrnp.ndarray

    Array indicating whether each label is a neighbor in the patch.

  • pat_label_countsnp.ndarray

    Array containing label counts in the patch.

  • pat_label_sumsnp.ndarray

    Array containing the sum of normalized values for each label in the patch.

FastSurferCNN.segstats.pv_calc(seg, norm, labels, patch_size=32, vox_vol=1.0, eps=1e-06, robust_percentage=None, merged_labels=None, threads=-1, return_maps=False, legacy_freesurfer=False)[source]

Compute volume effects.

Parameters:
segnpt.NDArray[_IntType]

Segmentation array with segmentation labels.

normnp.ndarray

Bias.

labelsSequence[_IntType]

Which labels are of interest.

patch_sizeint

Size of patches (Default value = 32).

vox_volfloat

Volume per voxel (Default value = 1.0).

epsfloat

Threshold for computation of equality (Default value = 1e-6).

robust_percentageOptional[float]

Fraction for robust calculation of statistics (Default value = None).

merged_labelsOptional[VirtualLabel]

Defines labels to compute statistics for that are (Default value = None).

threadsint

Number of parallel threads to use in calculation (Default value = -1).

return_mapsbool

Returns a dictionary containing the computed maps (Default value = False).

legacy_freesurferbool

Whether to use a freesurfer legacy compatibility mode to exactly replicate freesurfer (Default value = False).

Returns:
Union[List[PVStats],Tuple[List[PVStats],Dict[str,np.ndarray]]]

Table (list of dicts) with keys SegId, NVoxels, Volume_mm3, StructName, normMean, normStdDev, normMin, normMax, and normRange. (Note: StructName is unfilled) if return_maps: a dictionary with the 5 meta-information pv-maps: nbr: An image of alternative labels that were considered instead of the voxel’s label nbrmean: The local mean intensity of the label nbr at the specific voxel segmean: The local mean intensity of the primary label at the specific voxel pv: The partial volume of the primary label at the location ipv: The partial volume of the alternative (nbr) label at the location ipv: The partial volume of the alternative (nbr) label at the location.

FastSurferCNN.segstats.pv_calc_patch(patch, global_crop, loc_border, seg, norm, border, full_pv=None, full_ipv=None, full_nbr_label=None, full_seg_mean=None, full_nbr_mean=None, eps=1e-06, legacy_freesurfer=False)[source]

Calculate PV for patch.

If full* keyword arguments are passed, also fills, per voxel results for the respective voxels in the patch.

Parameters:
patchTuple[slice, …]

Patch to calculate PV for.

global_cropTuple[slice, …]

Global cropping context.

loc_borderDict[_IntType, npt.NDArray[bool]]

Dictionary mapping labels to their borders.

segnpt.NDArray[_IntType]

Segmentation image.

normnp.ndarray

Normalized image.

bordernpt.NDArray[bool]

Border of the patch.

full_pvnpt.NDArray[float], Optional

Array to store the partial volume for each voxel in the patch (Optional).

full_ipvnpt.NDArray[float], Optional

Array to store the inverse partial volume for each voxel in the patch (Optional).

full_nbr_labelnpt.NDArray[_IntType], Optional

Array to store the label for each neighboring voxel that contributes to the partial volume calculation. (Optional).

full_seg_meannpt.NDArray[float], Optional

Array to store the mean intensity of the segmentation label for each voxel in the patch (Optional).

full_nbr_meannpt.NDArray[float], Optional

Array to store the mean intensity of the neighboring voxels that contribute to the partial volume calculation for each voxel in the patch (Optional).

epsfloat, default=1e-6

Epsilon. Defaults to 1e-6.

legacy_freesurferbool, default=False

Whether to use a freesurfer legacy compatibility mode to exactly replicate freesurfer.

Returns:
Dict[_IntType, float]

Partial and inverse partial volumes for each label in the patch.

FastSurferCNN.segstats.read_classes_from_lut(lut_file)[source]

Modify from datautils to allow support for FreeSurfer-distributed ColorLUTs.

Read in FreeSurfer-like LUT table.

Parameters:
lut_filePath, str

Path and name of FreeSurfer-style LUT file with classes of interest. Example entry: ID LabelName R G B A 0 Unknown 0 0 0 0 1 Left-Cerebral-Exterior 70 130 180 0.

Returns:
pd.DataFrame

DataFrame with ids present, name of ids, color for plotting.

FastSurferCNN.segstats.seg_borders(_array, label, out=None, cmp_dtype='int8')[source]

Handle to fast 6-connected border computation.

Parameters:
_array_ArrayType

The input binary image or labeled array.

labelUnion[np.int, bool]

The label of the region for which borders will be computed.

outOptional[_ArrayType], optional

Output array to store the computed borders (Optional).

cmp_dtypenpt.DTypeLike, optional

The data type for the Laplace computation. Default is “int8” (Optional).

Returns:
_ArrayType

A binary image where borders are marked as True.

FastSurferCNN.segstats.uniform_filter(arr, filter_size, fillval, patch=None, out=None)[source]

Apply a uniform filter (with kernel size filter_size) to input.

The uniform filter is normalized (weights add to one).

Parameters:
arr_ArrayType

Input array.

filter_sizeint

Size of the uniform filter.

fillvalfloat

Fill value when the filter is outside the array.

patchtuple[slice, …], optional

Sub-region of the array to apply filter to (Default: None).

out_ArrayType, optional

Output array to store the result (Default: None).

Returns:
_ArrayType

The filtered array.

FastSurferCNN.segstats.unsqueeze(matrix, axis=-1)[source]

Unsqueeze the matrix.

Allows insertions of axis into the data/tensor, see numpy.expand_dims. This expands the torch.unsqueeze syntax to allow unsqueezing multiple axis at the same time.

Parameters:
matrixnp.ndarray

Matrix to unsqueeze.

axisUnion[int, Sequence[int]]

Axis for unsqueezing.

Returns:
np.ndarray

The unsqueezed matrix.

FastSurferCNN.segstats.write_statsfile(segstatsfile, dataframe, vox_vol, exclude=None, segfile=None, normfile=None, lut=None, extra_header=())[source]

Write a segstatsfile very similar and compatible with mri_segstats output.

Parameters:
segstatsfilestr

Path to the output file.

dataframepd.DataFrame

Data to write into the file.

vox_volfloat

Voxel volume for the header.

excludeOptional[Dict[int, str]]

Dictionary of ids and class names that were excluded from the pv analysis (default: None).

segfilestr

Path to the segmentation file (default: empty).

normfilestr

Path to the bias-field corrected image (default: empty).

lutstr

Path to the lookup table to find class names for label ids (default: empty).

extra_headerSequence[str]

Sequence of additional lines to add to the header. The initial # and newline characters will be added. Should not include newline characters (expect at the end of strings). (default: empty sequence).