HandCraftedFeatures Module¶
Provides methods for extracting and working with hand-crafted features from data.
This module provides functions for calculating handcrafted features from images and their masks (if existing).
Note
All functions in this module are authored by me and shared publicly mainly for educational purposes.
References
YouTube Playlist: For detailed explanations and demonstrations of the functions, refer to the following playlist: Handcrafted Features Tutorial
GitHub Repository: For practical examples and code implementations, visit the repository: BE-645 Artificial Intelligence and Radiomics
- Usage:
These functions are designed to extract meaningful features from images, which can be used in various applications such as image analysis, machine learning, and radiomics.
- HMB.HandCraftedFeatures.FirstOrderFeatures2D(img, mask, isNorm=True, ignoreZeros=True)[source]¶
Calculate first-order statistical features from an image using a mask.
- Parameters:
img (numpy.ndarray) – The input image as a 2D NumPy array.
mask (numpy.ndarray) – The binary mask as a 2D NumPy array.
isNorm (bool) – Flag to indicate whether to normalize the histogram.
ignoreZeros (bool) – Flag to indicate whether to ignore zeros in the histogram.
- Returns:
- A tuple containing:
dict: A dictionary containing the calculated first-order features.
numpy.ndarray: The histogram of the pixel values in the region of interest.
- Return type:
- HMB.HandCraftedFeatures.FirstOrderFeatures2DV2(data, isNorm=True, ignoreZeros=True)[source]¶
Calculate first-order statistical features from an image using a mask.
- Parameters:
data (numpy.ndarray) – The input image as a 2D NumPy array.
isNorm (bool) – Flag to indicate whether to normalize the histogram.
ignoreZeros (bool) – Flag to indicate whether to ignore zeros in the histogram.
- Returns:
- A tuple containing:
dict: A dictionary containing the calculated first-order features.
numpy.ndarray: The histogram of the pixel values in the region of interest.
- Return type:
- HMB.HandCraftedFeatures.CalculateGLCMCooccuranceMatrix(image, d, theta, isSymmetric=False, isNorm=True, ignoreZeros=True, epsilon=1e-06)[source]¶
Calculate the Gray-Level Co-occurrence Matrix (GLCM) for a given image.
- Parameters:
image (numpy.ndarray) – The input image as a 2D NumPy array.
d (int) – The distance between pixel pairs.
theta (float) – The angle (in radians) for the direction of pixel pairs.
isSymmetric (bool) – Whether to make the GLCM symmetric. Default is False.
isNorm (bool) – Whether to normalize the GLCM. Default is True.
ignoreZeros (bool) – Whether to ignore zero-valued pixels. Default is True.
epsilon (float) – A small value to avoid division by zero during normalization. Default is 1e-6.
- Returns:
The calculated GLCM.
- Return type:
coMatrix (numpy.ndarray)
- Raises:
ValueError – If the distance ‘d’ is less than 1 or greater than or equal to the number of unique intensity levels.
- HMB.HandCraftedFeatures.CalculateGLCMCooccuranceMatrix3D(volume, d, theta, isSymmetric=False, isNorm=True, ignoreZeros=True, epsilon=1e-06)[source]¶
Calculate the 3D Gray-Level Co-occurrence Matrix (GLCM) for a given volume.
- Parameters:
volume (numpy.ndarray) – The 3D volume as a NumPy array.
d (int) – The distance between voxel pairs.
theta (float) – The angle (in radians) for the direction of voxel pairs.
isSymmetric (bool) – Whether to make the GLCM symmetric. Default is False.
isNorm (bool) – Whether to normalize the GLCM. Default is True.
ignoreZeros (bool) – Whether to ignore zero-valued voxels. Default is True.
epsilon (float) – A small value to avoid division by zero during normalization. Default is 1e-6.
- Returns:
The calculated GLCM.
- Return type:
coMatrix (numpy.ndarray)
- Raises:
ValueError – If the distance ‘d’ is less than 1, greater than or equal to the number of slices, or greater than or equal to the number of unique intensity levels.
- HMB.HandCraftedFeatures.CalculateGLCMFeaturesOptimized(coMatrix)[source]¶
Calculate texture features from a Gray-Level Co-occurrence Matrix (GLCM).
- Parameters:
coMatrix (numpy.ndarray) – The GLCM as a 2D NumPy array.
- Returns:
- A dictionary containing the calculated texture features. This includes:
Energy: Measure of textural uniformity.
Contrast: Measure of local intensity variation.
Homogeneity: Measure of closeness of the distribution of elements in the GLCM to the GLCM diagonal.
Entropy: Measure of randomness in the texture.
Correlation: Measure of how correlated a pixel is to its neighbor over the whole image.
Dissimilarity: Measure of how different the elements of the GLCM are from each other.
TotalSum: Sum of all elements in the GLCM.
MeanX: Mean of the rows in the GLCM.
MeanY: Mean of the columns in the GLCM.
StdDevX: Standard deviation of the rows in the GLCM.
StdDevY: Standard deviation of the columns in the GLCM.
- Return type:
- HMB.HandCraftedFeatures.CalculateGLRLMRunLengthMatrix(matrix, theta, isNorm=True, ignoreZeros=True, epsilon=1e-06)[source]¶
Calculate the Gray-Level Run-Length Matrix (GLRLM) for a given 2D matrix. The GLRLM is a statistical tool used to quantify the texture of an image by analyzing the runs of pixels with the same intensity level in a specific direction.
- Parameters:
matrix (numpy.ndarray) – A 2D matrix representing the image or data for which the GLRLM is to be calculated.
theta (float) – The angle (in radians) specifying the direction in which runs are to be analyzed. The direction is determined by the cosine and sine of this angle.
isNorm (bool) – If True, the resulting GLRLM is normalized by dividing by the total number of runs. Normalization ensures that the matrix represents probabilities rather than counts. Default is True.
ignoreZeros (bool) – If True, runs with zero intensity are ignored in the calculation of the GLRLM. This is useful when zero values represent background or irrelevant data. Default is True.
epsilon (float) – A small value added to the denominator during normalization to prevent division by zero. Default is 1e-6.
- Returns:
A 2D matrix representing the Gray-Level Run-Length Matrix. The rows correspond to intensity levels, and the columns correspond to run lengths. If isNorm is True, the matrix is normalized.
- Return type:
- HMB.HandCraftedFeatures.CalculateGLRLMFeatures(rlMatrix, image)[source]¶
Calculate texture features from a Gray-Level Run-Length Matrix (GLRLM). This function computes various texture features based on the GLRLM, which is derived from an image. These features are commonly used in texture analysis and image processing.
- Parameters:
rlMatrix (numpy.ndarray) – A 2D Gray-Level Run-Length Matrix (GLRLM) computed from an image. The rows represent intensity levels, and the columns represent run lengths.
image (numpy.ndarray) – The original 2D image from which the GLRLM was derived. This is used to determine the number of gray levels and the total number of pixels.
- Returns:
- A dictionary containing the following texture features:
”Short Run Emphasis” : Emphasizes short runs in the image.
”Long Run Emphasis” : Emphasizes long runs in the image.
”Gray Level Non-Uniformity” : Measures the variability of gray levels.
”Run Length Non-Uniformity” : Measures the variability of run lengths.
”Run Percentage” : Ratio of runs to the total number of pixels.
”Low Gray Level Run Emphasis” : Emphasizes runs with low gray levels.
”High Gray Level Run Emphasis”: Emphasizes runs with high gray levels.
- Return type:
- HMB.HandCraftedFeatures.CalculateGLRLMRunLengthMatrix3D(volume, theta, isNorm=True, ignoreZeros=True, epsilon=1e-06)[source]¶
Calculate 3D Gray-Level Run-Length Matrix (GLRLM) for volumetric texture analysis.
- Parameters:
volume (numpy.ndarray) – 3D array of intensity values (z, y, x dimensions).
theta (float) – Analysis angle in radians determining 3D direction vector.
isNorm (bool) – Enable matrix normalization to probability distribution. Default is True.
ignoreZeros (bool) – Exclude zero-valued voxels from run calculations. Default is True.
epsilon (float) – Small value to prevent division by zero during normalization. Default is 1e-6.
- Returns:
2D matrix of size (intensity levels × max run length).
- Return type:
rlMatrix (numpy.ndarray)
- HMB.HandCraftedFeatures.FindConnectedRegions(image, connectivity=4)[source]¶
Finds connected regions in a 2D image based on pixel connectivity.
- Parameters:
image (numpy.ndarray) – A 2D NumPy array representing the input image. Each element represents a pixel value.
connectivity (int) – The type of connectivity to use for determining connected regions. Options are (a) 4 for 4-connectivity (up, down, left, right) and (b) 8 for 8-connectivity (includes diagonals).
- Returns:
A dictionary where keys are unique pixel values from the image, and values are lists of sets. Each set contains the coordinates (i, j) of pixels belonging to a connected region for that pixel value.
- Return type:
- HMB.HandCraftedFeatures.CalculateGLSZMSizeZoneMatrix(image, connectivity=4, isNorm=False, ignoreZeros=False, epsilon=1e-06)[source]¶
Calculate the Size-Zone Matrix for a given image based on connected regions.
- Parameters:
image (numpy.ndarray) – A 2D NumPy array representing the input image. Each element represents a pixel value.
connectivity (int) – The type of connectivity to use for determining connected regions. Options are (a) 4 for 4-connectivity (up, down, left, right) and (b) 8 for 8-connectivity (includes diagonals).
isNorm (bool) – Whether to normalize the size-zone matrix.
ignoreZeros (bool) – Whether to ignore zero pixel values.
epsilon (float) – A small value to avoid division by zero during normalization. Default is 1e-6.
- Returns:
- A tuple containing:
szMatrix (numpy.ndarray): A 2D NumPy array representing the Size-Zone Matrix.
szDict (dict): A dictionary where keys are unique pixel values from the image, and values are lists of sets. Each set contains the coordinates (i, j) of pixels belonging to a connected region for that pixel value.
N (int): The number of unique pixel values in the image.
Z (int): The maximum size of any region in the dictionary.
- Return type:
- Raises:
ValueError – If the input image is not 2D, if connectivity is not 4 or 8, if the image is empty, or if the image is completely black.
- HMB.HandCraftedFeatures.CalculateGLSZMFeatures(szMatrix, data, N, Z, epsilon=1e-06)[source]¶
Calculate the features of the Size-Zone Matrix (GLSZM).
- Parameters:
szMatrix (numpy.ndarray) – A 2D NumPy array representing the Size-Zone Matrix.
data (numpy.ndarray) – The original 2D image data from which the GLSZM was derived.
N (int) – The number of unique pixel values in the image.
Z – The maximum size of any region in the dictionary.
- Returns:
- A dictionary containing the calculated features. This includes:
”Small Zone Emphasis (SZE)”: Emphasizes small zones in the image.
”Large Zone Emphasis (LZE)”: Emphasizes large zones in the image.
”Gray Level Non-Uniformity (GLN)”: Measures the variability of gray levels.
”Zone Size Non-Uniformity (ZSN)”: Measures the variability of zone sizes.
”Zone Percentage (ZP)”: Ratio of zones to the total number of pixels.
”Gray Level Variance (GLV)”: Measures the variance of gray levels.
”Zone Size Variance (ZSV)”: Measures the variance of zone sizes.
”Zone Size Entropy (ZSE)”: Measures the randomness of zone sizes.
”Low Gray Level Zone Emphasis (LGZE)”: Emphasizes zones with low gray levels.
”High Gray Level Zone Emphasis (HGZE)”: Emphasizes zones with high gray levels.
”Small Zone Low Gray Level Emphasis (SZLGE)”: Emphasizes small zones with low gray levels.
”Small Zone High Gray Level Emphasis (SZHGE)”: Emphasizes small zones with high gray levels.
”Large Zone Low Gray Level Emphasis (LZGLE)”: Emphasizes large zones with low gray levels.
”Large Zone High Gray Level Emphasis (LZHGE)”: Emphasizes large zones with high gray levels.
- Return type:
- HMB.HandCraftedFeatures.FindConnectedRegions3D(volume, connectivity=6)[source]¶
Finds connected regions in a 3D volume based on pixel connectivity.
- Parameters:
volume (numpy.ndarray) – A 3D NumPy array representing the input volume.
connectivity (int) – The type of connectivity to use for determining connected regions. Options are (a) 6: 6-connectivity (faces only) and (b) 26: 26-connectivity (faces, edges, and corners).
- Returns:
A dictionary where keys are unique pixel values from the volume, and values are lists of sets. Each set contains the coordinates (i, j, k) of pixels belonging to a connected region for that pixel value.
- Return type:
- HMB.HandCraftedFeatures.CalculateGLSZMSizeZoneMatrix3D(volume, connectivity=6, isNorm=True, ignoreZeros=True, epsilon=1e-06)[source]¶
Calculate the Size-Zone Matrix for a 3D volume based on connected regions.
- Parameters:
volume (numpy.ndarray) – A 3D NumPy array representing the input volume.
connectivity (int) – The type of connectivity to use for determining connected regions. Options are (a) 6 for 6-connectivity (faces only) and (b) 26 for 26-connectivity (faces, edges, and corners). Default is 6.
isNorm (bool) – Whether to normalize the size-zone matrix. Default is True.
ignoreZeros (bool) – Whether to ignore zero pixel values. Default is True.
epsilon (float) – A small value to avoid division by zero during normalization. Default is 1e-6.
- Returns:
- A tuple containing the following elements:
szMatrix (numpy.ndarray): A 2D NumPy array representing the Size-Zone Matrix.
szDict (dict): A dictionary where keys are unique pixel values from the volume, and values are lists of sets. Each set contains the coordinates (i, j, k) of pixels belonging to a connected region for that pixel value.
N (int): The number of unique pixel values in the volume.
Z (int): The maximum size of any region in the dictionary.
- Return type:
- Raises:
ValueError – If the input volume is not a 3D array, if connectivity is not 6 or 26, if the input volume is empty, or if the input volume is completely black.
- HMB.HandCraftedFeatures.BuildLBPKernel(distance=1, theta=135, isClockwise=False)[source]¶
Build a kernel matrix for Local Binary Pattern (LBP) computation. The kernel is generated based on the specified distance and angle (theta). The kernel is a square matrix of size (2 * distance + 1) x (2 * distance + 1). The kernel is filled with powers of 2, representing the weights of the pixels in the LBP computation. The kernel is rotated by the specified angle (theta) in a clockwise or counterclockwise direction.
- Parameters:
- Returns:
A kernel matrix representing the LBP pattern weights.
- Return type:
- Raises:
ValueError – If the distance is less than 1, or if theta is not in the range [0, 360], or if theta is not a multiple of the angle between elements.
- HMB.HandCraftedFeatures.LocalBinaryPattern2D(matrix, distance=1, theta=135, isClockwise=False, normalizeLBP=False)[source]¶
Compute the Local Binary Pattern (LBP) matrix for a given 2D matrix. This function calculates the LBP values based on the specified distance, angle (theta), and direction (clockwise or counterclockwise). The LBP is a texture descriptor that encodes local patterns in the image, making it useful for various image analysis tasks.
- Parameters:
matrix (numpy.ndarray) – Input 2D matrix (grayscale) for LBP computation.
distance (int) – Distance from the center pixel to the surrounding pixels.
theta (int) – Angle in degrees for the LBP computation (must be a multiple of 45).
isClockwise (bool) – Direction of LBP computation (True for clockwise, False for counterclockwise).
normalizeLBP (bool) – Flag to normalize the LBP values (default is False).
- Returns:
LBP matrix with the same shape as the input image, containing LBP values.
- Return type:
- Raises:
ValueError – If the distance is less than 1, exceeds half of the image dimensions, or if the angle (theta) is outside the valid range (0 to 360 degrees).
- HMB.HandCraftedFeatures.UniformLocalBinaryPattern2D(matrix, distance=1, theta=135, isClockwise=False, normalizeLBP=False)[source]¶
Compute the Uniform Local Binary Pattern (LBP) matrix for a given 2D matrix. This function calculates the LBP values based on the specified distance, angle (theta), and direction (clockwise or counterclockwise). The Uniform LBP is a variant of LBP that focuses on uniform patterns, making it useful for texture analysis and classification tasks. The uniform patterns are defined as those with at most two transitions between 0 and 1 in the binary representation of the LBP value.
- Parameters:
matrix (numpy.ndarray) – Input 2D matrix (grayscale) for LBP computation.
distance (int) – Distance from the center pixel to the surrounding pixels.
theta (int) – Angle in degrees for the LBP computation (must be a multiple of 45).
isClockwise (bool) – Direction of LBP computation (True for clockwise, False for counterclockwise).
normalizeLBP (bool) – Flag to normalize the LBP values (default is False).
- Returns:
Uniform LBP matrix with the same shape as the input image, containing LBP values.
- Return type:
- HMB.HandCraftedFeatures.ComputeHogImage(imgGray, pixelsPerCell=(8, 8), orientations=9, eps=1e-05)[source]¶
Compute a HOG-like visualization image from a grayscale input image.
- Parameters:
imgGray (numpy.ndarray) – Input grayscale image as a 2D NumPy array.
pixelsPerCell (tuple) – Size of each cell in pixels (height, width).
orientations (int) – Number of orientation bins for the histogram.
eps (float) – Small value to avoid division by zero during normalization.
- Returns:
HOG visualization image as a 2D NumPy array (uint8).
- Return type:
- HMB.HandCraftedFeatures.ComputeGaborResponses(imgGray, scales=3, orientations=4, ksize=31, sigma=None, gamma=0.5, psi=0)[source]¶
Compute Gabor filter bank responses for a grayscale image.
- Parameters:
imgGray (numpy.ndarray) – Input grayscale image as a 2D NumPy array.
scales (int) – Number of scales (wavelengths) for the Gabor filters.
orientations (int) – Number of orientations for the Gabor filters.
ksize (int) – Size of the Gabor kernel (must be odd).
sigma (float or None) – Standard deviation of the Gaussian envelope. If None, a default heuristic is used.
gamma (float) – Spatial aspect ratio of the Gabor filter.
psi (float) – Phase offset of the Gabor filter in radians.
- Returns:
A list of tuples, each containing (scaleIndex, orientationIndex, responseImage).
- Return type:
- HMB.HandCraftedFeatures.ComputeLPQImage(imgGray, winSize=7)[source]¶
Compute the Local Phase Quantization (LPQ) code image from a grayscale input image.
- Parameters:
imgGray (numpy.ndarray) – Input grayscale image as a 2D NumPy array.
winSize (int) – Size of the local window (must be odd).
- Returns:
LPQ code image as a 2D NumPy array (uint8).
- Return type:
- HMB.HandCraftedFeatures.ComputeSobelMaps(imgGray, ksize=3)[source]¶
Compute Sobel gradient magnitude and angle maps from a grayscale image.
- Parameters:
imgGray (numpy.ndarray) – Input grayscale image as a 2D NumPy array.
ksize (int) – Size of the Sobel kernel (must be odd and positive).
- Returns:
- A tuple containing two 2D NumPy arrays (magN, angN) as uint8 images.
magN (numpy.ndarray): Gradient magnitude map (uint8).
angN (numpy.ndarray): Gradient angle map (uint8), mapped to [0, 255].
- Return type:
- HMB.HandCraftedFeatures.ComputeCanny(imgGray, lowThresh=50, highThresh=150, apertureSize=3)[source]¶
Compute Canny edge map from a grayscale image.
- Parameters:
imgGray (numpy.ndarray) – Input grayscale image as a 2D NumPy array.
lowThresh (int) – Lower threshold for hysteresis.
highThresh (int) – Upper threshold for hysteresis.
apertureSize (int) – Aperture size for the Sobel operator (must be odd).
- Returns:
Canny edge map as a binary uint8 image.
- Return type:
- HMB.HandCraftedFeatures.ComputeLocalEntropy(imgGray, winSize=9)[source]¶
Compute local entropy map from a grayscale image.
- Parameters:
imgGray (numpy.ndarray) – Input grayscale image as a 2D NumPy array.
winSize (int) – Size of the local neighborhood window (must be odd).
- Returns:
Local entropy map as a uint8 image.
- Return type:
- HMB.HandCraftedFeatures.ComputeDistanceTransform(maskImg, signed=True)[source]¶
Compute signed or unsigned distance transform from a binary mask image.
- Parameters:
maskImg (numpy.ndarray) – Input binary mask image as a 2D NumPy array.
signed (bool) – Flag to compute signed distance (True) or unsigned distance (False).
- Returns:
Distance transform image as a uint8 image (0..255).
- Return type:
- HMB.HandCraftedFeatures.ComputeCLAHE(imgGray, clipLimit=2.0, tileGridSize=(8, 8))[source]¶
Compute CLAHE (Contrast Limited Adaptive Histogram Equalization) enhanced image.
- Parameters:
imgGray (numpy.ndarray) – Input grayscale image as a 2D NumPy array.
clipLimit (float) – Threshold for contrast limiting.
tileGridSize (tuple) – Size of grid for histogram equalization (height, width).
- Returns:
CLAHE enhanced image as a 2D NumPy array (uint8).
- Return type:
- HMB.HandCraftedFeatures.ShapeFeatures2D(matrix)[source]¶
Calculate shape features of a given binary matrix in 2D. The function computes various shape features such as area, perimeter, centroid, bounding box, aspect ratio, compactness, eccentricity, convex hull area, extent, solidity, major and minor axis lengths, orientation, and roundness.
- Parameters:
matrix (numpy.ndarray) – A binary 2D NumPy array representing the shape.
- Returns:
- A dictionary containing the calculated shape features. This includes:
Area: The number of non-zero pixels in the matrix.
Perimeter: The perimeter of the largest contour in the matrix.
Centroid: The coordinates of the centroid of the shape.
Bounding Box: The bounding box of the shape in the format (x, y, w, h).
Aspect Ratio: The ratio of width to height of the bounding box.
Compactness: A measure of how compact the shape is.
Eccentricity: A measure of how elongated the shape is.
Convex Hull Area: The area of the convex hull of the shape.
Extent: The ratio of the area of the shape to the area of its bounding box.
Solidity: The ratio of the area of the shape to the area of its convex hull.
Major Axis Length: The length of the major axis of the shape.
Minor Axis Length: The length of the minor axis of the shape.
Orientation: The orientation angle of the major axis of the shape.
Roundness: A measure of how round the shape is.
Symmetry: A measure of the symmetry of the shape.
Elongation: The ratio of the major axis length to the minor axis length.
Thinness Ratio: The ratio of the square of the perimeter to the area.
Convexity: The ratio of the perimeter of the convex hull to the perimeter of the shape.
Sparseness: A measure of how spread out the shape is.
Curvature: A measure of how sharply the contour bends at each point.
- Return type:
- Raises:
ValueError – If the input matrix is empty or not a valid binary image.
- HMB.HandCraftedFeatures.ShapeFeatures3D(volume)[source]¶
Calculate 3D shape features of a given binary or labeled volume. The function computes various geometric and topological properties such as volume, surface area, compactness, sphericity, elongation, flatness, rectangularity, spherical disproportion, and Euler number. These features are derived from the mesh representation of the input volume using marching cubes.
- Parameters:
volume (numpy.ndarray) – A 3D binary or labeled matrix representing the object.
- Returns:
- A dictionary containing the calculated 3D shape features. This includes:
Volume: Total number of non-zero voxels in the volume.
Surface Area: Total surface area of the mesh generated by marching cubes.
Surface to Volume Ratio: Ratio of surface area to volume.
Compactness: A measure of how closely the shape resembles a sphere.
Sphericity: A measure of how spherical the shape is.
Elongation: Ratio of the longest dimension to the shortest dimension of the bounding box.
Flatness: Ratio of the shortest dimension to the intermediate dimension of the bounding box.
Rectangularity: Ratio of volume to bounding box volume.
Euler Number: Topological characteristic of the shape.
- Return type: