Stain Normalization¶
HistoKit provides a collection of stain normalization methods for H&E-stained histopathology images. Stain normalization reduces variations in color appearance caused by differences in staining protocols, laboratory procedures, and slide acquisition conditions.
The normalization process adjusts the color appearance of a source image to match a selected reference (target) image while aiming to preserve tissue morphology.
Tutorial¶
Available normalization methods¶
| Method | Identifier | Description |
|---|---|---|
| Macenko | macenko |
Optical density-based stain separation using singular value decomposition. |
| Vahadane | vahadane |
Stain separation based on sparse non-negative matrix factorization. |
| Reinhard | reinhard |
Color normalization based on matching color distribution statistics in a decorrelated color space. |
Basic usage¶
Stain normalizers accept RGB NumPy arrays with shape (H, W, 3), dtype uint8, and intensity values in [0, 255].
The normalization workflow consists of two steps:
- Fit the normalizer to a representative target image using
fit(). - Normalize one or more source images using
transform().
| stain_normalization.py | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 | |
StainingNormalizer¶
| Parameter | Type | Default | Description |
|---|---|---|---|
method |
str |
— | Normalization method: macenko, vahadane, or reinhard. Method names are case-insensitive. |
**kwargs |
dict |
— | Optional method-specific keyword arguments described below. |
| Method | Description |
|---|---|
fit(target) |
Estimates reference statistics or stain characteristics from the target image and returns the fitted normalizer. |
transform(img) |
Normalizes a source image using the fitted reference characteristics. |
The normalized image retains the spatial dimensions of the input image and is returned as an RGB uint8 NumPy array. The source and target images are not modified in place.
Reuse the fitted normalizer
Fit the normalizer once and reuse it for multiple source images to maintain a consistent reference staining appearance.
Normalization methods¶
The following sections describe the general principles of the supported algorithms.
Macenko¶
Macenko normalization estimates stain color vectors in optical density (OD) space. Singular value decomposition is used to identify the dominant stain subspace, from which the hematoxylin and eosin stain directions are estimated.
The general workflow consists of:
- Converting RGB intensities to optical density.
- Estimating the stain matrix from informative tissue pixels.
- Estimating stain concentrations.
- Adjusting stain concentrations and reconstructing the image using reference stain characteristics.
| Parameter | Type | Default | Description |
|---|---|---|---|
ang_per |
float |
99 |
Angular percentile used to estimate stain directions. |
lum_thr |
float |
0.8 |
Luminosity threshold used for tissue selection. |
normalizer = StainingNormalizer("macenko", ang_per=97, lum_thr=0.85).fit(target)
normalized = normalizer.transform(image)
Vahadane¶
Vahadane normalization uses sparse, non-negative matrix factorization to separate stain colors and their concentrations. The method aims to preserve tissue structure while transferring the staining appearance of the reference image.
| Parameter | Type | Default | Description |
|---|---|---|---|
lum_thr |
float |
0.8 |
Luminosity threshold used for tissue selection. |
reg |
float |
0.1 |
Regularization parameter for sparse stain decomposition. |
max_iter |
int |
10 |
Maximum number of optimization iterations. |
normalizer = StainingNormalizer(
"vahadane", lum_thr=0.85, reg=0.05, max_iter=30,
).fit(target)
normalized = normalizer.transform(image)
Reinhard¶
Reinhard normalization transfers color appearance by matching the mean and standard deviation of color channels in a decorrelated color space. Unlike Macenko and Vahadane, it does not explicitly estimate hematoxylin and eosin stain vectors.
| Parameter | Type | Default | Description |
|---|---|---|---|
lum_thr |
float |
0.90 |
Luminosity threshold used for tissue selection. |
normalizer = StainingNormalizer("reinhard", lum_thr=0.95).fit(target)
normalized = normalizer.transform(image)
Customizing normalization parameters¶
Method-specific keyword arguments override the default configuration. Create and fit a new normalizer for each configuration, using the same target and source images to isolate the effect of individual parameters.
| Method | Parameter | Example values |
|---|---|---|
| Macenko | ang_per |
95, 97, 99 |
| Macenko | lum_thr |
0.7, 0.8, 0.9 |
| Vahadane | lum_thr |
0.7, 0.8, 0.9 |
| Vahadane | reg |
0.05, 0.1, 0.2 |
| Vahadane | max_iter |
5, 10, 30 |
| Reinhard | lum_thr |
0.8, 0.9, 0.95 |
The luminosity threshold influences which pixels contribute to tissue statistics or stain estimation. The angular percentile controls stain direction estimation in Macenko. In Vahadane, regularization influences sparse decomposition, while the iteration limit controls the optimization budget. These example values are intended for exploration, not as universally optimal settings.
Visual comparison of parameter settings¶
| compare_parameters.py | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | |
Unknown keyword arguments
The current factory implementation silently ignores unrecognized keyword arguments. For example, lum_thrr=0.7 does not override lum_thr. Use the exact parameter names listed for the selected method.
Parameter selection
Compare configurations on representative tissue patches and inspect the normalized results. Changing parameters may cause normalization to fail on some images. Refit the normalizer whenever its configuration or target changes.
Stain matrix extraction¶
HistoKit also provides standalone stain matrix extractors for Macenko and Vahadane. These can be used to inspect estimated stain color vectors independently of the normalization workflow.
| Extractor | Description |
|---|---|
MacenkoExtractor |
Estimates stain vectors using the Macenko method. |
VahadaneExtractor |
Estimates stain vectors using the Vahadane method. |
from histokit.stain_normalisation import MacenkoExtractor, VahadaneExtractor
extractors = {
"Macenko": MacenkoExtractor(),
"Vahadane": VahadaneExtractor(),
}
for name, extractor in extractors.items():
stain_matrix = extractor.get_stain_matrix(target)
print(name)
print(stain_matrix)
The returned stain matrix has shape (2, 3), with two unit-normalized stain vectors represented in three-dimensional optical density space.
Input requirements
Stain matrix extractors require RGB images with dtype uint8. Use representative tissue regions containing sufficient staining information rather than predominantly white background.
Output visualizations¶
The following example compares the original source image with the outputs of all three normalization methods using the same target image.
| compare_normalization.py | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
Normalizing multiple images¶
normalizer = StainingNormalizer("macenko").fit(target)
images = [
np.asarray(Image.open(f"img{i}.png").convert("RGB"))
for i in range(1, 5)
]
normalized_images = [normalizer.transform(img) for img in images]
fig, axes = plt.subplots(len(images), 2, figsize=(8, 4 * len(images)),
squeeze=False, layout="constrained")
for i, (original, normalized) in enumerate(zip(images, normalized_images)):
axes[i, 0].imshow(original)
axes[i, 0].set_title(f"Source {i + 1}")
axes[i, 1].imshow(normalized)
axes[i, 1].set_title("Normalized")
for ax in axes[i]:
ax.axis("off")
plt.show()
Integration with image augmentation¶
StainNormalizationTransform¶
Stain normalization can also be integrated into an image augmentation pipeline using StainNormalizationTransform. This transformation wraps a fitted normalizer and applies its transform() method with a specified probability.
| Parameter | Type | Default | Description |
|---|---|---|---|
normalizer |
object |
Required | Fitted normalizer implementing transform(img). |
prob |
float |
1.0 |
Probability of applying stain normalization. |
from histokit.augmentation import StainNormalizationTransform
normalizer = StainingNormalizer("macenko").fit(target)
transform = StainNormalizationTransform(normalizer=normalizer, prob=1.0)
normalized = transform(image)
Example pipeline¶
| normalization_pipeline.py | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
Normalization and augmentation
Stain normalization reduces color variability, whereas color augmentation introduces variability. Applying color jitter after normalization allows controlled color variations around a common reference appearance.
Normalization failure
If the wrapped normalizer raises an exception, StainNormalizationTransform emits a RuntimeWarning and returns a white image with the same shape and dtype as the input for standard RGB uint8 images. This fallback belongs to the augmentation wrapper; it should not be assumed for direct calls to StainingNormalizer.transform().
Inspect or exclude failed samples before using them for training.
Practical recommendations¶
- Select a representative target image with sufficient tissue and well-defined H&E staining.
- Avoid using predominantly white, empty, or very low-contrast patches for stain estimation.
- Reuse the same fitted normalizer when a consistent reference appearance is required.
- For machine learning experiments, select the reference from training data rather than held-out validation or test data.
- Visually inspect normalized images to ensure that relevant tissue structures remain distinguishable.
References¶
- Macenko, M., et al. (2009). A method for normalizing histology slides for quantitative analysis. IEEE International Symposium on Biomedical Imaging. DOI.
- Vahadane, A., et al. (2016). Structure-preserving color normalization and sparse stain separation for histological images. IEEE Transactions on Medical Imaging, 35(8), 1962–1971. DOI.
- Reinhard, E., et al. (2001). Color transfer between images. IEEE Computer Graphics and Applications, 21(5), 34–41. DOI.
Acknowledgements¶
The implementation of stain normalizers in HistoKit is inspired by the StainTools library, developed by Peter Byfield and released under the MIT License.