WSIHelper Module¶
Provides tools for working with Whole Slide Images (WSI) in digital pathology.
- HMB.WSIHelper.ReadWSIViaOpenSlide(slidePath)[source]¶
Reads a whole slide image (WSI) using OpenSlide and returns an OpenSlide object.
- Parameters:
slidePath (str) – Path to the slide file.
- Returns:
OpenSlide object for the slide.
- Return type:
- Raises:
AssertionError – If the slide path does not exist.
- HMB.WSIHelper.ReadGeoJSONAnnotations(annotationFile)[source]¶
Read a GeoJSON annotation file and return a list of annotations.
- Each annotation is a dict with the keys:
id: feature id (or index)
properties: feature properties (dict)
geometry: dict with “type” and “coordinates”
Accepts either a pathlib.Path or a string path. Gracefully handles FeatureCollection, single Feature, or raw geometry objects.
- Parameters:
annotationFile (str or pathlib.Path) – Path to the GeoJSON annotation file.
- Returns:
List of annotations read from the GeoJSON file.
- Return type:
List[Dict[str, Any]]
- HMB.WSIHelper.DrawPolygonOnImage(imageArr, coords, outlineColor=(255, 0, 0), fillColor=None, width=2)[source]¶
Draw a polygon with optional filled semi-transparent interior.
- Parameters:
imageArr (numpy.ndarray) – Input image (HWC, uint8), RGB or BGR.
coords (list) – List of (x, y) tuples defining polygon vertices.
outlineColor (tuple) – RGB color for outline, e.g., (255, 0, 0) = red.
fillColor (tuple or None) – RGBA color for fill, e.g., (255, 0, 0, 0.5). If None, no fill.
width (int) – Thickness of the outline.
- Returns:
Modified image in same format as input (RGB assumed).
- Return type:
- HMB.WSIHelper.ExtractPatchesFromWSI(wsi, wsiFile, annotations, outputDir, patchSize=(256, 256), overlap=(0, 0), maxNumPatchesPerAnnotation=100, label=None, tissueThreshold=0.3)[source]¶
Extract patches from WSI within annotated regions, skipping background tiles.
- Parameters:
wsi (openslide.OpenSlide) – OpenSlide WSI object.
wsiFile (str or pathlib.Path) – Path to the WSI file (for reference).
annotations (list) – List of GeoJSON-like annotation dicts.
outputDir (str or pathlib.Path) – Directory to save extracted patches.
patchSize (tuple) – Size of patches to extract (width, height).
overlap (tuple) – Overlap between patches (x_overlap, y_overlap).
maxNumPatchesPerAnnotation (int) – Max patches to extract per annotation.
label – Optional label to embed in patch filenames.
tissueThreshold (float) – Minimum fraction of tissue pixels required.
- HMB.WSIHelper.TileExtractionAlignmentHandler(heSlidePath, mtSlidePath, storageDir, patchesPerSlide=5000, targetSize=(512, 512), regionSize=(4096, 4096), overlapSize=(256, 256), thumbnailSize=(1024, 1024), toleranceSIFT=0.5, maxNumFeaturesORB=5000, maxGoodMatchesORB=25, emptyPercentageThreshold=80, doPlotting=True, verbose=False, dpi=720, miThreshold=0.35, cosSimThreshold=0.75, pHashThreshold=20, strict=True)[source]¶
Extracts and aligns patches from HE (Hematoxylin-Eosin) and MT (Masson’s Trichrome) slides, processes them, and saves the results.
- Parameters:
heSlidePath (str) – Path to the HE slide.
mtSlidePath (str) – Path to the MT slide.
storageDir (str) – Directory to store extracted patches and visualizations.
patchesPerSlide (int) – Total number of patches to extract per slide.
targetSize (tuple) – Size of each patch to extract (width, height).
regionSize (tuple) – Size of the region used for processing.
overlapSize (tuple) – Overlap between adjacent patches.
thumbnailSize (tuple) – Size of the thumbnail for visualization.
toleranceSIFT (float) – Tolerance for SIFT matching (default is 0.50).
maxNumFeaturesORB (int) – Maximum number of features to detect for matching.
maxGoodMatchesORB (int) – Maximum number of good matches to consider for alignment.
emptyPercentageThreshold (int) – Threshold for empty percentage in patches (default is 80%).
doPlotting (bool) – Whether to generate and save plots for visualization.
verbose (bool) – Whether to print verbose output during processing.
dpi (int) – DPI for saved plots.
miThreshold (float) – Mutual Information threshold for similarity acceptance.
cosSimThreshold (float) – Cosine Similarity threshold for similarity acceptance.
pHashThreshold (int) – Perceptual Hash distance threshold for similarity acceptance.
strict (bool) – Whether to apply strict criteria for similarity acceptance.
- Raises:
AssertionError – If the HE or MT slide paths do not exist.
- HMB.WSIHelper.ExtractPatch(topLeftRegion, heSlide, mtSlide, mtContour, heContour, regionSize, targetSize, homography, maxNumFeaturesORB=5000, maxGoodMatchesORB=25)[source]¶
Extracts and processes patches from HE (Hematoxylin & Eosin) and MT (Trichrome) slides. The function applies transformations, matches regions using ORB, and computes differences between the two slide types. It also generates binary masks and weighted combinations.
- Parameters:
topLeftRegion (tuple) – Top-left corner coordinates of the region to extract.
heSlide (openslide.OpenSlide) – HE slide object.
mtSlide (openslide.OpenSlide) – MT slide object.
mtContour (list) – Contour defining the boundaries of the MT slide region.
heContour (list) – Contour defining the boundaries of the HE slide region.
regionSize (tuple) – Size of the region to extract (width, height).
targetSize (tuple) – Target size for the final extracted patch (width, height).
homography (numpy.ndarray) – Homography matrix for transforming coordinates.
maxNumFeaturesORB (int) – Maximum number of features to detect for matching.
maxGoodMatchesORB (int) – Maximum number of good matches to consider for alignment.
- Returns:
- A tuple containing:
heRegionOrig (PIL.Image): Original HE region at the target size.
mtRegionOrig (PIL.Image): Original MT region at the target size.
heRegionBW (numpy.ndarray): Binary mask of the HE region.
mtRegionBW (numpy.ndarray): Binary mask of the MT region.
diff (numpy.ndarray): Absolute difference between the binary masks.
weighted (numpy.ndarray): Weighted combination of the HE and MT regions.
topLeftFlag (bool): Flag indicating if the top-left point is inside both contours.
- Return type:
- HMB.WSIHelper.FreeFormDeformationHandler(heFolderPath, mtFolderPath, heDeformedFolderPath, doPlotting=False, visualizationFolderPath=None, gridSize=[10, 10], numberOfHistogramBins=50, samplingPercentage=0.1, learningRate=0.01, numberOfIterations=500, convergenceMinimumValue=1e-06, convergenceWindowSize=10, verbose=False)[source]¶
Apply Free Form Deformation (FFD) to HE images and save the deformed results. This function applies B-spline based Free Form Deformation to each HE image, optimizing the deformation to align with the corresponding MT image. The optimization is performed using a metric computed from sampled pixels and histogram bins, and the process is controlled by a learning rate and convergence criteria.
\[\text{FFD}(x, y) = \sum_{i=0}^{n} \sum_{j=0}^{m} B_i(u) \cdot B_j(v) \cdot P_{i,j}\]- where
\(B_i(u)\) and \(B_j(v)\) are B-spline basis functions.
\(P_{i,j}\) are control points.
- Parameters:
heFolderPath (str) – Path to the folder containing HE images.
mtFolderPath (str) – Path to the folder containing corresponding MT images.
heDeformedFolderPath (str) – Path to the folder where deformed HE images will be saved.
doPlotting (bool) – Whether to store visualizations (default is False).
visualizationFolderPath (str | None) – Path to the folder for storing visualizations (Optional, default is None).
gridSize (list) – Grid size for the B-spline transform (default is [10, 10]).
numberOfHistogramBins (int) – Number of histogram bins for the metric (default is 50).
samplingPercentage (float) – Percentage of pixels to sample for the metric (default is 0.1).
learningRate (float) – Learning rate for the optimizer (default is 0.01).
numberOfIterations (int) – Maximum number of iterations (default is 500).
convergenceMinimumValue (float) – Convergence threshold (default is 1e-6).
convergenceWindowSize (int) – Window size for convergence determination (default is 10).
verbose (bool) – Whether to print verbose output during processing (default is False).
- Raises:
AssertionError – If the HE or MT folder paths do not exist.
- HMB.WSIHelper.ExtractRandomTilesFromImages(labelsFile, slidesDir='Slides', outputDir='Tiles', targetShape=(256, 256), numOfTiles=1000, allowedBackgroundRatio=0.65, filenameColumn='filename', categoryColumn='Category', maxAttemptsFactor=10, verbose=False)[source]¶
Extract random tiles from a set of large images using pyvips for efficient IO and OpenCV for simple background filtering. This mirrors the user’s provided script but is wrapped as a reusable function following the repository style.
- HMB.WSIHelper.ExtractBACHAnnotationsFromXML(xmlFile, verbose=True)[source]¶
Extract annotations from a BACH XML file.
- HMB.WSIHelper.ExtractWSIRegion(slide, region)[source]¶
Extract a region of interest (ROI) from a whole-slide image (WSI) using OpenSlide. The extracted region is from the highest resolution level (level 0) and is masked according to the polygon defined by the annotation.
- Parameters:
slide (openslide.OpenSlide) – The OpenSlide object representing the WSI or an object with a read_region method and dimensions attribute.
region (dict) – A dictionary with a “Coords” key containing a list of (x, y) tuples.
- Returns:
- A tuple containing:
regionImage (numpy.ndarray): The extracted region image as a NumPy RGB array (H,W,3) uint8.
regionMask (numpy.ndarray): The binary mask for the region as a NumPy uint8 array (H,W) with 0/255 values.
roi (numpy.ndarray): The extracted region of interest (ROI) as a NumPy RGB array (H,W,3) uint8.
- Return type:
- HMB.WSIHelper.ExtractPyramidalWSITiles(slide, x=0, y=0, width=512, height=512)[source]¶
Extract tiles from each level of a whole-slide image (WSI) pyramid using OpenSlide, centered around a specified region defined by (x, y, width, height) at the highest resolution level (level 0). The function calculates the corresponding regions at each pyramid level, extracts the tiles, and visualizes them in a grid layout. Also, it returns the extracted tiles in a dictionary keyed by pyramid level and a list of magnification levels.
- Parameters:
slide (openslide.OpenSlide) – The OpenSlide object representing the WSI.
x (int) – The x-coordinate of the top-left corner of the region at level 0 (default is 0).
y (int) – The y-coordinate of the top-left corner of the region at level 0 (default is 0).
width (int) – The width of the region to extract at level 0 (default is 512).
height (int) – The height of the region to extract at level 0 (default is 512).
- Returns:
- A tuple containing:
tiles (dict): A dictionary where keys are pyramid level indices and values are the extracted tile images as NumPy arrays.
figToReturn (matplotlib.figure.Figure): The matplotlib figure object containing the visualizations of the extracted tiles and their verification crops.
magLevels (list): A list of magnification levels corresponding to each pyramid level, calculated from the downsample factors.
- Return type:
Examples
import os import matplotlib.pyplot as plt from HMB.WSIHelper import ExtractRegionTiles, ReadWSIViaOpenSlide, ExtractPyramidalWSITiles # Define the path to the WSI file. path = "path/to/your/slide.svs" # Define the storage path for the extracted tiles. storagePath = "path/to/store/tiles" # Define a case number for naming the extracted tiles. caseNum = "Case123" # Read the WSI using OpenSlide. slide = ReadWSIViaOpenSlide(path) # Define the region of interest (ROI) for tile extraction. x, y = 1000, 1000 # Define the tile dimensions. width, height = 512, 512 # Extract tiles from the specified region of the WSI. tilesDict, outFigure, magLevels = ExtractPyramidalWSITiles(slide, x=x, y=y, width=width, height=height) # Store the output figure in the specified directory. figurePath = os.path.join(storagePath, f"{caseNum}_L0_M0_Figure.png") outFigure.savefig(figurePath) # Optionally, display the output figure. outFigure.show() plt.show() # Store the extracted tiles in a directory. if (not os.path.exists(storagePath)): os.makedirs(storagePath) # Iterate through the extracted tiles and save them to the specified directory. for i in range(len(tilesDict.keys())): key = list(sorted(tilesDict.keys()))[i] tile = tilesDict[key] magLevel = magLevels[i] tilePath = os.path.join(storagePath, f"{caseNum}_L{key}_M{magLevel}.png") plt.imsave(tilePath, tile)
- HMB.WSIHelper.PrepareAnnotationsForLevel(annotation, dFactor=1.0)[source]¶
Map annotation coordinates from one pyramid level to another by applying a downsample factor.
- HMB.WSIHelper.ExtractWSITissueContour(slide, level=-1, thresholdValue=240, minAreaRatio=0.01)[source]¶
Extracts the combined contour of all tissue content from a whole-slide image (WSI) by analyzing a thumbnail or a specific pyramid level. It identifies all contiguous tissue regions, ignoring background areas based on a brightness threshold, and combines them into a single unified contour representation.
- Parameters:
slide (openslide.OpenSlide) – The OpenSlide object representing the WSI.
level (int) – The pyramid level to use for contour extraction. -1 uses the lowest resolution (thumbnail level) for speed (default is -1).
thresholdValue (int) – The pixel value threshold to distinguish background from tissue. Pixels brighter than this are considered background (default is 240).
minAreaRatio (float) – The minimum area ratio relative to the total contours area to consider a contour as valid tissue (default is 0.01).
- Returns:
- A dictionary containing:
”Coords”: A list of (x, y) tuples representing the polygon coordinates of the combined tissue contour at level 0 resolution.
”BoundingBox”: A tuple (x, y, w, h) representing the bounding rectangle of the combined contour at level 0 resolution.
”Area”: The total area of all valid contours in pixels at level 0 resolution.
- Return type:
- Raises:
ValueError – If no valid tissue contour is found.
Notes
The function uses OpenCV to process the image and extract contours. Ensure that OpenCV is installed in your Python environment.
The contour extraction is performed on a downsampled version of the WSI for efficiency. The coordinates are then scaled back to the original resolution.
Examples
import os from HMB.WSIHelper import ReadWSIViaOpenSlide, ExtractWSITissueContour # Path to the WSI file. wsiPath = r"/path/to/your/slide.svs" # Read the WSI using OpenSlide. slide = ReadWSIViaOpenSlide(wsiPath) # Extract the tissue contour and bounding box from the WSI. tissueInfo = ExtractWSITissueContour(slide, level=-1, thresholdValue=240, minAreaRatio=0.01) print(f"Tissue Contour Coords: {tissueInfo['Coords']}") print(f"Tissue Bounding Box: {tissueInfo['BoundingBox']}") print(f"Tissue Area: {tissueInfo['Area']} pixels")
- HMB.WSIHelper.ExtractRegionTiles(slide, region, width=512, height=512, overlapWidth=0, overlapHeight=0, storageDir=None, maxTiles=None, addPlots=True, prefix='', blackRatioThreshold=0.9, removeBackgroundTiles=True, convertBlackToWhite=True, dpi=300)[source]¶
Extract tiles from a specified region of a whole-slide image (WSI) across all pyramid levels, applying annotation masks and saving results. The function handles the mapping of annotations to each level, extracts tiles, applies masks, and optionally saves the tiles, masks, and ROIs to disk.
- Parameters:
slide (openslide.OpenSlide) – The OpenSlide object representing the WSI.
region (dict) – A dictionary with a “Coords” key containing a list of (x, y) tuples representing the annotation polygon.
width (int) – The width of the tiles to extract in pixels (default is 512).
height (int) – The height of the tiles to extract in pixels (default is 512).
overlapWidth (int) – The horizontal overlap between tiles in pixels (default is 0).
overlapHeight (int) – The vertical overlap between tiles in pixels (default is 0).
storageDir (str or None) – The directory path to save the extracted tiles, masks, and ROIs. If None, no files will be saved (default is None).
maxTiles (int or None) – The maximum number of tiles to extract for the region. If None, all tiles will be extracted (default is None).
addPlots (bool) – Whether to create and save plots visualizing the tiles, masks, and ROIs (default is True).
prefix (str) – A string prefix to add to saved file names for organization (default is an empty string).
blackRatioThreshold (float) – The maximum allowed ratio of black pixels in a tile to be considered valid (default is 0.90). Tiles with a higher ratio will be skipped.
removeBackgroundTiles (bool) – Whether to skip tiles that are considered background based on the black pixel ratio (default is True).
convertBlackToWhite (bool) – Whether to convert black pixels to white in the ROI before background analysis to avoid skewing metrics (default is True).
dpi (int) – The resolution in dots per inch for saving plots (default is 300).
- Returns:
A dictionary containing the extracted tiles, masks, and ROIs for each level, structured as follows: {level_index: {“Tiles”: [list of tile images as NumPy arrays], “Masks”: [list of corresponding masks as NumPy arrays], “ROIs”: [list of corresponding ROIs as NumPy arrays]}, …}
- Return type:
Notes
The function will create subdirectories for “Plots”, “Tiles”, “Masks”, and “ROIs” within the specified storageDir if it is not None.
The function uses tqdm for progress bars when processing tiles, which can be helpful for long-running operations.
The function applies the annotation mask to the extracted tiles to isolate the region of interest (ROI) and can optionally filter out tiles that are mostly background based on the specified black pixel ratio threshold.
Examples
import os from HMB.WSIHelper import ReadWSIViaOpenSlide, ExtractWSITissueContour, ExtractRegionTiles # Define the path to the WSI file and the storage directory for results. wsiPath = r"/path/to/your/slide.svs" storagePath = r"/path/to/store/results" caseNum = "Case123" # Read the WSI using OpenSlide. slide = ReadWSIViaOpenSlide(wsiPath) # Extract the tissue contour from the WSI to define the region of interest. tissueInfo = ExtractWSITissueContour(slide, level=-1, thresholdValue=240, minAreaRatio=0.01) region = { "Text": "TissueRegion", "Coords": tissueInfo["Coords"] } # Extract tiles from the defined region, applying masks and saving results. results = ExtractRegionTiles( slide, region, width=512, height=512, overlapWidth=0, overlapHeight=0, storageDir=storagePath, maxTiles=100, # Set a limit on the number of tiles to extract for testing purposes. addPlots=True, prefix=caseNum, blackRatioThreshold=0.90, removeBackgroundTiles=True, convertBlackToWhite=True, dpi=300 )
- HMB.WSIHelper.ExtractRegionTilesFromBoundingBox(slide, startX=0, startY=0, endX=None, endY=None, width=512, height=512, overlapWidth=0, overlapHeight=0, storageDir=None, maxTiles=None, addPlots=True, prefix='', blackRatioThreshold=0.9, removeBackgroundTiles=True, convertBlackToWhite=True, dpi=300)[source]¶
Extract tiles from a specified bounding box of a whole-slide image (WSI) across all pyramid levels, applying background filtering and saving results. The function extracts tiles within the defined coordinate range, processes them at each pyramid level, and optionally saves tiles, masks, and ROIs to disk.
- Parameters:
slide (openslide.OpenSlide) – The OpenSlide object representing the WSI.
startX (int) – The starting X coordinate in level 0 pixels for the extraction area (default is 0).
startY (int) – The starting Y coordinate in level 0 pixels for the extraction area (default is 0).
endX (int or None) – The ending X coordinate in level 0 pixels for the extraction area. If None, uses the full slide width (default is None).
endY (int or None) – The ending Y coordinate in level 0 pixels for the extraction area. If None, uses the full slide height (default is None).
width (int) – The width of the tiles to extract in pixels (default is 512).
height (int) – The height of the tiles to extract in pixels (default is 512).
overlapWidth (int) – The horizontal overlap between tiles in pixels (default is 0).
overlapHeight (int) – The vertical overlap between tiles in pixels (default is 0).
storageDir (str or None) – The directory path to save the extracted tiles, masks, and ROIs. If None, no files will be saved (default is None).
maxTiles (int or None) – The maximum number of tiles to extract. If None, all tiles will be extracted (default is None).
addPlots (bool) – Whether to create and save plots visualizing the tiles, masks, and ROIs (default is True).
prefix (str) – A string prefix to add to saved file names for organization (default is an empty string).
blackRatioThreshold (float) – The maximum allowed ratio of black pixels in a tile to be considered valid (default is 0.90). Tiles with a higher ratio will be skipped.
removeBackgroundTiles (bool) – Whether to skip tiles that are considered background based on tissue analysis (default is True).
convertBlackToWhite (bool) – Whether to convert black pixels to white in the ROI before background analysis to avoid skewing metrics (default is True).
dpi (int) – The resolution in dots per inch for saved plot images (default is 300).
Examples
import os import matplotlib.pyplot as plt from HMB.WSIHelper import ExtractRegionTilesFromBoundingBox, ReadWSIViaOpenSlide # Define the path to the WSI file. path = "path/to/your/slide.svs" # Define the storage path for the extracted tiles. storagePath = "path/to/store/tiles" # Define a case number for naming the extracted tiles. caseNum = "Case123" # Read the WSI using OpenSlide. slide = ReadWSIViaOpenSlide(path) # Define the bounding box coordinates for the region of interest (ROI). startX, startY = 1000, 1000 endX, endY = 5000, 5000 # Define the tile dimensions and overlap. width, height = 512, 512 overlapWidth, overlapHeight = 64, 64 # Extract tiles from the specified bounding box region of the WSI. ExtractRegionTilesFromBoundingBox( slide, startX=startX, startY=startY, endX=endX, endY=endY, width=width, height=height, overlapWidth=overlapWidth, overlapHeight=overlapHeight, storageDir=storagePath, maxTiles=100, addPlots=True, prefix=caseNum, blackRatioThreshold=0.90, removeBackgroundTiles=True, convertBlackToWhite=True, dpi=300 ) print("Tile extraction from bounding box completed. Check the storage directory for results.")
- HMB.WSIHelper.IsBackgroundTile(imagePath, image=None, entropyThreshold=5.5, colorVarianceThreshold=1500, tissueAreaThreshold=0.2, convertBlackToWhite=True)[source]¶
Detect background tiles using multiple criteria suitable for non-black backgrounds.
- Parameters:
imagePath (str) – Path to the tile image to analyze for background detection.
image (numpy.ndarray, Optional) – Pre-loaded image as a NumPy array (H,W,3) uint8. If provided, imagePath will be ignored.
entropyThreshold (float) – Threshold for Shannon entropy to detect uniformity. Adjust based on the expected variability in tissue tiles.
colorVarianceThreshold (float) – Threshold for color variance to detect lack of color diversity. Adjust based on the expected variability in tissue tiles.
tissueAreaThreshold (float) – Minimum ratio of tissue area to total area to consider the tile as non-background.
convertBlackToWhite (bool) – Whether to convert black pixels to white before analysis (default is True).
- Returns:
True if the tile is considered background, False otherwise. dict: A dictionary containing the computed metrics for debugging and analysis.
- Return type:
- HMB.WSIHelper.BatchNormalizeHistopathologyImages(inputFolder, outputFolder, modelPath, method='reinhard', targetImage=None)[source]¶
Normalize a folder of histopathology images. If a fitted model exists at modelPath, it loads and applies it directly. Otherwise, it fits the normalizer on the targetImage. If targetImage is None, it automatically and randomly selects a representative image from the input folder.
- Parameters:
inputFolder (str) – The path to the input folder containing the source images.
outputFolder (str) – The path to the output folder to save the normalized images.
modelPath (str) – The path to save/load the fitted normalizer model as a pickle file.
method (str) – The normalization method to use (“reinhard”, “macenko”, “vahadane”, or “histogram”).
targetImage (str or numpy.ndarray) – The target RGB image (or its path) to fit the normalizer (optional).
Examples
from HMB.WSIHelper import BatchNormalizeHistopathologyImages # Define the input and output directories, reference image, and other parameters. inputDirectory = "path/to/input/images" outputDirectory = "path/to/output/NormalizedImages" referenceImagePath = "path/to/reference/ReferenceImage.png" modelPath="path/to/save/NormalizerModel.pkl" normalizationMethod = "reinhard" # Options: "reinhard", "macenko", "vahadane", "histogram". # Normalize a folder of histopathology images using Reinhard normalization. BatchNormalizeHistopathologyImages( inputFolder=inputDirectory, outputFolder=outputDirectory, modelPath=modelPath, method=normalizationMethod, targetImage=referenceImagePath # Optional: can be None for automatic selection. )
- HMB.WSIHelper.NormalizeHistopathologyDatasetSplits(inputDir, outputDir, referencePath, splits, extensions, normMethod, storeExtension='.png')[source]¶
Normalizes histopathology images in a folder structure using the specified normalization method. The function processes images in the specified splits and saves the normalized images to the output directory.
- Parameters:
inputDir (str) – Path to the input directory containing the images to normalize.
outputDir (str) – Path to the output directory where normalized images will be saved.
referencePath (str) – Path to the reference image used for normalization.
splits (list) – List of subdirectory names (splits) to process (e.g., [“train”, “val”, “test”]).
extensions (list) – List of image file extensions to process (e.g., [“.jpg”, “.png”]).
normMethod (str) – Normalization method to use. Options are “reinhard”, “macenko”, “vahadane”, “histogram”, or “None” to disable normalization.
storeExtension (str) – File extension for saving normalized images (default is “.png”).
- Raises:
ValueError – If an unsupported normalization method is specified.
FileNotFoundError – If the reference image is not found at the specified path.
Examples
from HMB.WSIHelper import NormalizeHistopathologyDatasetSplits # Define the input and output directories, reference image, and other parameters. inputDirectory = "path/to/input/images" outputDirectory = "path/to/output/NormalizedImages" referenceImagePath = "path/to/reference/ReferenceImage.png" splitsToProcess = ["train", "val", "test"] imageExtensions = [".jpg", ".png"] normalizationMethod = "reinhard" # Options: "reinhard", "macenko", "vahadane", "histogram", "None". storeExtension = ".png" # Extension for saving normalized images. # Call the function to normalize images in the specified folder structure. NormalizeHistopathologyDatasetSplits( inputDir=inputDirectory, outputDir=outputDirectory, referencePath=referenceImagePath, splits=splitsToProcess, extensions=imageExtensions, normMethod=normalizationMethod, storeExtension=storeExtension )