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.
- labels
Iterable
[np.int
],bool
List of labels for which borders will be computed. If labels is True, _array is treated as a binary mask.
- max_label
np.int
,optional
The maximum label ot consider. If None, the maximum label in the array is used.
- six_connected
bool
, 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).
- _array
- 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:
- mask
npt.NDArray
[_NumberType
] To crop to.
- sub_patch
Optional
[Sequence
[slice
]] Subregion of mask to only consider (default: full mask).
- mask
- Returns:
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.
- norm
pt.NDArray
[_NumberType
] Normalized image.
- seg
npt.NDArray
[_IntType
] Segmentation image.
- out
npt.NDArray
[bool
],Optional
Output array to store the computed borders (Optional).
- robust_percentage
float
,Optional
Percentage of values to keep for robust statistics (Default: None).
- lab
- Returns:
- 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
bywhalf
(also considering the image shape).
- FastSurferCNN.segstats.loadfile_full(file, name)[source]¶
Load full image and data.
- Parameters:
- 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:
- args
argparse.Namespace
Command-line arguments parsed using argparse.
- args
- 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:
- Returns:
- 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:
- labels
List
[int
] List of unique labels.
- norm
np.ndarray
Array containing normalization values.
- seg
np.ndarray
Segmentation array.
- pat_border
np.ndarray
Array indicating whether each voxel in the patch is on the border.
- loc_border
Dict
[int
,np.ndarray
] Dictionary mapping labels to arrays indicating whether each voxel is on the global crop border.
- patch_grow7
Tuple
[slice
, …] Grown patch for label detection.
- patch_in_gc
Tuple
[slice
, …] Patch within the global crop.
- patch_shrink6
Tuple
[slice
, …] Shrunken patch for neighbor detection.
- ungrow1_patch
Tuple
[slice
, …] Ungrown patch for border detection.
- ungrow7_patch
Tuple
[slice
, …] Ungrown patch for label statistics.
- ndarray_alloc
Callable
[…,np.ndarray
] Function for allocating NumPy arrays.
- eps
float
Small value for numerical stability.
- legacy_freesurfer
bool
,optional
Whether to use legacy FreeSurfer mode. Defaults to False.
- labels
- 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:
- seg
npt.NDArray
[_IntType
] Segmentation array with segmentation labels.
- norm
np.ndarray
Bias.
- labels
Sequence
[_IntType
] Which labels are of interest.
- patch_size
int
Size of patches (Default value = 32).
- vox_vol
float
Volume per voxel (Default value = 1.0).
- eps
float
Threshold for computation of equality (Default value = 1e-6).
- robust_percentage
Optional
[float
] Fraction for robust calculation of statistics (Default value = None).
- merged_labels
Optional
[VirtualLabel
] Defines labels to compute statistics for that are (Default value = None).
- threads
int
Number of parallel threads to use in calculation (Default value = -1).
- return_maps
bool
Returns a dictionary containing the computed maps (Default value = False).
- legacy_freesurfer
bool
Whether to use a freesurfer legacy compatibility mode to exactly replicate freesurfer (Default value = False).
- seg
- 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:
- patch
Tuple
[slice
, …] Patch to calculate PV for.
- global_crop
Tuple
[slice
, …] Global cropping context.
- loc_border
Dict
[_IntType
,npt.NDArray
[bool
]] Dictionary mapping labels to their borders.
- seg
npt.NDArray
[_IntType
] Segmentation image.
- norm
np.ndarray
Normalized image.
- border
npt.NDArray
[bool
] Border of the patch.
- full_pv
npt.NDArray
[float
],Optional
Array to store the partial volume for each voxel in the patch (Optional).
- full_ipv
npt.NDArray
[float
],Optional
Array to store the inverse partial volume for each voxel in the patch (Optional).
- full_nbr_label
npt.NDArray
[_IntType
],Optional
Array to store the label for each neighboring voxel that contributes to the partial volume calculation. (Optional).
- full_seg_mean
npt.NDArray
[float
],Optional
Array to store the mean intensity of the segmentation label for each voxel in the patch (Optional).
- full_nbr_mean
npt.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).
- eps
float
, default=1e-6 Epsilon. Defaults to 1e-6.
- legacy_freesurfer
bool
, default=False Whether to use a freesurfer legacy compatibility mode to exactly replicate freesurfer.
- patch
- 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.
- 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.
- label
Union
[np.int
,bool
] The label of the region for which borders will be computed.
- out
Optional
[_ArrayType
],optional
Output array to store the computed borders (Optional).
- cmp_dtype
npt.DTypeLike
,optional
The data type for the Laplace computation. Default is “int8” (Optional).
- _array
- 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
) toinput
.The uniform filter is normalized (weights add to one).
- Parameters:
- 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:
- matrix
np.ndarray
Matrix to unsqueeze.
- axis
Union
[int
,Sequence
[int
]] Axis for unsqueezing.
- matrix
- 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:
- segstatsfile
str
Path to the output file.
- dataframe
pd.DataFrame
Data to write into the file.
- vox_vol
float
Voxel volume for the header.
- exclude
Optional
[Dict
[int
,str
]] Dictionary of ids and class names that were excluded from the pv analysis (default: None).
- segfile
str
Path to the segmentation file (default: empty).
- normfile
str
Path to the bias-field corrected image (default: empty).
- lut
str
Path to the lookup table to find class names for label ids (default: empty).
- extra_header
Sequence
[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).
- segstatsfile