Image normalization for deep learning: value ranges, mean and std, histograms
Why a model needs the same pixel range it was trained on, how to divide by 255 and standardize each channel with a mean and std in PyTorch, and how bit depth and a histogram help you catch range bugs before training.
Image normalization is the fixed set of steps that turns the stored numbers of an image into the numbers a model learned from. A photo on disk usually holds whole numbers from 0 to 255, while many models expect decimals near 0 that can go negative. A model fed the wrong range raises no error. It reads numbers unlike anything it saw in training and its predictions get worse, even though the picture on screen looks normal.
Two common pixel ranges
A pixel in a color image is three numbers, one each for red, green and blue. Each of those numbers is a channel value. The same photo can reach a model in two common ranges:
- whole numbers from 0 to 255, stored as
uint8(an 8-bit unsigned integer, one byte per channel value) - decimals from 0 to 1, stored as
float32
Stored image files almost always use the first. Many model pipelines use the second, and some expect decimals from 0 to 255. Feed a model the wrong one and every number is 255 times too large or too small. No single convention covers every model, so check what each one expects.

Converting uint8 to float from 0 to 1
Going from 0 to 255 to 0 to 1 is one division by 255. A pixel of 255 becomes 1.0, and a pixel of 128 becomes about 0.502:
import torch
def to_float01(x_uint8):
# x_uint8: values 0 to 255
return x_uint8 / 255.0
x = torch.tensor([0, 128, 255], dtype=torch.uint8)
once = to_float01(x)
twice = to_float01(once)
print(once) # tensor([0.0000, 0.5020, 1.0000])
print(twice) # tensor([0.0000, 0.0020, 0.0039])Skip the division and every value is 255 times too large. Run it twice by mistake, for example once in a data loader and once in the model wrapper, and the brightest pixel becomes 0.0039. The model then sees an almost black image.

Integer math on pixels can go wrong without an error
A uint8 tensor only holds whole numbers from 0 to 255, so math on it can give a wrong answer with no warning:
import torch
a = torch.tensor([128], dtype=torch.uint8)
b = torch.tensor([200], dtype=torch.uint8)
dark = torch.tensor([1], dtype=torch.uint8)
print(a + b) # tensor([72], dtype=torch.uint8)
print(dark // 2) # tensor([0], dtype=torch.uint8)
print((a + b) // 2) # tensor([36], dtype=torch.uint8)
print((a.float() + b.float()) / 2) # tensor([164.])Adding 128 and 200 gives 328, which does not fit in a byte, so it wraps around to 72 instead of stopping at 255. The // operator divides and rounds down, so a dark pixel of 1 halved becomes 0, and a dark region can turn fully black. Averaging two images in uint8 overflows the same way: the average of 128 and 200 comes out as 36 instead of 164. Convert to float before doing math on pixels.

Why range bugs are hard to see
An image with the wrong range or dtype can look completely normal on screen. Image viewers rescale the values before drawing them, so a tensor in 0 to 1 and one in 0 to 255 both show the same picture. The model does no rescaling and reads the numbers as they are. Training and evaluation then go wrong while every picture you check looks fine.
So print the minimum and maximum of the tensor instead of trusting how the image looks. A max of 255 where you expected 1, or a max of 0.0039, tells you at once what happened.

Standardizing each channel with a mean and std
Dividing by 255 is usually only the first step. Many pipelines then standardize each channel: subtract a mean and divide by a standard deviation. The standard deviation (std) is a number that measures how spread out values are around their mean. Both numbers are fixed in advance, usually computed once over the training images, and each channel gets its own pair.
For one channel with mean $\mu$ and standard deviation $\sigma$, a value $x$ becomes:
$$x' = \frac{x - \mu}{\sigma}$$
The subtraction moves the channel's average to 0, and the division makes its spread about 1. Take $\mu = 0.5$ and $\sigma = 0.5$ as an example. A black pixel of 0 becomes $(0 - 0.5) / 0.5 = -1$, a mid-gray pixel of 0.5 becomes 0, and a white pixel of 1 becomes 1. Negative values after this step are expected.

The same steps have to run at training time and at inference time. If training used standardized inputs and inference does not, the model sees numbers unlike anything it was trained on.
Per-channel standardization in PyTorch
import torch
def normalize(x, mean, std):
# x: (3, H, W) float in [0, 1]
# mean, std: (3,) tensors, one value per channel
mean = mean[:, None, None]
std = std[:, None, None]
return (x - mean) / std
# a 1 by 3 image: a black, a mid-gray and a white pixel, the same in all 3 channels
x = torch.tensor([0.0, 0.5, 1.0]).repeat(3, 1).reshape(3, 1, 3)
half = torch.tensor([0.5, 0.5, 0.5])
print(normalize(x, half, half)[0]) # tensor([[-1., 0., 1.]])The image is stored channels first, as $(3, H, W)$. The mean and std tensors have shape $(3,)$, one value per channel. mean[:, None, None] reshapes them to $(3, 1, 1)$, so PyTorch applies each channel's value across that channel's whole height and width (this is broadcasting). The printed row is the red channel, and it matches the worked example: $-1$, $0$ and $1$.

If the output looks wrong, print the shapes of x, mean and std first. A mean left at shape $(3,)$ broadcasts against the width instead of the channels when the width is 3, and errors out otherwise.
Pretrained models come with their own numbers
A pretrained model has already been trained on a large dataset, so you download it and run it instead of training your own. It usually ships with a fixed image processor. The processor sets the resize, the channel order and the scaling, plus a mean and standard deviation per channel. Your preprocessing has to match it exactly.
Many models trained on ImageNet, a large dataset of labeled photos, expect these values:
$$\mu = [0.485,\ 0.456,\ 0.406]$$
$$\sigma = [0.229,\ 0.224,\ 0.225]$$
With them, a black pixel's red channel becomes $(0 - 0.485) / 0.229 = -2.12$, and a white pixel's blue channel becomes $(1 - 0.406) / 0.225 = 2.64$. So a correctly normalized ImageNet input runs from about $-2.1$ to $2.6$. Running the same three pixels through, once correctly and once without the division by 255, shows what printing the range catches:
imagenet_mean = torch.tensor([0.485, 0.456, 0.406])
imagenet_std = torch.tensor([0.229, 0.224, 0.225])
good = normalize(x, imagenet_mean, imagenet_std)
bad = normalize(x * 255, imagenet_mean, imagenet_std) # forgot to divide by 255
for name, t in (("good", good), ("bad", bad)):
print(f"{name}: min {t.min():.2f} max {t.max():.2f} mean {t.mean():.2f}")
# good: min -2.12 max 2.64 mean 0.23
# bad: min -2.12 max 1136.36 mean 562.22The minimum is the same in both runs, because a black pixel is 0 in both. Only the maximum shows the bug. Use different mean and std values from the ones a model was trained with and its predictions get much worse, even though the image on screen looks fine.

Before a batch goes in, read the processor config for the exact mean and std. Then run one known image through the full preprocessing and print the minimum, maximum and mean of the result, and check that the model's prediction for that image makes sense.

Bit depth: where 0 to 255 comes from
The 0 to 255 range comes from storing each channel value in 8 bits. Bit depth is how many bits each value gets, and it sets how many different levels a channel can hold. With $b$ bits, the number of levels $L$ is:
$$L = 2^{b}$$
So 8 bits give $2^8 = 256$ levels (0 to 255), 12 bits give 4096, and 16 bits give 65536. More levels means finer steps between one brightness and the next.

When there are too few levels for a smooth fade, the fade breaks into visible steps. This is called banding. A clear sky in an 8-bit image can show flat stripes instead of an even gradient.

Converting 16-bit to 8-bit
To show a 16-bit image on a normal screen, or to save it as an 8-bit file, rescale by its maximum value and round:
import torch
def to_8bit(x16, max_value):
# x16: torch tensor, 0 to max_value
scaled = x16 / max_value * 255.0
rounded = scaled.round().clip(0, 255)
return rounded.to(torch.uint8)
x16 = torch.tensor([0, 100, 200, 32768, 65535])
print(to_8bit(x16, 65535)) # tensor([ 0, 0, 1, 128, 255], dtype=torch.uint8)A 16-bit value of 32768 maps to $32768 / 65535 \times 255 = 127.5$, which rounds to 128. The values 0, 100 and 200 were three different levels in 16 bits, and two of them become the same 0 after the conversion. Those extra levels are gone for good, so train on the 16-bit data if the fine steps carry signal.

Unprocessed RAW files from cameras, medical scans and scientific images often use more than 8 bits. So does low-light photography. The extra levels keep detail in very dark and very bright areas, where 8 bits would band or lose it.

What a histogram shows
A histogram shows all of an image's values in one plot. It counts how many pixels fall at each brightness level: the x-axis runs from 0 to 255 and the y-axis is the number of pixels. It is one of the fastest ways to spot a range problem that the image on screen hides.

The shape tells you about brightness and contrast at a glance. A histogram bunched at the low end means a dark image, and one bunched at the high end means a bright image. A histogram spread across the whole range means high contrast. One squeezed into a narrow band means low contrast, as in a faded photo.

Spotting clipping
A camera can only record brightness within a certain span, from the darkest to the brightest light it can measure. That span is its dynamic range. Light beyond the bright end is stored as 255, and light below the dark end is stored as 0.
On a histogram this shows up as a tall spike right at 255 or right at 0. A spike at 255 means blown-out highlights, and a spike at 0 means crushed shadows. Those pixels lost their true values, and no later step can bring the detail back.

Computing an intensity histogram in PyTorch
A histogram puts each pixel into a bin, a range of values, and counts the pixels in each bin. With bins equal-width bins over 0 to 255, a value $v$ goes in bin $\lfloor v \cdot \text{bins} / 256 \rfloor$. For 4 bins, values 0 to 63 go in bin 0 and 64 to 127 in bin 1. Values 128 to 191 go in bin 2 and 192 to 255 in bin 3. So a value of 200 goes in bin $\lfloor 800 / 256 \rfloor = 3$.
import torch
def intensity_histogram(x, bins):
# x: torch uint8 tensor, values 0 to 255
v = x.to(torch.int64).flatten()
bin_idx = v * bins // 256
return torch.bincount(bin_idx, minlength=bins)
x = torch.tensor([
[12, 45, 78, 123, 200, 255],
[ 5, 33, 64, 200, 255, 255],
[ 0, 15, 70, 130, 210, 255],
[ 8, 42, 90, 160, 220, 255],
[ 2, 28, 55, 100, 180, 255],
[ 7, 60, 88, 128, 199, 255],
], dtype=torch.uint8)
counts = intensity_histogram(x, bins=4)
print(counts) # tensor([13, 7, 4, 12])
print(counts.sum().item()) # 36
print((x == 255).sum().item()) # 7x.to(torch.int64) widens the values first, because v * bins would overflow in uint8 for any $v$ above 63. .flatten() lays every pixel out in one row, and torch.bincount counts how many times each bin index appears. The counts add up to the 36 pixels in the image, and the tall last bin holds 7 pixels sitting exactly at 255. That is the clipping pattern from the section above, in a 6 by 6 image.
If the counts do not add up to the number of pixels, the overflow is the first thing to check.

Thresholding and dataset debugging
A histogram with two clear humps suggests that one brightness value between them can separate an object from its background, such as dark text on a light page. Picking that value and splitting the pixels at it is called thresholding: pixels above the value become 1 and pixels below it become 0.
Across a whole dataset, histograms also help with debugging. When the images' histograms fall into separate groups, the groups often come from different cameras, lighting or capture sessions. A model trained mostly on one group can do worse on the others.

When to use each step, and common mistakes
Divide by 255 whenever a model expects 0 to 1, which is common for PyTorch vision models. Add per-channel standardization when the model's processor says so, with the exact mean and std it lists. For a model you train from scratch, compute the mean and std on the training images only and reuse those numbers for validation, test and deployment. Reach for a histogram when a dataset looks off, before you change the model.
- Normalizing twice, or not at all. Two divisions by 255 give a nearly black image, and none gives values up to 255. Print the min and max after preprocessing.
- Doing math in uint8. Sums wrap around and
//rounds down. Convert to float first. - Using the wrong mean and std for a pretrained model. Copy them from the model's processor config rather than from another model.
- Trusting how the image looks. Viewers rescale before drawing, so a broken range can look perfect.
- Converting 16-bit data to 8-bit before training. The fine steps are lost for good. Keep the 16-bit values if they carry signal.
- Ignoring spikes at 0 or 255. They mean clipped pixels whose detail cannot be recovered. Fix the capture settings if you can.
Related concepts
How images are stored as tensors covers the shapes and dtypes these steps run on. Broadcasting explains how a $(3, 1, 1)$ mean reaches every pixel of its channel. Floating point for deep learning covers what float32 can and cannot hold. Data leakage shows why the mean and std should come from the training split alone.
QuiddityML teaches pixel ranges, per-channel normalization, bit depth and histograms in the images-as-data unit of its Computer Vision track. Learners there fill in and then write normalize, to_8bit and intensity_histogram from scratch. They also spot the bugs in a broken normalization and trace the shapes through per-channel standardization (QuiddityML).