cerr.radiomics package
Submodules
cerr.radiomics.first_order module
This module contains routine for calculation of 1st order statistical features.
- cerr.radiomics.first_order.stats(planC, structNum, offsetForEnergy=0, binWidth=None, binNum=None)[source]
This routine calculates 1st order statistical features from the input image and segmentation based on IBSI definitions https://ibsi.readthedocs.io/en/latest/03_Image_features.html#intensity-based-statistical-features.
- Parameters:
planC (plan_container.planC or np.ndarray(dtype=flat)) – planC containing the image and segmentation or scan np.ndarray.
structNum (int or np.ndarray(dtype=int)) – index of structure number in planC or binary mask for segmentation that matches the scan dimensions
offsetForEnergy (float) – optional, value to add to scan for computing the Energy, TotalEnergy and RMS features
binWidth (float) – optional, bin width for discretizing the input scan. Required when binNum is None. The default value is None.
binNum (int) – optional, number of bins to discretize the input scan. Required when binWidth is None. The default value is None.
- Returns:
dictionary of features
- Return type:
dict
cerr.radiomics.gray_level_cooccurence module
This module contains routines for calculation of Gray Level Co-occurrence matrix and features.
- cerr.radiomics.gray_level_cooccurence.calcCooccur(quantizedM, offsetsM, nL, cooccurType=1)[source]
This function calculates the cooccurrence matrix for the passed quantized image based on IBSI definitions https://ibsi.readthedocs.io/en/latest/03_Image_features.html#grey-level-co-occurrence-based-features
- Parameters:
quantizedM (np.ndarray(dtype=int)) – quantized 3d matrix obtained, for example, from radiomics.preprocess.imquantize_cerr
offsetsM (np.ndarray(dtype=int)) – Offsets for directionality/neighbors, obtained from radiomics.ibsi1.getDirectionOffsets
nL (int) – Number of gray levels. nL must be less than 65535.
cooccurType (int) – flag, 1 or 2. 1: returns a single cooccurrence matrix by combining contributions from all offsets into one cooccurrence matrix. 2: returns cooccurM with each column containing cooccurrence matrix for the row of offsetsM.
- Returns:
- cooccurrence matrix of size (nL*nL) x 1 for cooccurType = 1,
or (nL*nL) x offsetsM.shape[0] for cooccurType = 2.
The output can be passed to cooccurToScalarFeatures to get GLCM texture features.
- Return type:
np.ndarray
- cerr.radiomics.gray_level_cooccurence.cooccurToScalarFeatures(cooccurM)[source]
This function calculates scalar texture features from cooccurrence matrix as per IBSI definitions https://ibsi.readthedocs.io/en/latest/03_Image_features.html#grey-level-co-occurrence-based-features
- Parameters:
cooccurM (np.ndarray(dtype=int)) – cooccurrence matrix of size (nL*nL) x 1 for combined cooccurrrences from all the directions, or (nL*nL) x offsetsM.shape[0] for individual directions or patches.
- Returns:
- dictionary with scalar texture features as its
fields. Each field’s value is a vector containing the feature values for each column cooccurM.
- Return type:
dict
cerr.radiomics.ibsi1 module
This module contains routines for IBSI1 compatible radiomics calculation
- cerr.radiomics.ibsi1.getDirectionOffsets(direction)[source]
Return the voxel offset vectors for the given directionality.
- Parameters:
direction (int) – Directionality flag.
1for 3D (13 unique directions),2for 2D (4 in-plane directions).- Returns:
- Integer array of shape
(N, 3)where each row is a [row, col, slice]offset vector defining one co-occurrence direction.
- Integer array of shape
- Return type:
numpy.ndarray
- cerr.radiomics.ibsi1.getRadiomicsSettings(paramS)[source]
Parse a radiomics parameter dictionary and return individual extraction settings.
- Parameters:
paramS (dict) – Radiomics parameter dictionary loaded from a JSON settings file. Expected top-level keys include
'settings'and'featureClass'.- Returns:
A 13-element tuple containing:
firstOrderOffsetEnergy (float or None): Energy offset for first-order features.
firstOrderEntropyBinWidth (float or None): Bin width used for first-order entropy.
firstOrderEntropyBinNum (int or None): Number of bins for first-order entropy.
cooccurType (int or None): GLCM computation type (
1= merged texture,2= merged features).rlmType (int or None): RLM computation type (same convention as cooccurType).
szmDir (int or None): SZM directionality (
1= 3D,2= 2D).patch_radius (int or None): Patch radius in voxels for NGTDM/NGLDM.
difference_threshold (float or None): Intensity difference threshold for NGLDM.
offsetsM (numpy.ndarray or list): Direction offset vectors for texture matrices.
minClipIntensity (float or None): Lower clipping bound before quantization.
maxClipIntensity (float or None): Upper clipping bound before quantization.
textureBinNum (int or None): Number of quantization bins for texture features.
textureBinWidth (float or None): Bin width for texture quantization.
- Return type:
tuple
- Raises:
Exception – If both
textureBinNumandtextureBinWidthare specified simultaneously.
- cerr.radiomics.ibsi1.getQuantizedVolume(volToEval, paramS, maskBoundingBox3M, textureBinNum, minClipIntensity, maxClipIntensity, textureBinWidth)[source]
Quantize a 3D volume for texture feature computation.
Voxels outside the mask are set to
NaNprior to quantization so that the intensity range is derived exclusively from within the ROI.- Parameters:
volToEval (numpy.ndarray) – 3D image array (floating-point) to quantize.
paramS (dict) – Radiomics parameter dictionary. Must contain a
'settings'key; if a'texture'sub-key is present, quantization is applied.maskBoundingBox3M (numpy.ndarray) – Boolean 3D mask aligned with volToEval. Voxels outside the mask are excluded from quantization range estimation.
textureBinNum (int or None) – Number of quantization levels. Mutually exclusive with textureBinWidth.
minClipIntensity (float or None) – Lower clip bound applied before quantization. If
None, the in-mask minimum is used.maxClipIntensity (float or None) – Upper clip bound applied before quantization. If
None, the in-mask maximum is used.textureBinWidth (float or None) – Bin width for quantization. Mutually exclusive with textureBinNum.
- Returns:
- Quantized integer volume of the same shape as volToEval, or
the original volToEval unmodified when no
'texture'settings are found.
- Return type:
numpy.ndarray
- cerr.radiomics.ibsi1.calcRadiomicsForImgType(volToEval, maskBoundingBox3M, morphMask3M, gridS, paramS, rowColSlcOri='LPS')[source]
Compute IBSI-1 radiomics features for a single image type.
Iterates over the feature classes listed in
paramS['featureClass'](shape, first-order, GLCM, RLM, SZM, NGLDM, NGTDM) and returns a dictionary of computed features.- Parameters:
volToEval (numpy.ndarray) – 3D floating-point image array cropped to the bounding box of the ROI.
maskBoundingBox3M (numpy.ndarray) – Boolean 3D mask of the same shape as volToEval identifying the ROI voxels.
morphMask3M (numpy.ndarray) – Boolean 3D mask used for shape/morphology feature calculation (may differ from maskBoundingBox3M when re-segmentation thresholds are applied).
gridS (dict) – Grid coordinate dictionary with keys
'xValsV','yValsV','zValsV', and'PixelSpacingV'.paramS (dict) – Radiomics parameter dictionary loaded from a JSON settings file specifying which feature classes to compute and their settings.
rowColSlcOri (str) – Patient orientation string for the scan (e.g.
'LPS'). Defaults to'LPS'.
- Returns:
- Dictionary whose keys are feature-class names (e.g.
'shape', 'firstOrder','glcm') and whose values are dictionaries of scalar feature name → value mappings.
- Dictionary whose keys are feature-class names (e.g.
- Return type:
dict
- cerr.radiomics.ibsi1.computeFeatureImportance()[source]
Placeholder for future feature importance computation.
- Returns:
None
- cerr.radiomics.ibsi1.computeScalarFeatures(scanNum, structNum, settingsFile, planC)[source]
Pre-process a scan and compute all IBSI-1 radiomics features specified in a settings file.
Reads the JSON settings file, pre-processes the scan, and loops over every image type (original + filtered) requested in
radiomicsSettingS['imageType']. For each image type,calcRadiomicsForImgType()is called and the results are flattened into a single dictionary.- Parameters:
scanNum (int) – Index of the scan in
planC.scan.structNum (int) – Index of the structure in
planC.structure.settingsFile (str) – Path to the JSON radiomics settings file.
planC (cerr.plan_container.PlanC) – pyCERR plan container object.
- Returns:
A 2-element tuple
(featDictAllTypes, diagS)wherefeatDictAllTypes (dict): Flat dictionary mapping feature names (prefixed with image-type and feature-class labels) to scalar values. Returns an empty dict pair
({}, {})when the ROI mask is empty.diagS (dict): Diagnostic statistics dictionary (voxel counts, mean/min/max intensity after interpolation and re-segmentation).
- Return type:
tuple
- cerr.radiomics.ibsi1.getIBSINameMap()[source]
Return mappings from pyCERR feature names to IBSI benchmark feature names.
- Returns:
A 2-element tuple
(classDict, featDict)whereclassDict (dict): Maps pyCERR feature-class names (e.g.
'firstOrder') to their IBSI counterparts (e.g.'stat').featDict (dict): Maps pyCERR scalar feature names (e.g.
'mean') to their IBSI counterparts (e.g.'mean').
- Return type:
tuple
- cerr.radiomics.ibsi1.createFieldNameFromParameters(imageType, settingS)[source]
Create unique fieldname for radiomics features returned by calcRadiomicsForImgType :param imageType: ‘Original’ or filtered image type (see processImage.m for valid options) :param settingS: Parameter dictionary for radiomics feature extraction :return: fieldName
- cerr.radiomics.ibsi1.createFlatFeatureDict(featDict, imageType, avgType, directionality, mapToIBSI=False)[source]
Flatten a nested feature dictionary into a single-level dictionary with descriptive keys.
Constructs unique feature-name strings by combining the image type, feature class, feature name, directionality, and averaging strategy. For matrix-based features (GLCM, RLM) the mean, median, standard deviation, min, and max across directions are stored separately.
- Parameters:
featDict (dict) – Nested dictionary returned by
calcRadiomicsForImgType(). Outer keys are feature-class names; inner keys are scalar feature names.imageType (str) – Label for the image type (e.g.
'original','wavelets_...').avgType (str) – Averaging strategy used for directional texture features.
'feature'→ values are averaged per feature; any other string → combined (merged) matrix approach.directionality (str) – Directionality string from the settings file (
'2D'or'3D').mapToIBSI (bool) – When
True, feature class and feature names are mapped to IBSI benchmark identifiers viagetIBSINameMap(). Defaults toFalse.
- Returns:
- Flat dictionary mapping descriptive feature-name strings to scalar
numeric values (or arrays for directional features).
- Return type:
dict
- cerr.radiomics.ibsi1.writeFeaturesToFile(featList, csvFileName, writeHeader=True)[source]
Append one or more flat feature dictionaries to a CSV file.
- Parameters:
featList (dict or list of dict) – A single flat feature dictionary or a list of flat feature dictionaries (as produced by
createFlatFeatureDict()) to write as rows.csvFileName (str) – Path to the output CSV file. The file is opened in append mode so existing content is preserved.
writeHeader (bool) – When
True, a header row of field names is written before the data rows. Defaults toTrue.
- Returns:
None
cerr.radiomics.neighbor_gray_level_dependence module
This module contains routines for claculation of Gray Level Dependence texture features
- cerr.radiomics.neighbor_gray_level_dependence.calcNGLDM(scan_array, patch_size, num_grayscale_levels, a)[source]
This function calculates the Neighborhood Gray Level Dependence Matrix for the passed quantized image based on IBSI definitions https://ibsi.readthedocs.io/en/latest/03_Image_features.html#neighbouring-grey-level-dependence-based-features
- Parameters:
scan_array (np.ndarray(dtype=int)) – quantized 3d matrix obtained, for example, from radiomics.preprocess.imquantize_cerr
patch_size (list) – list of length 3 defining patch radius for row, col, slc dimensions.
num_grayscale_levels (int) – Number of gray levels.
a – coarseness parameter
- Returns:
NGLDM matrix os size (num_grayscale_levels, max_nbhood_size)
The output can be passed to ngldmToScalarFeatures to get NGLDM texture features.
- Return type:
np.ndarray
- cerr.radiomics.neighbor_gray_level_dependence.ngldmToScalarFeatures(s, numVoxels)[source]
This function calculates scalar texture features from Neighborhood Gray Level Dependence matrix as per IBSI definitions https://ibsi.readthedocs.io/en/latest/03_Image_features.html#neighbouring-grey-level-dependence-based-features
- Parameters:
(np.ndarray (s) – NGLDM matrix of size (num_grayscale_levels, max_nbhood_size)
numVoxels (int) – number of voxels in the region of interest used for generating s.
- Returns:
- dictionary with scalar NGLDM texture features as its
fields.
- Return type:
dict
cerr.radiomics.neighbor_gray_tone module
This module contains routines for claculation of Gray Tone Difference texture features
- cerr.radiomics.neighbor_gray_tone.calcNGTDM(scan_array, patch_size, numGrLevels)[source]
This function calculates the Neighborhood Gray Tone Difference Matrix for the passed quantized image based on IBSI definitions https://ibsi.readthedocs.io/en/latest/03_Image_features.html#neighbourhood-grey-tone-difference-based-features
- Parameters:
scan_array (np.ndarray(dtype=int)) – quantized 3d matrix obtained, for example, from radiomics.preprocess.imquantize_cerr
patch_size (list) – list of length 3 defining patch radius for row, col, slc dimensions.
num_grayscale_levels (int) – Number of gray levels.
a – coarseness parameter
- Returns:
NGLDM matrix os size (num_grayscale_levels, max_nbhood_size)
The output can be passed to ngldmToScalarFeatures to get NGLDM texture features.
- Return type:
np.ndarray
cerr.radiomics.preprocess module
This module contains routines for processing image and segmentation mask for radiomics calculation.
- cerr.radiomics.preprocess.imquantize(x, num_level=None, xmin=None, xmax=None, binwidth=None)[source]
Function to quantize an image based on the number of bins (num_level) or the bin width (bin_width). The min and max are computed from the input image image when they are not provided.
- Parameters:
x (np.ndarray) – Input image matrix.
num_level (int) – [optional, default: Use fixed bin_width] Number of quantization levels.
xmin (int) – [optional, default: Use min intensity in x] Minimum value for quantization.
xmax (int) – [optional, default: Use max intensity in x] Maximum value for quantization.
bin_width (int) – [optional, default: Use fixed num_level] Bin width for quantization.
- Returns:
Quantized image.
- Return type:
np.ndarray(dtype=int)
- cerr.radiomics.preprocess.calcRobustZscore(imgM)[source]
Compute element-wise robust z-scores using median and median absolute deviation (MAD).
The robust z-score is defined as
0.6745 * (x - median) / MAD, where the constant0.6745makes the estimator consistent with the standard deviation for normally distributed data.- Parameters:
imgM (numpy.ndarray) – Input image array of any shape.
- Returns:
- Array of the same shape as imgM containing the robust
z-score for each element.
- Return type:
numpy.ndarray
- cerr.radiomics.preprocess.extract_patches_3d_slice_wise(data_3d, patch_size)[source]
Extract 2-D patches from each axial slice of a 3-D volume.
For every slice along the third axis of data_3d,
sklearn’ssklearn.feature_extraction.image.extract_patches_2d()is called with patch_size and the resulting patches are stacked into a 4-D array.- Parameters:
data_3d (numpy.ndarray) – 3-D input array of shape
(rows, cols, slices).patch_size (tuple) – 2-element tuple
(patch_rows, patch_cols)specifying the spatial size of each extracted patch.
- Returns:
- 4-D array of shape
(n_patches_per_slice, patch_rows, patch_cols, slices)containing all extracted patches.
- Return type:
numpy.ndarray
Example:
data_3d = np.random.rand(30, 30, 30) patch_size = (5, 5) patches_3d = extract_patches_3d_slice_wise(data_3d, patch_size)
- cerr.radiomics.preprocess.getResampledGrid(resampResolutionV, xValsV, yValsV, zValsV, gridAlignMethod='center', *args)[source]
Function to create x,y,z image grid by resampling the input x,y,z grid at the required resolution.
- Parameters:
resampResolutionV (np.ndarray) – Input image matrix.
xValsV (np.array) – x-coordinates of the image grid.
yValsV (np.array) – y-coordinates od the image grid.
zValsV (np.array) – z-coordinates od the image grid.
gridAlignMethod – [optional, default=’center’] Currently, the only method supported is “center”.
- Returns:
(xResampleV, yResampleV, zResampleV) Resamples x,y,z grid coordinates.
- Return type:
Tuple
- cerr.radiomics.preprocess.imgResample3D(img3M, xValsV, yValsV, zValsV, xResampleV, yResampleV, zResampleV, method, extrapVal=None, inPlane=False)[source]
- Parameters:
img3M (np.ndarray) – 3D scan array e.g. planC.scan[scanNum].getScanArray()
xValsV (np.array) – x-coordinates i.e. along columns of img3M. Must be monotonically increasing order as per CERR coordinate system.
yValsV (np.array) – y-coordinates i.e. along rows of img3M. Must be monotonically decreasing order as per CERR coordinate system.
zValsV (np.array) – z-coordinates i.e. along slices of img3M. Must be monotonically increasing order as per CERR coordinate system.
xResampleV (np.array) – new x-coordinates i.e. along columns of resampled image
yResampleV (np.array) – new y-coordinates i.e. along rows of resampled image
zResampleV (np.array) – new z-coordinates i.e. along slices of resampled image
method (string) – Resampling methods supported by SimpleITK, viz. ‘sitkNearestNeighbor’, ‘sitkLinear’, ‘sitkBSpline’, ‘sitkGaussian’, ‘sitkLabelGaussian’,’sitkHammingWindowedSinc’,’sitkCosineWindowedSinc’, ‘sitkWelchWindowedSinc’,’sitkLanczosWindowedSinc’, ‘sitkBlackmanWindowedSinc’
extrapVal (float) – Value of extrapolated pixels. When not specified, the value of an extrapolated pixel is assigned from the nearest neighbor.
inPlane (bool) – [optional, default=False] Specify whether to restrict the interpolation to in-plane. (e.g. bi-linear). The default is 3D interpolation.
- Returns:
(np.ndarray) 3D array resampled at xResampleV, yResampleV, zResampleV
- cerr.radiomics.preprocess.padScan(scan3M, mask3M, method, marginV, cropFlag=True)[source]
Function to pad the input image using specified method and padding size.
- Parameters:
scan3M (np.ndarray) – 3D scan.
mask3M (np.ndarray) – 3D mask.
method (string) – Padding method. The following methods are supported: ‘expand’ - Image is cropped around the mask and expanded using the specified margin. ‘padzeros’ - Image is padded by zeros. ‘periodic’ - Image is padded with periodic expansion. ‘nearest’ - Image is padded by using values from nearest neighbors. ‘mirror’ - Image is padded by mirrorig the boundary region as per the margin.
marginV (np.array, 1D) – [nRows, nCols, nSlices] in voxels.
cropFlag – [optional, default:True] bool for flag to crop around mask bounding box when set to True.
- Returns:
- ) outScan3M
- outMask3M
outLimitsV
np.ndarray(dtype=int): , maskBoundingBox3M, morphmask3M, gridS, paramS, diagS
- Return type:
np.ndarray(dtype=
- cerr.radiomics.preprocess.unpadScan(padScan3M, marginV)[source]
This function return the image array after stripping off specified padding margin
- Parameters:
padScan3M (np.ndarray) – image to be unpadded
marginV (list) – padding margin for row, col, slc
- Returns:
unpadded image
- Return type:
np.ndarray
- cerr.radiomics.preprocess.getPerIndices(length, lf)[source]
Compute 0-based periodic (wrap-around) index array for wavelet extension.
Constructs the index sequence
[length-lf, ..., length-1, 0, ..., length-1, 0, ..., lf-1](1-based math mapped to 0-based) used to periodically extend an array of length elements by lf elements on each side.- Parameters:
length (int) – Length of the original array to be extended.
lf (int) – Number of extension elements (half the filter length).
- Returns:
- 1-D integer array of 0-based indices into the original array,
of length
length + 2 * lf(approximately).
- Return type:
numpy.ndarray
Note
Replicate periodic indices:
[length-lf+1 : length, 1:length, 1:lf]
- cerr.radiomics.preprocess.wextend(x, padV)[source]
Periodically extend a 1-D or 2-D array for wavelet decomposition.
Ensures an even number of elements along each axis (repeating the last element if needed) and then applies periodic (wrap-around) extension using
getPerIndices().- Parameters:
x (numpy.ndarray) – Input 1-D or 2-D array to extend.
padV (array-like) – Sequence of padding amounts. For a 1-D array, only
padV[0](row padding) is used. For a 2-D array,padV[0]applies to rows andpadV[1]applies to columns.
- Returns:
- Periodically extended copy of x with the same number
of dimensions.
- Return type:
numpy.ndarray
- cerr.radiomics.preprocess.dyadUp(filter1d, evenOdd=1)[source]
Upsample a 1-D filter by interleaving zeros (dyadic upsampling).
Inserts a zero between every pair of consecutive filter coefficients, doubling the length of the array. This is the standard upsampling step in the synthesis bank of a wavelet filter.
- Parameters:
filter1d (array-like) – 1-D filter coefficient array to upsample.
evenOdd (int) –
Controls the zero-insertion pattern.
Odd value (default
1): zeros at odd indices (i.e. original values occupy even-indexed positions0, 2, 4, …).Even value: zeros at even indices (i.e. original values occupy odd-indexed positions
1, 3, 5, …).
- Returns:
- 1-D array of length
2 * len(filter1d)with zeros interleaved according to evenOdd.
- 1-D array of length
- Return type:
numpy.ndarray
- cerr.radiomics.preprocess.preProcessForRadiomics(scanNum, structNum, paramS, planC)[source]
This function applies pre-processing to scanNum as per settings specified in paramS dictionary.
- Parameters:
scanNum (int)
structNum (int)
paramS (dict)
planC (plan_container.planC)
- Returns:
unpadded image np.ndarray(dtype=int): maskBoundingBox3M np.ndarray(dtype=int): tuple: (x,y,z) grid corresponding to the processed image paramS (dictionary): Parameters for pre-processing. diagS (dictionary): Diagnostic features from the region of interest
- Return type:
np.ndarray(dtype=float)
cerr.radiomics.run_length module
This module contains routines for calculation of Run Length texture features
- cerr.radiomics.run_length.calcRLM(quantizedM, offsetsM, nL, rlmType=1)[source]
This function calculates the run-length matrix for the passed quantized image based on IBSI definitions https://ibsi.readthedocs.io/en/latest/03_Image_features.html#grey-level-run-length-based-features
- Parameters:
quantizedM (np.ndarray(dtype=int)) – quantized 3d matrix obtained, for example, from radiomics.preprocess.imquantize_cerr
offsetsM (np.ndarray(dtype=int)) – Offsets for directionality/neighbors, obtained from radiomics.ibsi1.getDirectionOffsets
nL (int) – Number of gray levels. nL must be less than 65535.
rlmType (int) – flag, 1 or 2. 1: returns a single run length matrix by combining contributions from all offsets into one cooccurrence matrix. 2: returns a list of run length matrices, per row row of offsetsM.
- Returns:
- run-length matrix of size (nL x L) for rlmType = 1,
list of size equal to the number of directions for rlmType = 2.
The output can be passed to rlmToScalarFeatures to get RLM texture features.
- Return type:
np.ndarray
- cerr.radiomics.run_length.rlmToScalarFeatures(rlmM, numVoxels)[source]
This function calculates scalar texture features from run length matrix as per IBSI definitions https://ibsi.readthedocs.io/en/latest/03_Image_features.html#grey-level-run-length-based-features
- Parameters:
rlmM (np.ndarray(dtype=int)) – run-length matrix of size (nL x L) for rlmType = 1, list of size equal to the number of directions for rlmType = 2.
- Returns:
- dictionary with scalar texture features as its
fields. Each field’s value is a vector containing the feature values for each list element of rlmM.
- Return type:
dict
cerr.radiomics.shape module
shape module.
The shape module contains routines for calculation of shape features.
- cerr.radiomics.shape.trimeshSurfaceArea(v, f)[source]
Routine to calculate surface area from vertices and faces of triangular mesh
- Parameters:
v (numpy.array) – (numPoints x 3) vertices of triangular mesh
f (numpy.array) – (numFaces x 3) faces of triangular mesh
- Returns:
Surface area
- Return type:
float
- cerr.radiomics.shape.calcMaxDistBetweenPts(ptsM, distType)[source]
This routine calculates the maximum distance between the input points
- Parameters:
ptsM (numpy.array) – (nunPoints x 3) coordinates of points
distType (str or Callable) – Type of distance. E.g. ‘euclidean’ as supported by scipy.spatial.distance.cdist
- Returns:
Maximum distance between the input points
- Return type:
float
- cerr.radiomics.shape.calcShapeFeatures(mask3M, xValsV, yValsV, zValsV, rowColSlcOri)[source]
Routine to calculate shape features for the inout mask and grid
- Parameters:
mask3M (numpy.nparray) – Binary mask where 1s represent the segmentation
xValsV (numpy.nparray) – x-values i.e. coordinates of columns of input mask
yValsV (numpy.nparray) – y-values i.e. coordinates of rows of input mask
zValsV (numpy.nparray) – z-values i.e. coordinates of slices of input mask
rowColSlcOri (str) – string specifying the direction of row, column and slice of mask3M
- Returns:
Dictionary containing shape features
- Return type:
dict
cerr.radiomics.size_zone module
This module contains routines for claculation of Size Zone texture features
- cerr.radiomics.size_zone.calcSZM(quantized3M, nL, szmType)[source]
This function calculates the Size Zone Matrix for the passed quantized image based on IBSI definitions https://ibsi.readthedocs.io/en/latest/03_Image_features.html#grey-level-size-zone-based-features
- Parameters:
quantized3M (np.ndarray(dtype=int)) – quantized 3d matrix obtained, for example, from radiomics.preprocess.imquantize_cerr
nL (int) – Number of gray levels.
szmType – flag, 1 or 2. 1: 3D zones 2: 2D zones
- Returns:
size-zone matrix of size (nL x L)
The output can be passed to szmToScalarFeatures to get SZM texture features.
- Return type:
np.ndarray
- cerr.radiomics.size_zone.szmToScalarFeatures(szmM, numVoxels)[source]
This function calculates scalar texture features from Size Zone Matrix as per IBSI definitions https://ibsi.readthedocs.io/en/latest/03_Image_features.html#grey-level-size-zone-based-features
- Parameters:
szmM (np.ndarray(dtype=int)) – size-zone matrix of size (nL x L)
numVoxels (int) – number of voxels in the region of interest for szmM calculation
- Returns:
- dictionary with scalar texture features as its
fields. Each field’s value is a vector containing the feature values for each list element of rlmM.
- Return type:
dict
cerr.radiomics.texture_filters module
This module contains definitions of image texture filters and a wrapper function to apply any of them. Supported filters include: “mean”, “sobel”, “LoG”, “gabor”, “gabor3d”, “laws”, “lawsEnergy” “rotationInvariantLaws”, “rotationInvariantLawsEnergy”
- cerr.radiomics.texture_filters.meanFilter(scan3M, kernelSize, absFlag=False)[source]
Function to compute patchwise mean on input image using specified kernel size.
- Parameters:
scan3M (np.ndarray) – Input image matrix.
kernelSize (np.array) – Size of filter kernel [nRow, nCol, nSlc].
absFlag (bool) – [optional, default:False] Flag to use absolute intensities.
- Returns:
Mean filter response.
- Return type:
np.ndarray(dtype=float)
- cerr.radiomics.texture_filters.sobelFilter(scan3M)[source]
Function to compute gradient magnitude and direction using Sobel filter.
- Parameters:
scan3M (np.ndarray) – 3D input scan matrix.
- Returns:
gradient magnitude np.ndarray(dtype=float): gradient direction
- Return type:
np.ndarray(dtype=float)
- cerr.radiomics.texture_filters.LoGFilter(scan3M, sigmaV, cutoffV, voxelSizeV)[source]
Function to apply IBSI standard Laplacian of Gaussian (LoG) filter
- Parameters:
scan3M (np.ndarray) – 3D scan matrix.
sigmaV (np.array, 1-D) – Gaussian smoothing widths, [sigmaRows,sigmaCols,sigmaSlc] in mm.
cutoffV (np.array 1-D) – Filter cutoffs [cutOffRow, cutOffCol cutOffSlc] in mm. Note: Filter size = 2.*cutoffV+1
voxelSizeV (np.array, 1-D) – Scan voxel dimensions [dx, dy, dz] in mm.
- Returns:
IBSI-compatible Laplacian of Gaussian filter response.
- Return type:
np.ndarray(dtype=float)
- cerr.radiomics.texture_filters.gaborFilter(scan3M, sigma, wavelength, gamma, thetaV, aggS=None, radius=None, paddingV=None)[source]
Function to apply IBSI standard 2D Gabor filter
- Parameters:
scan3M (np.ndarray) – 3D scan matrix.
sigma (float) – Std. deviation Gaussian envelope in no. voxels.
lambda (float) – wavelength in no. voxels.
gamma (float) – Spatial aspect ratio
thetaV (np.array, 1D) – Orientations in degrees
aggS (dict) – [optional, default=None] Parameters for averaging responses across orientations.
radius (np.array(dtype=int)) – [optional, default=None] Kernel radius in voxels [nRows nCols].
paddingV (np.array, 1D) – [optional, default=None] Amount of padding applied to scan in voxels [nRows nCols].
- Returns:
IBSI-compatible 2D Gabor filter response.
- Return type:
np.ndarray(dtype=float)
- cerr.radiomics.texture_filters.gaborFilter3d()[source]
Function to return Gabor filter responses aggregated across the 3 orthogonal planes (IBSI-compatible)
- Parameters:
scan3M (np.ndarray) – 3D scan array.
sigma (int) – Std. dev. of Gaussian envelope in no. voxels.
lambda (int) – Wavelength in no. voxels.
gamma (float) – Spatial aspect ratio.
thetaV (list(dtype=float)) – Orientations in degrees.
aggS (dict) – Parameters for aggregation of responses across orientations and/or planes.
radius (np.array, 1D) – [optional, default=None] Kernel radii in voxels [nRows, nCols].
paddingV (np.aray, 1D) – [optional, default=None] Amount of padding applied to scan in voxels [nRows nCols].
- Returns:
Gabor filter responses. hGaborPlane (dict): Gabor filter kernels for each plane.
- Return type:
gaborOut (dict)
- cerr.radiomics.texture_filters.get3dLawsMask(x, y, z)[source]
Function to get 3D Laws’ filter kernel (IBSI-compatible)
- Parameters:
x (np.array, 1D) – Supported Laws filter coefficients applied along rows.
y (np.array, 1D) – Supported Laws filter coefficients applied along cols.
z (np.array, 1D) – Supported Laws filter coefficients applied along slices.
- Returns:
3D Laws’ kernel.
- Return type:
conved3M (np.ndarray)
- cerr.radiomics.texture_filters.getLawsMasks()[source]
Function to get Laws filter kernels.
- Parameters:
direction (string) – [optional, default=’all’] specifying ‘2d’, ‘3d’ or ‘All’
filterType (string) – [optional, default=’all’] specifying ‘3’, ‘5’, ‘all’, or a combination of any 2 (if 2d) or 3 (if 3d) of E3, L3, S3, E5, L5, S5.
normFlag (bool) – [optional, default=False] Flag to normalize filter coefficients when True. Normalization ensures average pixel in filtered image is as bright as the average pixel in the original image.
- Returns:
Laws kernels for specified filter types and directions.
- Return type:
lawsMasks (dict)
- cerr.radiomics.texture_filters.lawsFilter(scan3M, direction, filterDim, normFlag)[source]
Function to compute Laws’ filter response (IBSI-compatible)
- Parameters:
scan3M (np.ndarray) – 3D scan.
direction (string) – specifying ‘2d’, ‘3d’ or ‘All’
filterDim (string) – specifying ‘3’, ‘5’, ‘all’, or a combination of any 2 (if 2d) or 3 (if 3d) of E3, L3, S3, E5, L5, S5.
normFlag (bool) – Flag to normalize filter coefficients if True. Normalization ensures average pixel in filtered image is as bright as the average pixel in the original image)
- Returns:
Filter responses for specified filter types and directions.
- Return type:
lawsOut (dict)
- cerr.radiomics.texture_filters.energyFilter(tex3M, mask3M, texPadFlag, texPadSizeV, texPadMethod, energyKernelSizeV, energyPadSizeV, energyPadMethod)[source]
Function to compute energy (local mean of absolute intensities)
- Parameters:
tex3M (np.ndarray(dtype=float)) – Input filter response map
mask3M (np.ndarray(dtype=bool)) – Processed mask returned by radiomics.preprocess.
texPadFlag (bool) – Flag to indicate if padding was applied to compute Laws filter response.
texPadSizeV (np.array(dtype=int)) – Amount of padding applied to compute tex3M
texPadMethod (string) – Padding method applied prior to compute tex3M
energyKernelSizeV (np.array(dtype=int)) – Patch size used to calculate local energy [numRows numCols num_slc] in voxels.
energyPadMethod (string) – Padding method applied to calculate local energy.
energyPadSizeV – np.array(dtype=int) for amount padding applied to calculate local energy [numRows numCols num_slc] in voxels.
- Returns:
Energy filter response.
- Return type:
texEnergyPad3M (np.ndarray(dtype=float))
- cerr.radiomics.texture_filters.lawsEnergyFilter(scan3M, mask3M, direction, filterDim, normFlag, lawsPadFlag, lawsPadSizeV, lawsPadMethod, energyKernelSizeV, energyPadSizeV, energyPadMethod)[source]
Function to compute local mean of absolute values of laws filter response
- Args:
scan3M (np.ndarray): 3D scan. mask3M (np.ndarray(dtype=bool)): 3D mask. direction (string): Specifying ‘2d’, ‘3d’ or ‘All’. filterDim (string: Specifying ‘3’, ‘5’, ‘all’, or a combination
of any 2 (if 2d) or 3 (if 3d) of E3, L3, S3, E5, L5, S5.
- normFlag (bool): Flag to normalize kernel coefficients if set to True.
Normalization ensures average pixel in filtered image is as bright as the average pixel in the original image.
- lawsPadFlag (bool): Flag to indicate if padding was applied to compute
Laws filter response.
- lawsPadSizeV (np.array(dtype=int)): Amount of padding applied to compute Laws
filter response.
lawsPadMethod (string): Padding method applied to compute Laws filter response. energyKernelSizeV (np.array(dtype=int)): Patch size used to calculate local energy
[numRows numCols num_slc] in voxels.
- energyPadMethod (np.array(dtype=int)): Padding method applied to
calculate local energy.
- energyPadSizeV (np.array(dtype=int)): Amount padding applied to
calculate local energy [numRows numCols num_slc] in voxels.
- Returns:
Filter responses for specified directions and filter types.
- Return type:
outS (dict)
- cerr.radiomics.texture_filters.rotationInvariantLawsFilter(scan3M, direction, filterDim, normFlag, rotS)[source]
Function to return rotation-invariant Laws filter response.
- Parameters:
scan3M (np.ndarray) – 3D scan.
direction (string) – Specifying ‘2d’, ‘3d’ or ‘All’.
filterDim (string) – Specifying ‘3’, ‘5’, ‘all’, or a combination of any 2 (if 2d) or 3 (if 3d) of E3, L3, S3, E5, L5, S5.
normFlag (bool) – Flag to normalize kernel coefficients if set to True. Normalization ensures average pixel in filtered image is as bright as the average pixel in the original image
rotS (dict) – Parameters for aggregating filter response across different orientations
- Returns:
- Laws filter response aggregated
across orientations as specified.
- Return type:
out3M (np.ndarray(dtype=float))
- cerr.radiomics.texture_filters.rotationInvariantLawsEnergyFilter(scan3M, mask3M, direction, filterDim, normFlag, lawsPadFlag, lawsPadSizeV, lawsPadMethod, energyKernelSizeV, energyPadSizeV, energyPadMethod, rotS)[source]
Function to return rotation-invariant Laws energy response.
- Parameters:
scan3M (np.ndarray) – 3D scan.
direction (string) – Specifying ‘2d’, ‘3d’ or ‘All’.
filterDim (string) – Specifying ‘3’, ‘5’, ‘all’, or a combination of any 2 (if 2d) or 3 (if 3d) of E3, L3, S3, E5, L5, S5.
normFlag (bool) – Flag to normalize kernel coefficients if set to True. Normalization ensures average pixel in filtered image is as bright as the average pixel in the original image
lawsPadFlag (bool) – Flag to indicate if padding was applied to compute Laws filter response.
lawsPadSizeV (np.array(dtype=int)) – Amount of padding applied to compute Laws filter response.
lawsPadMethod (string) – Padding method applied to compute Laws filter response.
energyKernelSizeV (np.array(dtype=int)) – Patch size used to calculate local energy [numRows numCols num_slc] in voxels.
energyPadMethod (np.array(dtype=int)) – Padding method applied to calculate local energy.
energyPadSizeV (np.array(dtype=int)) – Amount padding applied to calculate local energy [numRows numCols num_slc] in voxels.
rotS (dict) – Parameters for aggregating filter response across different orientations
- Returns:
- Energy of Laws filter response
aggregated across orientations as specified.
- Return type:
lawsEnergyAggPad3M (np.ndarray(dtype=float))
- cerr.radiomics.texture_filters.wkeep(z, size, first)[source]
Keep central segment of signal after convolution Args
z (np.array) : Convolved signal size (tuple) : Dimensions of original signal first: (int) : Start index
- Returns
Central segment of signal after convolution
- cerr.radiomics.texture_filters.swt(sigV, level, loD, hiD)[source]
Replicates MATLAB’s swt 1D behavior using custom filters and symmetric padding. :param sigV: 1D signal :type sigV: np.array :param level: No. of decomposition levels :type level: int :param loD: Low-pass decomposition filter :type loD: np.array :param hiD: High-pass decomposition filter :type hiD: np.array
- Returns:
list of approximation coefficients per level H: list of detail coefficients per level
- Return type:
L
- cerr.radiomics.texture_filters.swt2(imgM, level, loD, hiD)[source]
- Parameters:
imgM (np.float64) – 2D image
level (int) – No. of decomposition levels
loD (np.array) – Low-pass decomposition filter
hiD (np.array) – High-pass decomposition filter
- Returns:
list of approximation coefficients per level h: list of horizontal wavelet coefficients per level v: list of vertical wavelet coefficients per level d: list of diagonal wavelet coefficients per level
- Return type:
a
- cerr.radiomics.texture_filters.getWaveletSubbands()[source]
Copyright (C) 2017-2019 Martin Vallières All rights reserved. https://github.com/mvallieres/radiomics-develop ———————————————————————— IMPORTANT: - THIS FUNCTION IS TEMPORARY AND NEEDS BENCHMARKING. ALSO, IT ONLY WORKS WITH AXIAL SCANS FOR NOW. USING DICOM CONVENTIONS(NOT MATLAB). - Strategy: 2D transform for each axial slice. Then 1D transform for each r axial line. I need to find a faster way to do that with 3D convolutions of wavelet filters, this is too slow now. Using GPUs would be ideal. ————————————————————————
- cerr.radiomics.texture_filters.waveletFilter(vol3M, waveType, direction, level, rotInvFlag=False)[source]
Function to return wavelet filter response.
- Parameters:
vol3M (np.ndarray) – 3D scan.
waveType (string) – Wavelet name. Supported options include ‘haar’, ‘db’ (Daubechies), ‘sym’ (Symlets), ‘coif’ (Coiflets), ‘bior’, (Biorthogonal), and ‘rbio’ (Reverse biorthogonal).
direction (string) – Filter sequence. May be :’HHH’, ‘LHH’, ‘HLH’, ‘HHL’, ‘LLH’, ‘LHL’, ‘HLL’, ‘LLL’ or ‘All’.
level (int) – Wavelet level. Supported: 1.
rotInvFlag (bool) – Set to True for rotation-invariant filtering (default:False).
- Returns:
- Laws filter response aggregated
across orientations as specified.
- Return type:
out3M (np.ndarray(dtype=float))
- cerr.radiomics.texture_filters.rotationInvariantWaveletFilter(scan3M, waveType, direction, level, rotS)[source]
Function to return rotation-invariant Wavelet filter response.
- Parameters:
scan3M (np.ndarray) – 3D scan.
direction (string) – Specifying ‘2d’, ‘3d’ or ‘All’.
filterDim (string) – Specifying ‘3’, ‘5’, ‘all’, or a combination of any 2 (if 2d) or 3 (if 3d) of E3, L3, S3, E5, L5, S5.
normFlag (bool) – Flag to normalize kernel coefficients if set to True. Normalization ensures average pixel in filtered image is as bright as the average pixel in the original image
rotS (dict) – Parameters for aggregating filter response across different orientations
- Returns:
- Laws filter response aggregated
across orientations as specified.
- Return type:
out3M (np.ndarray(dtype=float))
- cerr.radiomics.texture_filters.getMatchFields(dictIn, *args)[source]
Return vals in list of dictionaries matching input key
- cerr.radiomics.texture_filters.aggregateRotatedResponses(rotTexture, aggregationMethod)[source]
Function to aggregate textures from all orientations.
- Parameters:
rotTexture – list of filter response maps to be aggregated, computed at different orientations.
aggregationMethod – string for aggregation method. May be ‘avg’,’max’, or ‘std’.
- Returns:
Aggregated response map.
- cerr.radiomics.texture_filters.rot3d90(arr3M, axis, angle)[source]
Function to rotate a 3D array 90 degrees around a specified axis.
- Parameters:
arr3M (np.ndarray) – 3D scan.
axis (int) – Axis around which to rotate the array.
angle (float) – Angle of rotation in degrees.
- Returns:
Rotated scan.
- Return type:
rotArr3M (np.ndarray)
- cerr.radiomics.texture_filters.rotate3dSequence(vol3M, index, sign)[source]
Function to apply pre-defined sequence of right angle rotations to 2D/3D arrays
- Parameters:
vol3M (np.ndarray) – 3D scan.
index (int) – Multiplicative factor of 90 degrees.
sign (int) – Indicate direction of rotation (+1 or -1).
- Returns:
Rotated scan.
- Return type:
rotArr3M (np.ndarray)
- cerr.radiomics.texture_filters.flipSequenceForWavelets(vol3M, index, sign)[source]
Function to flip 2D or 3D arrays by 180 degrees around a specified axis. :param vol3M: 3D scan. :type vol3M: np.ndarray :param index: Flip index from (0,1,2…,7) :type index: int :param sign: +1 or -1 (-1 to reverse order of flips).
- cerr.radiomics.texture_filters.rotationInvariantFilt(scan3M, mask3M, filter, *params)[source]
Function to apply filter over a range of orientations to approximate rotation invariant filter.
- Parameters:
scan3M (np.ndarray) – 3D scan.
mask3M (np.ndarray(dtype=bool)) – 3D mask.
filter (dict) – Filter names and associated parameters.
params (dict) – Dictionary of filter parameters
- Returns:
Rotation -invariant filter responses.
- Return type:
aggS (dict)
cerr.radiomics.texture_utils module
- cerr.radiomics.texture_utils.loadSettingsFromFile(settingsFile, scanNum=None, planC=None)[source]
Function to load filter parameters from user-input JSON.
- Parameters:
settingsFile (string) – Path to JSON file.
scanNum (int) – [optional, default=None] Scan no. from which to extract additional parameters like voxel size.
planC (plan_container.planC) – [optional, default=None] pyCERR’s plan container object.
- Returns:
Radiomics parameters parsed from JSON file. filterTypes (list): Texture filters specified in JSON file.
- Return type:
paramS (dict)
- cerr.radiomics.texture_utils.processImage(filterType, scan3M, mask3M, paramS)[source]
Function to process scan using selected filter and parameters :param filterType: Name of supported filter. :type filterType: string :param scan3M: 3D scan. :type scan3M: np.ndarray :param mask3M: 3D binary mask. :type mask3M: np.ndarray(dtype=bool) :param paramS: Parameters (read from JSON). :type paramS: dict
- Returns:
Containing response maps for each filter type.
- Return type:
outS(dict)
- cerr.radiomics.texture_utils.generateTextureMapFromPlanC(planC, scanNum, strNum, configFilePath)[source]
Function to filter scan and import result to planC.
- Parameters:
planC – pyCERR’s plan container object.
scanNum – int for index of scan to be filtered.
strNum – int for index of ROI.
configFilePath – string for path to JSON config file with filter parameters.
- Returns:
pyCERR plan_container object with texture map as pseudo-scan.
- Return type:
planC (plan_container.planC)