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
- class FastSurferCNN.segstats.PVStats[source]¶
Dictionary of volume statistics for partial volume evaluation and global stats
Methods
clear
()copy
()fromkeys
(iterable[, value])Create a new dictionary with keys from iterable and values set to value.
get
(key[, default])Return the value for key if key is in the dictionary, else default.
items
()keys
()pop
(key[, default])If the key is not found, return the default if given; otherwise, raise a KeyError.
popitem
(/)Remove and return a (key, value) pair as a 2-tuple.
setdefault
(key[, default])Insert key with a value of default if key is not in the dictionary.
update
([E, ]**F)If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]
values
()
- FastSurferCNN.segstats.add_measure_parser(subparser_callback)[source]¶
Add a parser that supports adding measures to the parameters.
- FastSurferCNN.segstats.add_two_help_messages(parser)[source]¶
Adds separate help flags -h and –help to the parser for simple and detailed help. Both trigger the help action.
- Parameters:
- parser
argparse.ArgumentParser
Parser to add the flags to.
- parser
- FastSurferCNN.segstats.borders(_array, labels, max_label=None, six_connected=True, out=None)[source]¶
Handle to fast border computation.
This is an efficient implementation, for multiple/many classes between which borders should be computed.
- Parameters:
- _array
_ArrayType
Input labeled image or binary image.
- labels
Iterable
[int
],bool
List of labels for which borders will be computed. If labels is True, _array is treated as a binary mask.
- max_label
int
,optional
The maximum label to consider. If None, the maximum label in the array is used.
- six_connected
bool
, default=True If True, 6-connected borders (must share a face) are computed, otherwise 26-connected borders (must share a vertex) are computed.
- out
npt.NDArray
[bool
],optional
Output array to store the computed borders.
- _array
- Returns:
npt.NDArray
[bool
]Binary mask of border voxels.
- Raises:
ValueError
If labels does not fit to _array (binary mask and integer and vice-versa).
- FastSurferCNN.segstats.calculate_merged_labels(merged_labels, voxel_counts, robust_voxel_counts, volumes, mins=None, maxes=None, sums=None, sums_of_squares=None, eps=1e-06)[source]¶
Calculate the statistics for meta-labels, i.e. labels based on other labels (
merge_labels
). Add respective items totable
.- Parameters:
- merged_labels
VirtualLabel
A dictionary of key ‘merged id’ to value list of ids it references.
- voxel_counts
dict
[int
,int
] A dict of voxel counts for labels in the image/referenced in
merged_labels
.- robust_voxel_counts
dict
[int
,int
] A dict of the robust number of voxels referenced in
merged_labels
.- volumes
dict
[int
,float
] A dict of the volumes associated with each label.
- mins
dict
[int
,float
],optional
A dict of the minimum intensity associated with each label.
- maxes
dict
[int
,float
],optional
A dict of the minimum intensity associated with each label.
- sums
dict
[int
,float
],optional
A dict of the sums of voxel intensities associated with each label.
- sums_of_squares
dict
[int
,float
],optional
A dict of the sums of squares of voxel intensities associated with each label.
- eps
float
, default=1e-6 An epsilon value for numeric stability.
- merged_labels
- Yields:
PVStats
A dictionary per entry in
merged_labels
.
- FastSurferCNN.segstats.check_shape_affine(img1, img2, name1, name2)[source]¶
Check whether the shape and affine of
- Parameters:
- Raises:
RuntimeError
If shapes or affines are not the same.
- 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 slicer/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
] Mask to crop to.
- sub_patch
Optional
[Sequence
[slice
]] Subregion of mask to only consider (default: full mask).
- mask
- Returns:
- not_empty
bool
Whether there is any voxel in the patch at all.
- target_slicer
SlicingSequence
Sequence of slice-objects to extract the subregion of mask that is ‘True’.
- not_empty
- FastSurferCNN.segstats.format_parameters(**kwargs)[source]¶
Formats each keyword argument passed as a pair of key and value.
- 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
npt.NDArray
[_NumberType
],optional
The intensity image (default: None, do not compute intensity stats such as normMin, normMax, etc.).
- seg
npt.NDArray
[_IntType
] The segmentation image.
- out
npt.NDArray
[bool
],optional
Output array to store the computed borders.
- robust_percentage
float
,optional
A robustness percentile to compute the statistics with (default: None/off = 1).
- lab
- Returns:
- label
int
The label the stats belong to (input).
- stats
_GlobalStats
A tuple of number_of_voxels, number_of_within_robustness_thresholds, minimum_intensity, maximum_intensity, sum_of_intensities, sum_of_intensity_squares, and border with respect to the label.
- label
- FastSurferCNN.segstats.infer_labels_excludeid(args, lut, data)[source]¶
Infer the labels and excluded ids from command line arguments, the lookup table, or the segmentation image.
- Parameters:
- args
argparse.Namespace
The commandline arguments object.
- lut
pd.DataFrame
The ColorLUT lookup table object, e.g. FreeSurferColorLUT.
- data
npt.NDArray
[int
] The segmentation array.
- args
- Returns:
- FastSurferCNN.segstats.infer_merged_labels(manager, used_labels, merged_labels=(), merge_labels_start=0)[source]¶
- Parameters:
- manager
Manager
The brainvolstats Manager object to get virtual labels.
- used_labels
Iterable
[int
] A list of labels at that are already in use.
- merged_labels
Sequence
[Sequence
[int
]], default=() The list of merge labels (first value is SegId, then SegIds it sums across).
- merge_labels_start
int
, default=0 Start index to start at for finding multi-class merged label groups.
- manager
- Returns:
- FastSurferCNN.segstats.make_arguments(helpformatter=False)[source]¶
Create an argument parser object with all parameters of the script.
- Returns:
argparse.ArgumentParser
The configured argument parser.
- FastSurferCNN.segstats.pad_slicer(slicer, 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).- Parameters:
- slicer
Sequence
[slice
] Input slicing tuple.
- whalf
int
How much to pad/grow the slicing tuple all around.
- img_size
np.ndarray
,Sequence
[float
] Shape of the image.
- slicer
- Returns:
SlicingTuple
Tuple of slice-objects to go from image to padded patch.
SlicingTuple
Tuple of slice-objects to go from padded patch to patch.
- FastSurferCNN.segstats.parse_files(args, subjects_dir=None, subject_id=None, require_measurefile=False, require_pvfile=True)[source]¶
Parse and read paths of files.
- Parameters:
- args
argparse.Namespace
Parameters object from make_arguments.
- subjects_dir
Path
,str
,optional
Path to SUBJECTS_DIR, where subject directories are.
- subject_id
str
,optional
The subject_id string.
- require_measurefile
bool
, default=False Require the measurefile to exist.
- require_pvfile
bool
, default=True Require a pvfile or normfile to exist.
- args
- Returns:
- segfile
Path
Path to the segmentation file, most likely an absolute path.
- pvfile
Path
,None
Path to the pvfile file, most likely an absolute path.
- normfile
Path
,None
Path to the norm file, most likely an absolute path, or None if not passed.
- segstatsfile
Path
Path to the output segstats file, most likely an absolute path.
- measurefile
Path
,None
Path to the measure file, most likely an absolute path, not None is not passed.
- segfile
- Raises:
ValueError
If there is a necessary parameter missing or invalid.
- FastSurferCNN.segstats.patch_filter(patch_corner, 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:
bool
Whether there is any data in the patch at all.
SlicingSequence
Sequence of slice objects that describe patches with patch_corner and patch_size.
- FastSurferCNN.segstats.patch_neighbors(labels, pv_guide, seg, border_patch, borders, slicer_large_patch, slicer_patch, slicer_large_to_small, slicer_small_to_patch, slicer_large_to_patch, eps=1e-06, legacy_freesurfer=False)[source]¶
Calculate the neighbor statistics of labels for a specific patch.
The patch is defined by
slicer_large_patch
,slicer_large_to_small
,slicer_small_to_patch
, andslicer_large_to_patch
.- Parameters:
- labels
Sequence
[int
] A sequence of all labels that we want to compute the PV for.
- pv_guide
numpy.ndarray
The (full) image with intensities to guide the PV calculation.
- seg
numpy.typing.NDArray
[int
] The segmentation (full image) defining the labels.
- border_patch
npt.NDArray
[bool
] Binary mask for the current patch, True, where a voxel is considered to be a border voxel.
- borders
dict
[_IntType
,npt.NDArray
[bool
]] Dictionary containing the borders for each label.
- slicer_large_patch
SlicingTuple
Slicing tuple to obtain a patch of shape like the patch but padded to the large filter size.
- slicer_patch
SlicingTuple
Tuple of slice-objects to extract the patch from the full image.
- slicer_large_to_small
SlicingTuple
Tuple of slice-objects to extract the small patch (patch plus small filter window) from the large patch (patch plus large filter window).
- slicer_small_to_patch
SlicingTuple
Tuple of slice-objects to extract the patch from the patch padded by the small filter size.
- slicer_large_to_patch
SlicingTuple
Tuple of slice-objects to extract the patch from the patch padded by the large filter size.
- eps
float
, default=1e-6 Epsilon for considering a voxel being in the neighborhood.
- legacy_freesurfer
bool
, default=False Whether to use the legacy freesurfer mri_segstats formula or the corrected formula.
- labels
- Returns:
- pat_is_border
npt.NDArray
[bool
] Array indicating whether each label is on the patch border.
- pat_is_nbr
npt.NDArray
[bool
] Array indicating whether each label is a neighbor in the patch.
- pat_label_count
npt.NDArray
[float
] Array containing label counts in the patch (divided by the neighborhood size).
- pat_label_sums
npt.NDArray
[float
] Array containing the sum of normalized values for each label in the patch.
- pat_is_border
- FastSurferCNN.segstats.preproc_image(ops, data)[source]¶
Apply preprocessing operations to data. Performs, –mul, –abs, –sqr, –sqrt operations in that order.
- Parameters:
- ops
Sequence
[str
] Sequence of operations to perform from ‘mul=<factor>’, ‘div=<factor>’, ‘sqr’, ‘abs’, and ‘sqrt’.
- data
np.ndarray
Data to perform operations on.
- ops
- Returns:
np.ndarray
Data after ops are performed on it.
- FastSurferCNN.segstats.pv_calc(seg, pv_guide, 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
np.ndarray
Segmentation array with segmentation labels.
- pv_guide
np.ndarray
Image to use to calculate partial volume effects from.
- norm
np.ndarray
Intensity image to use to calculate image statistics from.
- labelsarray_like
Which labels are of interest.
- patch_size
int
, default=32 Size of patches.
- vox_vol
float
, default=1.0 Volume per voxel.
- eps
float
, default=1e-6 Threshold for computation of equality.
- robust_percentage
float
,optional
Fraction for robust calculation of statistics.
- merged_labels
VirtualLabel
,optional
Defines labels to compute statistics for that are.
- threads
int
,concurrent.futures.Executor
, default=-1 Number of parallel threads to use in calculation, alternatively an executor object.
- return_maps
bool
, default=False Returns a dictionary containing the computed maps.
- legacy_freesurfer
bool
, default=False Whether to use a freesurfer legacy compatibility mode to exactly replicate freesurfer.
- seg
- Returns:
- pv_stats
list
[PVStats
] Table (list of dicts) with keys SegId, NVoxels, Volume_mm3, Mean, StdDev, Min, Max, and Range.
- maps
dict
[str
,np.ndarray
],optional
Only returned, if return_maps is True: A dictionary with the 5 meta-information pv-maps: nbr: The alternative labels that were considered instead of the voxel’s label. nbr_means: The local mean intensity of the label nbr at the specific voxel. seg_means: The local mean intensity of the primary label at the specific voxel. mixing_coeff: The partial volume of the primary label at the location. nbr_mixing_coeff: The partial volume of the alternative (nbr) label.
- pv_stats
- FastSurferCNN.segstats.pv_calc_patch(slicer_patch, global_crop, borders, seg, pv_guide, 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, the function also fills in per voxel results for the respective voxels in the patch.
- Parameters:
- slicer_patch
SlicingTuple
Tuple of slice-objects, with indexing origin at the image origin.
- global_crop
SlicingTuple
Tuple of slice-objects, a global mask to limit computing to relevant parts of the image.
- borders
dict
[int
,npt.NDArray
[bool
]] Dictionary containing the borders for each label.
- seg
numpy.typing.NDArray
[int
] The segmentation (full image) defining the labels.
- pv_guide
numpy.ndarray
The (full) image with intensities to guide the PV calculation.
- border
npt.NDArray
[bool
] Binary mask, True, where a voxel is considered to be a border voxel.
- full_pv
npt.NDArray
[float
],optional
PV image to fill with values for debugging.
- full_ipv
npt.NDArray
[float
],optional
IPV image to fill with values for debugging.
- full_nbr_label
npt.NDArray
[_IntType
],optional
NBR image to fill with values for debugging.
- full_seg_mean
npt.NDArray
[float
],optional
Mean pv_guide-values for current segmentation label-image to fill with values for debugging.
- full_nbr_mean
npt.NDArray
[float
],optional
Mean pv_guide-values for nbr label-image to fill with values for debugging.
- eps
float
, default=1e-6 Epsilon for considering a voxel being in the neighborhood.
- legacy_freesurfer
bool
, default=False Whether to use the legacy freesurfer mri_segstats formula or the corrected formula.
- slicer_patch
- Returns:
- FastSurferCNN.segstats.seg_borders(_array, label, out=None, cmp_dtype='int8')[source]¶
Handle to fast 6-connected border computation.
- Parameters:
- _array
numpy.ndarray
Image to compute borders from, typically either a label image or a binary mask.
- label
int
,bool
Which classes to consider for border computation (True/False for binary mask).
- out
nt.NDArray
[bool
],optional
The array for inplace computation.
- cmp_dtype
npt.DTypeLike
, default=int8 The data type to use for border laplace computation.
- _array
- Returns:
npt.NDArray
[bool
]A binary mask with border voxels as True.
- FastSurferCNN.segstats.table_to_dataframe(table, report_empty=True, must_keep_ids=None)[source]¶
Convert the list of PVStats dictionaries into a dataframe.
- Parameters:
- Returns:
pandas.DataFrame
The DataFrame object of all columns and rows in table.
- FastSurferCNN.segstats.uniform_filter(data, filter_size, fillval=0.0, slicer_patch=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 data.
- FastSurferCNN.segstats.update_structnames(table, lut, merged_labels=None)[source]¶
Update StructNames from
lut
andmerged_labels
intable
.
- FastSurferCNN.segstats.write_statsfile(segstatsfile, dataframe, vox_vol, exclude=None, segfile=None, normfile=None, pvfile=None, lut=None, report_empty=False, extra_header=(), norm_name='norm', norm_unit='MR', volume_precision='1', legacy_freesurfer=False)[source]¶
Write a segstatsfile very similar and compatible with mri_segstats output.
- Parameters:
- segstatsfile
Path
,str
Path to the output file.
- dataframe
pd.DataFrame
Data to write into the file.
- vox_vol
float
Voxel volume for the header.
- exclude
Sequence
[Union
[int
,str
]],optional
Sequence of ids and class names that were excluded from the pv analysis (default: None).
- segfile
Path
,str
,optional
Path to the segmentation file (default: empty).
- normfile
Path
,str
,optional
Path to the bias-field corrected image (default: empty).
- pvfile
Path
,str
,optional
Path to file used to compute the PV effects (default: empty).
- lut
Path
,str
,optional
Path to the lookup table to find class names for label ids (default: empty).
- report_empty
bool
, default=False Do not skip non-empty regions in the lut.
- extra_header
Sequence
[str
], default=() 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).
- norm_name
str
, default=”norm” Name of the intensity image.
- norm_unit
str
, default=”MR” Unit of the intensity image.
- volume_precision
str
, default=”1” Number of digits after the comma for volume. Forced to 1 for legacy_freesurfer.
- legacy_freesurfer
bool
, default=False Whether the script ran with the legacy freesurfer option.
- segstatsfile