Sub topic 6
Photometric transforms: color, contrast, noise, and blur
This chapter assumes you know Python, can treat an image as an (H, W, C) array of pixel values, and have trained a classifier in PyTorch. Geometric transforms move pixels. Photometric transforms keep every pixel where it is and change its value. They simulate differences in lighting, camera sensors, and image quality.
Why photometric transforms matter
A model trained on photos from one camera under one kind of light can latch onto cues such as overall brightness or a color cast. Real deployment data varies in exposure, white balance, sensor noise, compression, and focus. Photometric augmentation trains the model to ignore these nuisance factors.
Because the pixel grid does not move, photometric transforms need no interpolation or border handling. They also leave masks and bounding boxes untouched. When you augment an image with a segmentation mask, apply photometric transforms to the image only.
Brightness, contrast, saturation, and hue
Each of these is a simple per-pixel formula. Assume pixel values are floats in [0, 1].
| Transform | Operation | Effect |
|---|---|---|
| Brightness | `x * b` | Scales every pixel. `b > 1` brightens, `b < 1` darkens. |
| Contrast | `(x - m) * c + m` | Scales distance from the mean gray level `m`. |
| Saturation | blend between grayscale and original | Controls color intensity. |
| Hue | rotate hue in HSV space | Shifts colors around the color wheel. |
After each operation the result is clipped back into the valid range. Clipping is a source of information loss: a heavily brightened image has many pixels stuck at 1.0, and that detail cannot be recovered by later transforms.
import torch
def adjust_brightness(img, b):
# img: float tensor (C, H, W) in [0, 1]
return (img * b).clamp(0.0, 1.0)
def adjust_contrast(img, c):
mean = img.mean(dim=(-3, -2, -1), keepdim=True)
return ((img - mean) * c + mean).clamp(0.0, 1.0)
torch.manual_seed(0)
img = torch.rand(3, 8, 8)
print(adjust_brightness(img, 1.5).max().item())
print(adjust_contrast(img, 0.5).std().item() < img.std().item())The second print shows True: lowering contrast shrinks the spread of pixel values.
ColorJitter in torchvision
torchvision.transforms.ColorJitter bundles the four adjustments. Each argument defines a range from which a factor is sampled on every call.
from torchvision import transforms
jitter = transforms.ColorJitter(
brightness=0.3, # factor sampled from [0.7, 1.3]
contrast=0.3, # factor sampled from [0.7, 1.3]
saturation=0.3, # factor sampled from [0.7, 1.3]
hue=0.05, # shift sampled from [-0.05, 0.05]
)Two details cause confusion:
- Brightness, contrast, and saturation take a float
xand sample a factor from[max(0, 1 - x), 1 + x]. Hue takes a float in[0, 0.5]and samples a shift in[-hue, hue], expressed as a fraction of the full color wheel. - By default
ColorJitterapplies the four adjustments in a random order on each call. This is intentional, because the operations do not commute.
Choosing ranges
Large hue shifts are the most dangerous. They can turn a ripe red tomato green or a blue sky orange. If color is part of the label (fruit ripeness, traffic lights, skin lesions, stained tissue), keep hue at 0 or very small, and consider limiting saturation changes too. If color is irrelevant (many object categories), larger ranges are fine. Chapter-level reasoning about label preservation applies here: ask whether a human annotator would still give the same label.
Grayscale conversion
RandomGrayscale(p=0.1) converts an image to grayscale with a given probability and keeps three channels, so the model's input shape does not change. It forces the model to rely on shape and texture occasionally. Use a low probability, because a model that sees mostly grayscale images may underuse color cues that are useful at test time.
Gamma and other tone curves
Gamma adjustment applies x ** g. With g < 1 it brightens midtones and with g > 1 it darkens them, while black (0) and white (1) stay fixed. It models exposure and display differences more faithfully than plain brightness scaling, because it does not push many pixels to the clipping limit. Torchvision exposes it as torchvision.transforms.functional.adjust_gamma, and libraries such as Albumentations provide RandomGamma.
Other useful tone operations include:
- Equalization and autocontrast, which stretch the histogram.
- Posterize, which reduces the number of bits per channel.
- Solarize, which inverts pixels above a threshold.
Posterize and solarize are rarely realistic. They appear mostly inside automated policies, covered in a later chapter.
Additive noise
Cameras produce noise, especially in low light. You can simulate it by adding random values to each pixel. Gaussian noise is the common choice.
import torch
class AddGaussianNoise:
def __init__(self, std_range=(0.0, 0.05), p=0.5):
self.std_range = std_range
self.p = p
def __call__(self, img):
# img: float tensor (C, H, W) in [0, 1]
if torch.rand(1).item() >= self.p:
return img
lo, hi = self.std_range
std = lo + (hi - lo) * torch.rand(1).item()
noisy = img + torch.randn_like(img) * std
return noisy.clamp(0.0, 1.0)Three points about this class:
- Noise is added before normalization, while pixels are still in
[0, 1]. If you add it afterNormalize, the samestdmeans something different, because normalized values have a different scale. - The noise strength is itself random. Sampling the standard deviation per image exposes the model to clean, mildly noisy, and heavily noisy inputs.
- It operates on tensors, so it belongs after
ToTensorand beforeNormalize.
Real sensor noise is not purely Gaussian. It is signal-dependent (Poisson-like shot noise) and often varies by channel. Salt-and-pepper noise and JPEG compression artifacts model other degradations. If your deployment images are JPEG-compressed at low quality, a JPEG-compression augmentation (available in Albumentations as ImageCompression) matches the target domain better than Gaussian noise does.
Blur and sharpness
Blur simulates defocus, motion, and low resolution. Torchvision provides GaussianBlur, which convolves the image with a Gaussian kernel.
from torchvision import transforms
blur = transforms.GaussianBlur(kernel_size=5, sigma=(0.1, 2.0))The kernel size must be odd and positive. sigma as a tuple is sampled uniformly per call. A kernel that is small relative to sigma truncates the Gaussian and gives weaker blur than expected, so keep kernel_size at roughly 6 * sigma_max rounded up to an odd number when you want the full effect.
Blur has a cost. It removes fine texture, and if your classes differ by fine detail (bird species, defects, text), strong blur can make the label ambiguous. Wrap it in RandomApply so it fires only some of the time:
from torchvision import transforms
maybe_blur = transforms.RandomApply(
[transforms.GaussianBlur(kernel_size=9, sigma=(0.1, 1.5))], p=0.3
)Sharpening is the inverse. RandomAdjustSharpness(sharpness_factor=2, p=0.3) increases sharpness, and a factor below 1 blurs the image.
Placing photometric transforms in a pipeline
Order matters, and so does the data type.
ColorJitter,GaussianBlur, andRandomGrayscaleaccept PIL images and tensors, so they can go beforeToTensor.- Custom tensor noise goes after
ToTensorand beforeNormalize. Normalizeshould come last among the photometric steps, because it assumes unmodified[0, 1]inputs for its mean and standard deviation.
from torchvision import transforms
mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.225]
train_tf = transforms.Compose([
transforms.RandomResizedCrop(224, scale=(0.5, 1.0)),
transforms.RandomHorizontalFlip(),
transforms.ColorJitter(brightness=0.3, contrast=0.3, saturation=0.3, hue=0.03),
transforms.RandomGrayscale(p=0.05),
transforms.RandomApply([transforms.GaussianBlur(9, sigma=(0.1, 1.5))], p=0.2),
transforms.ToTensor(),
AddGaussianNoise(std_range=(0.0, 0.03), p=0.3),
transforms.Normalize(mean=mean, std=std),
])This pipeline reuses the AddGaussianNoise class defined earlier. Apply none of these random photometric steps in the evaluation pipeline. Evaluation should be deterministic.
Common errors
- Hue too large. It silently changes class-defining colors. Inspect augmented samples before training.
- Noise after normalization. The noise scale no longer matches your intent, and clamping to
[0, 1]would destroy normalized values. - Clipping chains. Stacking strong brightness and contrast adjustments saturates pixels at 0 or 1. Check a histogram of augmented images.
- Applying photometric transforms to masks. A mask holds class IDs. Changing its values corrupts the labels.
- Mismatch with deployment. Augmenting with noise and blur that your real images never contain wastes capacity. Pick transforms that mimic the variation you expect to see.
- Applying the same random parameters to a whole batch. A transform called on a batched tensor samples one factor for the entire batch in many implementations. Apply per-sample transforms in the dataset, not on the collated batch, unless the library documents per-sample sampling.
Summary
Photometric augmentation varies lighting, color, noise, and focus without moving pixels. Choose ranges by asking which variations the deployment data contains and which image properties define the label. Keep the transforms on the image, place them before normalization, and apply them with moderate probabilities.
Exercise
Your task is classifying ripe versus unripe bananas from photos. You add ColorJitter(brightness=0.3, contrast=0.3, saturation=0.3, hue=0.4). Validation accuracy drops compared with having no color augmentation. Explain why, and propose a better setting.
Show answer
A hue range of 0.4 shifts colors across much of the color wheel, so yellow (ripe) bananas can look green (unripe) or other hues. The transform changes the label-relevant feature, so the labels become noisy. Set hue to 0 or a very small value such as 0.02, keep brightness and contrast jitter to simulate lighting changes, and use a modest saturation range. Then compare validation accuracy against the no-augmentation baseline.
Exercise
A teammate writes a pipeline ending with ToTensor, Normalize, then AddGaussianNoise(std_range=(0.0, 0.05)) that clamps to [0, 1]. What are two problems?
Show answer
First, after Normalize the values are no longer in [0, 1] (they are roughly zero-centered with a range of about -2 to 2.6), so clamping to [0, 1] removes all negative values and destroys the image. Second, the noise standard deviation of 0.05 is relative to a different scale than intended. Move the noise step between ToTensor and Normalize.
Exercise
You use GaussianBlur(kernel_size=3, sigma=(0.1, 5.0)). Why does the blur at high sigma look weaker than expected, and what kernel size would you use?
Show answer
A 3-pixel kernel truncates the Gaussian to a very narrow window, so even with sigma near 5 the effective blur is small. With sigma_max = 5, use a kernel size of about 6 * 5 = 30, rounded up to an odd number, so 31.