Image Augmentation¶
HistoKit provides a collection of image transformations that can be composed into a pipeline. Image augmentation increases the diversity of training samples by introducing variations in tissue orientation, color appearance, image sharpness, noise, and compression quality.
Tutorial¶
Available transformations¶
| Category | Transformations |
|---|---|
| Geometric transformations | RandomFlip, RandomRotation |
| Color transformations | ColorJitter |
| Image blurring | GaussianBlur, MedianBlur, MotionBlur |
| Noise and image degradation | GaussianNoise, SaltAndPepper, JPEGCompression |
| Pipeline composition | Transform, Compose, OneOf |
Basic usage¶
Transformations accept NumPy arrays and return transformed images. For RGB transformations, use images with shape (H, W, 3), dtype uint8, and intensity values in [0, 255].
import numpy as np
from PIL import Image
from histokit.augmentation import GaussianBlur
image = np.asarray(Image.open("patch.png").convert("RGB"))
transform = GaussianBlur(sigma_range=(0.5, 2.0), prob=1.0)
augmented = transform(image)
Application probability¶
The Transform base class defines the probabilistic execution mechanism. Each call samples a random value and invokes apply() if the value is lower than prob. Otherwise, the original image is returned.
| Parameter | Type | Default | Description |
|---|---|---|---|
prob |
float |
0.5 |
Probability of invoking the transformation, in [0, 1]. Individual transformations default to 1.0. |
Application probability and random parameters
Setting prob=1.0 ensures that the transformation is always
executed, but its parameters may still be sampled randomly
on each call.
For example, GaussianBlur samples a random sigma value,
while RandomRotation randomly selects a rotation angle
from 0°, 90°, 180°, and 270°.
Consequently, a transformation may produce different results on successive calls or leave the input image unchanged (e.g., when a 0° rotation is selected).
Transformation parameters¶
Geometric transformations¶
Geometric transformations introduce orientation variability without interpolation of pixel values.
RandomFlip¶
Applies horizontal and vertical flips using independent random decisions inside apply().
| Parameter | Type | Default | Description |
|---|---|---|---|
prob |
float |
1.0 |
Probability of invoking the transformation and, conditionally, the probability of each axis flip. |
from histokit.augmentation import RandomFlip
augmented = RandomFlip(prob=0.5)(image)
Flip probability
The current implementation uses prob both in the base class and for each axis inside apply(). Consequently, prob=1.0 always flips both axes, while intermediate values can result in no flip, a single-axis flip, or a double flip.
RandomRotation¶
Rotates an image by a uniformly selected multiple of 90 degrees: 0°, 90°, 180°, or 270°.
| Parameter | Type | Default | Description |
|---|---|---|---|
prob |
float |
1.0 |
Probability of sampling and applying a rotation. |
from histokit.augmentation import RandomRotation
augmented = RandomRotation(prob=1.0)(image)
Spatial annotations
Geometric transformations operate on images only. Segmentation masks and spatial annotations must undergo the same sampled geometric transformation separately. Rotating a rectangular image by 90° or 270° swaps its height and width.
Color transformations¶
ColorJitter¶
Randomly modifies brightness, contrast, saturation, and hue. Brightness and contrast are adjusted in RGB space, whereas saturation and hue are adjusted in HSV space.
| Parameter | Type | Default | Description |
|---|---|---|---|
brightness_range |
tuple[float, float] |
(0, 0.3) |
Range used to sample the brightness adjustment. |
contrast_range |
tuple[float, float] |
(0, 0.3) |
Range used to sample the contrast adjustment around the per-channel mean. |
saturation_range |
tuple[float, float] |
(0, 0.3) |
Range used to sample the saturation adjustment. |
hue_range |
tuple[float, float] |
(0, 0.1) |
Hue shift range, expressed as fractions of the OpenCV hue scale. |
prob |
float |
1.0 |
Probability of applying color jitter. |
Brightness, contrast, and saturation are adjusted using randomly
sampled multiplicative factors. For example, a range of
(-0.1, 0.1) corresponds to factors between 0.9 and 1.1,
allowing both a decrease and an increase in the corresponding
image property.
Hue is adjusted by adding a randomly sampled shift in the HSV color space, preserving the circular nature of hue values.
from histokit.augmentation import ColorJitter
transform = ColorJitter(
brightness_range=(-0.1, 0.1),
contrast_range=(-0.15, 0.15),
saturation_range=(-0.1, 0.1),
hue_range=(-0.02, 0.02),
prob=1.0,
)
augmented = transform(image)
Disabling individual adjustments
Set any parameter range to (0, 0) to disable the corresponding adjustment.
Image blurring¶
Blur transformations can simulate reduced image sharpness and directional image degradation.
GaussianBlur¶
Applies Gaussian smoothing with a randomly sampled standard deviation. The kernel size is determined automatically by OpenCV.
| Parameter | Type | Default | Description |
|---|---|---|---|
sigma_range |
tuple[float, float] |
(0.3, 2.0) |
Range of Gaussian standard deviations, in pixels. |
prob |
float |
1.0 |
Probability of applying Gaussian blur. |
MedianBlur¶
Applies median filtering using a randomly sampled kernel size. Even sampled sizes are increased by one to obtain an odd kernel size.
| Parameter | Type | Default | Description |
|---|---|---|---|
size_range |
tuple[int, int] |
(3, 7) |
Range of median filter kernel sizes, in pixels. |
prob |
float |
1.0 |
Probability of applying median blur. |
MotionBlur¶
Constructs a linear blur kernel, rotates it by a randomly sampled angle, and applies it using two-dimensional convolution.
| Parameter | Type | Default | Description |
|---|---|---|---|
degree_range |
tuple[int, int] |
(5, 15) |
Range of motion blur kernel sizes, in pixels. |
angle_range |
tuple[float, float] |
(0, 360) |
Range of kernel rotation angles, in degrees. |
prob |
float |
1.0 |
Probability of applying motion blur. |
Noise and image degradation¶
GaussianNoise¶
Adds Gaussian-distributed noise to image intensities. The mean and standard deviation are sampled independently for each application. The resulting intensities are clipped to [0, 255] and converted to uint8.
| Parameter | Type | Default | Description |
|---|---|---|---|
mean_range |
tuple[float, float] |
(0.0, 6.0) |
Range of noise distribution means. |
std_range |
tuple[float, float] |
(10.0, 30.0) |
Range of noise standard deviations. |
prob |
float |
1.0 |
Probability of adding noise. |
SaltAndPepper¶
Randomly replaces selected pixels with black (pepper) or white (salt) values. Pixel locations are sampled with replacement, so the actual fraction of distinct affected pixels may be smaller than the sampled fraction.
| Parameter | Type | Default | Description |
|---|---|---|---|
amount_range |
tuple[float, float] |
(0.01, 0.05) |
Range of nominal fractions of pixels selected for noise. |
prob |
float |
1.0 |
Probability of adding salt-and-pepper noise. |
JPEGCompression¶
Encodes and decodes the image using JPEG compression at a randomly sampled quality level. Lower quality values generally introduce stronger compression artifacts.
| Parameter | Type | Default | Description |
|---|---|---|---|
quality_range |
tuple[int, int] |
(10, 50) |
Range of JPEG quality values, typically in [0, 100]. |
prob |
float |
1.0 |
Probability of applying JPEG compression. |
from histokit.augmentation import StainNormalizationTransform
# normalizer must be fitted beforehand.
transform = StainNormalizationTransform(normalizer=normalizer, prob=1.0)
normalized = transform(image)
Normalization failure
If normalization raises an exception, the transformation emits a RuntimeWarning and returns a white image with the same shape and dtype as the input (for standard uint8 RGB input). Inspect failed samples before using them for training.
Augmentation pipelines¶
Compose¶
Executes transformations sequentially in the specified order. The output of each transformation becomes the input of the next transformation.
| Parameter | Type | Default | Description |
|---|---|---|---|
transforms |
list |
Required | Ordered list of callable transformations. |
OneOf¶
Randomly selects one transformation from a non-empty list with probability prob. Selection is uniform, and the selected transformation retains its own application probability.
| Parameter | Type | Default | Description |
|---|---|---|---|
transforms |
list |
Required | List of callable transformations to select from. |
prob |
float |
0.5 |
Probability of selecting and invoking one transformation. |
Nested probabilities
For a group of \(n\) transformations, the probability of selecting and passing the probability gate of transformation \(i\) is \(p_{group}p_i/n\). This does not guarantee a visible image change. Set the individual probabilities to 1.0 if the group should control the application probability alone.
Example pipeline¶
| augmentation_pipeline.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 | |
Output visualizations¶
The following example generates a comparison of the original image and individual transformations.
import matplotlib.pyplot as plt
examples = {
"Original": image,
"Rotation": RandomRotation()(image),
"Flip": RandomFlip()(image),
"Color jitter": ColorJitter()(image),
"Gaussian blur": GaussianBlur(sigma_range=(2, 2))(image),
"Median blur": MedianBlur(size_range=(5, 5))(image),
"Motion blur": MotionBlur(degree_range=(11, 11))(image),
"Gaussian noise": GaussianNoise(std_range=(25, 25))(image),
"Salt and pepper": SaltAndPepper(amount_range=(0.04, 0.04))(image),
"JPEG compression": JPEGCompression(quality_range=(15, 15))(image),
"Pipeline": pipeline(image),
}
fig, axes = plt.subplots(3, 4, figsize=(12, 9), layout="constrained")
for ax in axes.flat:
ax.axis("off")
for ax, (title, result) in zip(axes.flat, examples.items()):
ax.imshow(result)
ax.set_title(title)
plt.show()
Reproducibility¶
HistoKit transformations use both Python's random module and NumPy's random number generator. Seed both before generating augmentations to reproduce the same sequence in a consistent execution environment.
import random
import numpy as np
random.seed(42)
np.random.seed(42)
augmented = pipeline(image)