Modules
SilentInfarctionSegmentationFLAIR.histograms module
Created on 2025-08-11 17:18:09
@author: david
- SilentInfarctionSegmentationFLAIR.histograms.gaussian_smooth_histogram(hist, sigma=3, ax=None)[source]
Smooth a histogram using a Gaussian kernel.
- Parameters:
hist (tuple) – Tuple
(counts, bin_edges)fromnp.histogram.sigma (float, optional) – Standard deviation of the Gaussian kernel.
ax (matplotlib.axes.Axes, optional) – Axis on which to draw.
- Returns:
smooth_hist – Smoothed histogram
(counts, bin_edges).- Return type:
tuple
- SilentInfarctionSegmentationFLAIR.histograms.histogram_stats(hist, q1=25, q2=75)[source]
Compute descriptive statistics from a histogram.
- Parameters:
hist (tuple) – Tuple
(counts, bin_edges)fromnp.histogram.q1 (float, optional) – First percentile (default 25).
q2 (float, optional) – Second percentile (default 75).
- Returns:
(mean, p1, p2, variance, skewness, kurtosis).- Return type:
tuple
- SilentInfarctionSegmentationFLAIR.histograms.mode_and_rhwhm(hist, ax=None)[source]
Compute the mode and right-side half-width at half-maximum (HWHM).
- Parameters:
hist (tuple) – Tuple
(counts, bin_edges)fromnp.histogram.ax (matplotlib.axes.Axes, optional) – Axis on which to draw.
- Returns:
mode (float) – Most frequent gray level.
rhwhm (float) – Right-side half-width at half-maximum.
- SilentInfarctionSegmentationFLAIR.histograms.plot_histogram(image, bins=None, title='Gray level histogram', save_path=None, no_bkg=False, show=True, normalize=False, alpha=1, downsampling=None, ax=None)[source]
Plot the histogram of a gray‑scale 3D SimpleITK image.
- Parameters:
image (SimpleITK.Image) – Input image.
bins (int or str, optional) – Number of bins or binning strategy. If None, uses the maximum gray level.
title (str, optional) – Title of the plot.
save_path (str, optional) – Path where the figure is saved.
no_bkg (bool, optional) – If True, exclude gray level 0.
show (bool, optional) – Whether to display the plot.
normalize (bool, optional) – If True, normalize histogram counts.
alpha (float, optional) – Transparency of the bars.
downsampling (float or None, optional) – Percentage of voxels to sample.
ax (matplotlib.axes.Axes, optional) – Axis on which to draw.
- Returns:
hist – Tuple
(counts, bin_edges)fromnp.histogram.- Return type:
tuple
- SilentInfarctionSegmentationFLAIR.histograms.plot_multiple_histograms(images, bins=None, labels=None, title='Gray level histograms', legend_title='', save_path=None, no_bkg=False, alpha=0.5, normalize=False, downsampling=None, show=True, ax=None)[source]
Plot histograms for multiple 3D SimpleITK images.
- Parameters:
images (list of SimpleITK.Image) – Images to process.
bins (int, list, or None) – Number of bins. If list, must match
imageslength.labels (list of str, optional) – Labels for each histogram.
title (str, optional) – Plot title.
legend_title (str, optional) – Title of the legend.
save_path (str, optional) – Path where the figure is saved.
no_bkg (bool, optional) – If True, exclude gray level 0.
alpha (float, optional) – Transparency of bars.
normalize (bool, optional) – If True, normalize histogram counts.
downsampling (float or None, optional) – Percentage of voxels to sample.
show (bool, optional) – Whether to display the plot.
ax (matplotlib.axes.Axes, optional) – Axis on which to draw.
- Returns:
hist_tables – List of histograms
(counts, bin_edges).- Return type:
list of tuple
SilentInfarctionSegmentationFLAIR.refinement module
Created on 2025-08-13 13:41:50
@author: david
- SilentInfarctionSegmentationFLAIR.refinement.connected_components(image, connectivity=26)[source]
Compute connected components in a binary image.
- Parameters:
image (SimpleITK.Image) – Binary input image (0 = background, 1 = foreground).
connectivity (int, optional) – Connectivity type: 6 (faces), 18 (faces + edges), 26 (faces + edges + corners). Default is 26.
- Returns:
ccs (SimpleITK.Image) – Labeled image where each connected component has a unique integer label.
n_components (int) – Number of connected components (excluding background).
- SilentInfarctionSegmentationFLAIR.refinement.diameter_filter(ccs, lower_thr=None, upper_thr=None)[source]
Filter connected components based on their physical diameters.
A component is removed if its minimum diameter is below
lower_thror its maximum diameter is aboveupper_thr.- Parameters:
ccs (SimpleITK.Image) – Labeled connected components image.
lower_thr (float or None, optional) – Minimum allowed diameter (mm). If None, no lower bound is applied.
upper_thr (float or None, optional) – Maximum allowed diameter (mm). If None, no upper bound is applied.
- Returns:
points (pandas.Series) – Series indexed by component label. Value is 1 if the component is kept, 0 if removed.
n_components (int) – Number of components remaining after filtering.
ccs_filtered (SimpleITK.Image) – Labeled image after removing filtered components.
- SilentInfarctionSegmentationFLAIR.refinement.evaluate_region_wise(mask, gt)[source]
Compute region‑wise detection metrics between a predicted mask and ground‑truth lesions.
Metrics follow the definitions in: Cabezas et al., Automatic multiple sclerosis lesion detection in brain MRI by FLAIR thresholding (2014).
A lesion is considered detected if at least one voxel of the predicted mask overlaps with it.
- Parameters:
mask (SimpleITK.Image) – Binary prediction mask to evaluate.
gt (SimpleITK.Image) – Binary ground‑truth lesion mask.
- Returns:
metrics – Dictionary containing: -
rw-TPF: True Positive Fraction (detected GT lesions / total GT) -rw-FPF: False Positive Fraction (spurious predicted lesions /total predicted lesions)
- Return type:
dict
- SilentInfarctionSegmentationFLAIR.refinement.extend_lesions(ccs, n_components, image, n_std=1, dilation_radius=1)[source]
Extend lesion regions by adding surrounding voxels whose intensity exceeds a lesion‑specific threshold.
The surrounding region is defined by morphological dilation. Each voxel in this region is assigned to the closest lesion using a Voronoi-like partition. For each lesion, a threshold is computed as:
threshold_i = mean_i - n_std * std_iVoxels in the surrounding region whose intensity exceeds this threshold are added to the lesion.
- Parameters:
ccs (SimpleITK.Image) – Labeled connected components image (lesions).
n_components (int) – Number of connected components in
ccs.image (SimpleITK.Image) – Original intensity image used to compute lesion statistics.
n_std (float, optional) – Number of standard deviations subtracted from the mean to compute the threshold. Lower values produce more aggressive extension. Default is 1.
dilation_radius (float, optional) – Physical radius (mm) used for morphological dilation. Default is 1.
- Returns:
extended_lesion – Binary image containing the original and extended lesions.
- Return type:
SimpleITK.Image
Notes
Each lesion receives its own adaptive threshold.
Voronoi assignment ensures each surrounding voxel is associated with the closest lesion.
- SilentInfarctionSegmentationFLAIR.refinement.find_diameters(ccs)[source]
Compute minimum and maximum physical diameter of each connected component.
- Parameters:
ccs (SimpleITK.Image) – Labeled connected components image.
- Returns:
diameters – Dictionary mapping each label to a tuple
(min_diameter, max_diameter)in millimeters.- Return type:
dict of tuple
- SilentInfarctionSegmentationFLAIR.refinement.label_filter(segm, labels_to_remove=None, keywords_to_remove=None, labels_dict=None)[source]
Remove specific labels from a segmentation image.
Labels can be removed either by specifying their numeric values or by providing keywords that match their textual descriptions.
- Parameters:
segm (SimpleITK.Image) – Labeled segmentation image.
labels_to_remove (list of int, optional) – List of numeric labels to remove. Default is None.
keywords_to_remove (list of str, optional) – Keywords used to match label names in
labels_dict.labels_dict (dict, optional) – Mapping from numeric labels to textual descriptions. Required if
keywords_to_removeis provided.
- Returns:
segm_filtered (SimpleITK.Image) – Segmentation image after removing selected labels.
removed (dict) – Dictionary mapping removed label names to the number of voxels removed.
- SilentInfarctionSegmentationFLAIR.refinement.nearly_isotropic_kernel(spacing, desired_radius=1)[source]
Compute a nearly isotropic kernel radius in voxel units.
Converts a desired physical radius (in mm) into voxel units for each dimension, based on the image spacing.
- Parameters:
spacing (sequence of float) – Voxel spacing (e.g., (sx, sy, sz)).
desired_radius (float, optional) – Desired physical radius in millimeters. Default is 1.
- Returns:
kernel – Kernel radius in voxels for each dimension.
- Return type:
list of int
- SilentInfarctionSegmentationFLAIR.refinement.pve_filter(ccs, n_components, pves)[source]
Assign points to connected components based on predominant partial volume estimates (PVE).
Each component receives a score depending on whether white matter (WM), gray matter (GM), or cerebrospinal fluid (CSF) is predominant in its region.
- Parameters:
ccs (SimpleITK.Image) – Labeled connected components image.
n_components (int) – Number of connected components in
ccs.pves (list of SimpleITK.Image) – List of PVE images in the order [WM, GM, CSF].
- Returns:
points (pandas.Series) – Score assigned to each component: - +2 → WM predominant - +1 → GM predominant - 0 → CSF predominant - -2 → all PVEs equal to zero
counts (tuple of int) – Tuple
(n_wm, n_gm, n_csf, n_zeros)with the number of components in each category.pve_sums (pandas.DataFrame) – Mean PVE values for WM, GM, and CSF for each component.
- SilentInfarctionSegmentationFLAIR.refinement.surrounding_filter(ccs, n_components, pves, dilation_radius=1)[source]
Assign points to connected components based on surrounding tissue composition.
For each lesion, the surrounding region is defined by morphological dilation. Each voxel in this region is assigned to the closest lesion using a Voronoi-like partition. Mean PVE values of WM, GM, and CSF are then computed for each lesion’s surrounding area.
- Parameters:
ccs (SimpleITK.Image) – Labeled connected components image.
n_components (int) – Number of connected components in
ccs.pves (list of SimpleITK.Image) – List of PVE images in the order [WM, GM, CSF].
dilation_radius (float, optional) – Physical radius (mm) used for morphological dilation. Default is 1.
- Returns:
points (pandas.Series) – Score assigned to each component: - +2 → WM predominant in surrounding region - +1 → GM predominant - 0 → CSF predominant - -2 → all PVEs equal to zero
counts (tuple of int) – Tuple
(n_wm, n_gm, n_csf, n_zeros)with the number of components in each category.pve_sums (pandas.DataFrame) – Mean PVE values for WM, GM, and CSF in the surrounding region.
SilentInfarctionSegmentationFLAIR.segmentation module
Created on Tue May 27 19:49:24 2025
@author: david
- SilentInfarctionSegmentationFLAIR.segmentation.apply_threshold(image, thr, ax=None)[source]
Apply a binary lower threshold to an image.
Voxels with intensity >=
thrare set to 1, otherwise to 0. Optionally draws a vertical threshold line on a provided axis.- Parameters:
image (SimpleITK.Image) – Input image.
thr (float) – Lower threshold value.
ax (matplotlib.axes.Axes, optional) – Axis on which to draw the threshold line.
- Returns:
thr_image – Binary thresholded image.
- Return type:
SimpleITK.Image
- SilentInfarctionSegmentationFLAIR.segmentation.evaluate_voxel_wise(mask, gt)[source]
Compute voxel-wise evaluation metrics between prediction and ground truth.
Metrics include: - True Positive Fraction (TPF) - False Positive Fraction (FPF) - Dice Similarity Coefficient (DSC) - Matthews Correlation Coefficient (MCC)
- Parameters:
mask (SimpleITK.Image) – Binary prediction mask.
gt (SimpleITK.Image) – Binary ground-truth mask.
- Returns:
metrics – Dictionary containing voxel-wise metrics.
- Return type:
dict
- SilentInfarctionSegmentationFLAIR.segmentation.get_mask_from_pve(pve, thr=1e-12)[source]
Generate a binary mask from a partial volume estimation (PVE) map.
- Parameters:
pve (SimpleITK.Image) – Partial volume estimation map.
thr (float, optional) – Threshold value. Voxels >= thr are set to 1. Default is 1e-12.
- Returns:
mask – Binary mask.
- Return type:
SimpleITK.Image
- SilentInfarctionSegmentationFLAIR.segmentation.get_mask_from_segmentation(segm, labels=1)[source]
Generate a binary mask from a segmentation image.
- Parameters:
segm (SimpleITK.Image) – Segmentation image where each voxel contains an integer label.
labels (int, float, iterable, or dict) – Labels to include in the mask. If a dict is provided, its values are used.
- Returns:
mask – Binary mask where selected labels are set to 1.
- Return type:
SimpleITK.Image
SilentInfarctionSegmentationFLAIR.utils module
Utility functions for 3D SimpleITK image handling and visualization.
Created on Fri May 23 20:16:28 2025 @author: david
- exception SilentInfarctionSegmentationFLAIR.utils.DimensionError[source]
Bases:
ExceptionCustom exception for non‑3D images.
- SilentInfarctionSegmentationFLAIR.utils.check_3d(image)[source]
Ensure that a SimpleITK image is 3‑dimensional.
- Parameters:
image (SimpleITK.Image) – Input image.
- Raises:
DimensionError – If the image is not 3‑dimensional.
- SilentInfarctionSegmentationFLAIR.utils.cliffs_delta(x, y)[source]
Compute Cliff’s delta effect size between two 1D samples.
Cliff’s delta measures how often values in
xexceed values inyminus how often they are smaller, normalized by the total number of pairwise comparisons.The statistic ranges from -1 to +1: - +1 → all values in
x> all values iny- 0 → distributions largely overlap - -1 → all values inx< all values iny- Parameters:
x (np.ndarray) – First 1D sample.
y (np.ndarray) – Second 1D sample.
- Returns:
Cliff’s delta effect size.
- Return type:
float
- SilentInfarctionSegmentationFLAIR.utils.downsample_array(arr, perc=0.01)[source]
Evenly downsample a 1D NumPy array.
Useful for reducing memory and computation on very large arrays by selecting regularly spaced samples.
- Parameters:
arr (np.ndarray) – Input 1D array.
perc (float, optional) – Fraction of elements to keep (e.g., 0.01 = 1%). Must be in (0, 1]. Default is 0.01.
- Returns:
Downsampled array.
- Return type:
np.ndarray
- Raises:
ValueError – If
percis <= 0.
- SilentInfarctionSegmentationFLAIR.utils.gaussian_transform(image, mean, std, return_float=False, normalized=False)[source]
Apply a Gaussian weighting to voxel intensities.
Each voxel intensity
Iis transformed as:G(I) = exp(-0.5 * ((I - mean) / std)**2) * I
If
return_float=Trueandnormalized=True, the result is additionally scaled by:1 / (std * sqrt(2π))
- Parameters:
image (SimpleITK.Image) – Input image with non‑negative voxel intensities.
mean (float) – Mean of the Gaussian distribution.
std (float) – Standard deviation of the Gaussian.
return_float (bool, optional) – If True, return a float image in [0, 1].
normalized (bool, optional) – If True and
return_float=True, apply Gaussian normalization.
- Returns:
Gaussian‑weighted image with preserved metadata.
- Return type:
SimpleITK.Image
- Raises:
ValueError – If the input image contains negative voxel values.
- SilentInfarctionSegmentationFLAIR.utils.get_array_from_image(image)[source]
Convert a SimpleITK 3D image into a NumPy array.
The returned array is transposed so that: - axial plane → xy - sagittal plane → yz - coronal plane → xz
- Parameters:
image (SimpleITK.Image) – Input 3D image.
- Returns:
Array with shape (x, y, z).
- Return type:
np.ndarray
- SilentInfarctionSegmentationFLAIR.utils.get_image_from_array(image_array, reference_image=None, cast_to_reference=True)[source]
Convert a NumPy array into a SimpleITK image.
The input array must follow the convention: - axial plane → xy - sagittal plane → yz - coronal plane → xz
- Parameters:
image_array (np.ndarray) – Array with shape (x, y, z).
reference_image (SimpleITK.Image, optional) – If provided, copy spacing, origin and direction.
cast_to_reference (bool, optional) – If True, cast voxel type to match
reference_image.
- Returns:
Output image.
- Return type:
SimpleITK.Image
- SilentInfarctionSegmentationFLAIR.utils.get_info(image)[source]
Extract metadata from a SimpleITK 3D image.
- Parameters:
image (SimpleITK.Image) – Input image.
- Returns:
Dictionary containing size, spacing, origin and direction.
- Return type:
dict
- SilentInfarctionSegmentationFLAIR.utils.get_paths_df(folder, extensions='')[source]
Build a DataFrame containing paths of files inside a folder.
- Parameters:
folder (str) – Path to the folder to scan.
extensions (str or list of str, optional) – File extensions to include. If a single string is provided, it is converted to a list.
- Returns:
DataFrame where: - index = folder paths - columns = filenames - values = full file paths
- Return type:
pandas.DataFrame
- SilentInfarctionSegmentationFLAIR.utils.label_names(label_name_file_path)[source]
Read a text file and map numeric labels to string names.
The file must contain lines beginning with an integer followed by a label name. Only the first word after the number is used.
Examples
‘1 Left-Thalamus’ → {1: ‘Left-Thalamus’} ‘2 Left Thalamus’ → {2: ‘Left’}
- Parameters:
label_name_file_path (str) – Path to the label text file.
- Returns:
Mapping from integer labels to string names.
- Return type:
dict
- SilentInfarctionSegmentationFLAIR.utils.normalize(image, n_bits=8)[source]
Normalize an image using min‑max rescaling.
If
n_bits == 0, the output is float64 in [0, 1]. Otherwise, the output is cast to an unsigned integer type.- Parameters:
image (SimpleITK.Image) – Input image.
n_bits (int, optional) – Number of bits for the output image. Default is 8.
- Returns:
Normalized image with preserved metadata.
- Return type:
SimpleITK.Image
- SilentInfarctionSegmentationFLAIR.utils.orient_image(image, orientation)[source]
Reorient a SimpleITK image to a given coordinate system.
- Parameters:
image (SimpleITK.Image) – Input 3D image.
orientation (str) – Desired orientation code (e.g., ‘RAS’, ‘LPS’).
- Returns:
Reoriented image.
- Return type:
SimpleITK.Image
- SilentInfarctionSegmentationFLAIR.utils.plot_image(image, xyz=None, mask=None, title=None, show=True, save_path=None)[source]
Plot three orthogonal slices (axial, sagittal, coronal) of a 3D image.
- Parameters:
image (SimpleITK.Image) – Input 3D image.
xyz (tuple of int, optional) – Coordinates of the slice intersection (x, y, z). If None, the center of the image is used.
mask (SimpleITK.Image, optional) – Binary mask to overlay on the image. Masked voxels are shown in red.
title (str, optional) – Title of the figure.
show (bool, optional) – Whether to display the figure.
save_path (str, optional) – Path where the figure is saved.
- Returns:
Dictionary containing array size, spacing and aspect ratios.
- Return type:
dict
- SilentInfarctionSegmentationFLAIR.utils.progress_bar(iteration, total, start_time=None, prefix='', length=40)[source]
Display or update a textual progress bar in the console.
- Parameters:
iteration (int) – Current iteration (0‑based).
total (int) – Total number of iterations.
start_time (float, optional) – Start time (e.g.,
time.time()). If provided, an ETA is shown.prefix (str, optional) – Text displayed before the bar.
length (int, optional) – Length of the bar in characters.
Notes
The bar updates in place using carriage return.
A newline is printed at the last iteration.
Handles cases where
iteration >= totalortotal <= 0.
- SilentInfarctionSegmentationFLAIR.utils.resample_to_reference(image, reference, interpolator=1, default_value=0)[source]
Resample an image into the space of a reference image.
- Parameters:
image (SimpleITK.Image) – Image to resample.
reference (SimpleITK.Image) – Target reference image.
interpolator (SimpleITK interpolator, optional) – Interpolation method (e.g., sitk.sitkLinear).
default_value (float, optional) – Value assigned outside the original image domain.
- Returns:
Resampled image.
- Return type:
SimpleITK.Image
- SilentInfarctionSegmentationFLAIR.utils.train_val_test_split(data_folder, validation_fraction=0, test_fraction=0, gt_file='GT.nii', show=False, save_series=True, title=None)[source]
Split patients into train/validation/test sets based on ground‑truth lesion ratios.
Patients are grouped by quartiles of the positive‑label ratio and sampled proportionally within each quartile.
- Parameters:
data_folder (str) – Root folder containing patient subdirectories with .nii files.
validation_fraction (float, optional) – Fraction of patients assigned to validation. Default is 0.
test_fraction (float, optional) – Fraction of patients assigned to test. Default is 0.
gt_file (str, optional) – Name of the ground‑truth file inside each patient folder.
show (bool, optional) – Whether to display the ratio distribution plot.
save_series (bool, optional) – Whether to save train/val/test patient lists as pickle files.
title (str, optional) – Title for the ratio distribution plot.
- Returns:
tr_patients (list of str) – Patients assigned to the training set.
val_patients (list of str) – Patients assigned to the validation set.
ts_patients (list of str) – Patients assigned to the test set.
Notes
Patients missing required .nii files are discarded.
Positive ratio is defined as:
ratio = count(label == 1) / (count(label == 0) + count(label == 1))
Quartile‑based stratification ensures balanced sampling.
A plot
ratios.pngis saved indata_folder.