A picture on a screen looks smooth, but a computer stores it as a table of numbers. Zoom in far enough and the picture disappears: you are left with a grid of tiny squares, and each square holds three numbers. Every model in this part of the course, from the first convolution to the networks that recognize faces and objects, works on that table. This lesson says exactly what is in it.
A picture is a grid of numbers
A black-and-white image is a matrix of brightness values. The plus sign from P1.B5 is the matrix with ones in the whole middle row and the whole middle column and zeros in the corners. Each entry is one pixel (short for “picture element”). In a grayscale image one number per pixel is enough: small means dark, large means bright.
A colour image needs more. Almost every colour image you will meet stores three numbers per pixel: how much red, how much green and how much blue light to mix. This is the RGB system. Each of the three numbers is a channel value, and a whole grid of one of them is called a channel. So a colour image is three grids stacked together: a red channel, a green channel and a blue channel.
The widget below shows a colour picture drawn by code (a sky, a sun, a house and some grass). At 1× you see the picture. Press 4× and the picture is cut to a window of pixels with the numbers written in each cell. Press 8× to see a window of pixels. Then try the other buttons.
Things to try, and what you should see:
- Zoom to 4×, Colour. The pixel at row 14, column 9 is a wall pixel with the numbers , , : a lot of red, a little green and blue. Mixed together, those three give the brick red you see at 1×.
- Switch to Gray. The same pixel is now one number, , and the shape line loses its last axis.
- Switch to Red, Green and Blue in turn. Each channel is a grid of its own. The sun is bright in the red and green channels and dark in the blue one, which is why it looks yellow when they are mixed.
- Switch to float. Every number is divided by 255. The picture does not change; only the way we write the numbers does.
The coordinates deserve a moment, because they are the first thing beginners get wrong. In a picture we say “ goes right and goes up”. In an image array the row comes first and rows count downward, starting from the top-left corner. The pixel img[14, 9] is in row 14 (the fifteenth row from the top, since we start at 0) and column 9. The shape (H, W, C) lists the height first (the number of rows) and then the width (the number of columns). Some libraries break the pattern: Pillow’s image.size is (width, height), the opposite order of the array shape.
Shapes: , , ,
Each axis of the array has a meaning, and the order depends on the library.
| Shape | Meaning |
|---|---|
| one grayscale image (NumPy) | |
| one image, channels last: expected by NumPy-style code, PIL and Matplotlib | |
| one image, channels first: PyTorch | |
| a batch of images in PyTorch | |
| a batch, channels last: NumPy, and Keras by default |
Here is the height in pixels, the width, the number of channels and the number of images in a batch. A few familiar sizes: an MNIST digit is with one channel; a CIFAR-10 image (60,000 small colour images in 10 classes) is with three. In PyTorch a grayscale image is still written with its channel axis, , because the layers expect it. An image with an extra opacity channel (RGBA) has , and satellite or medical images can have many more. The word “channel” also reappears inside networks: the outputs of a convolution layer are called channels too (P5.5).
Moving between the two layouts is a permutation of the axes, exactly as P1.B14 described. P1.B14 used a batch of 8 colour pictures of pixels: x.transpose(0, 3, 1, 2) in NumPy (or x.permute(0, 3, 1, 2) in PyTorch) turns (8, 32, 32, 3) into (8, 3, 32, 32), and transpose(0, 2, 3, 1) goes back. For one image the same idea is img.transpose(2, 0, 1) for and chw.transpose(1, 2, 0) for the way back.
Do not use reshape for this. A reshape reads the numbers in their stored order and cuts them into the new shape, so it keeps the same list and changes only where the cuts go. The result has the right shape and the wrong pixels: the image looks like noise, and no error tells you. A permutation moves each number to its new place.
PyTorch’s Conv2d layer expects input, and the Keras Conv2D layer takes channels-last input unless its data_format setting says otherwise (both documentations say so). Check the layout before you feed data into any layer. One more trap: OpenCV’s imread returns the three channels in the order blue, green, red, not red, green, blue, so a picture loaded with OpenCV looks wrong in Matplotlib until you convert it with cv2.cvtColor(img, cv2.COLOR_BGR2RGB).
Two ways to write a pixel value: uint8 and float
A pixel value is stored in one of two forms.
uint8: an unsigned integer from 0 to 255, one byte. This is what image files and cameras give you. is black (or none of that colour) and is the most of it.- float: a real number, usually between 0 and 1, usually 4 bytes (
float32). This is what neural networks want.
To convert, divide by 255: . The pixel becomes . To go back, multiply by 255, round, and clip to the range 0 to 255 before you cast to uint8.
Mixing the two forms is a rich source of silent bugs. Three of them:
- Overflow. A
uint8has only 256 values and arithmetic wraps around. Adding 50 to the values , , gives , and : , and . A “brighter” picture gets dark spots, and nothing raises an error. Do arithmetic in a wider type (int16or float) and clip at the end. - 255 times too bright. A float image is expected to lie between 0 and 1. If you pass values from 0 to 255 to a plotting function it clips everything above 1 and shows white; if you pass them to a network trained on 0-to-1 inputs, every input is 255 times too large, and the first layer’s outputs are far from anything it was trained on.
- Truncation. Casting a float in straight to
uint8cuts off the fraction: becomes , and only exactly survives, so the picture is black. The fix isnp.round(x * 255).astype(np.uint8).
The first cell below runs all three.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Note that dividing by 255 gives a float64 array, because NumPy keeps 64-bit floats by default. A network wants float32, so convert with astype(np.float32).
How much memory an image takes
The memory of an array is the number of entries times the bytes per entry: , with for uint8 and for float32.
- A RGB image (the usual input size of many ImageNet models) has entries: bytes (147 KiB) as
uint8, and bytes (588 KiB) asfloat32. - A batch of 32 such images as
float32takes bytes, which is 18.4 MiB (about 19.3 million bytes), before any layer has computed anything. - A single photo as
uint8has bytes, about 5.9 MiB.
(One MiB is bytes. File sizes you see on disk are much smaller because files are compressed; the array in memory is not. Image file formats are not covered here.) Memory is why networks work on small images such as and not on full photos, and why datasets are kept as uint8 and converted to float one batch at a time.
Normalizing each channel
Pixel values from 0 to 1 are better than 0 to 255, but a network usually learns faster and more reliably when the inputs are also centred near 0 and have a similar spread, the same reason features are scaled in P3.A11 and weights are initialized with care in P4.12. For images we do it per channel: subtract the channel’s mean and divide by its standard deviation ,
where is already a float between 0 and 1. The three channels have different means (the ImageNet values below are for red and for blue), so each gets its own pair.
If your network was pretrained on ImageNet, use the preprocessing that goes with its weights. For ResNet-style models the torchvision documentation says that images are resized to 256, centre-cropped to 224, rescaled to 0 to 1, and then normalized with
Other models use other sizes with the same mean and standard deviation, so use the preprocessing listed for the exact weights you load. A pretrained model has only ever seen inputs prepared this way, so a different preparation sends it inputs it does not know. If you train from scratch, compute your own and over the training set only (using the test set would be leakage, P3.A11).
The worked example is our pixel . As floats it is . Normalized with the ImageNet values:
For a whole tensor, the mean and the standard deviation are written as arrays of shape , so that broadcasting (P1.B14) stretches each across the height and the width. A mean of shape would be lined up with the last axis, the width, and fail or, worse, give wrong results when the width happens to be 3. For an array the right shape is , because the channel is the last axis. The second cell checks the shapes, the memory sizes, the transposes, the normalization and the gray values of the next section.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
The normalized pixel in the output is the one computed by hand above.
From colour to gray: luma weights
To turn an RGB pixel into one gray number you could average the three channels. The standard way is a weighted sum instead. The weights used for the standard-definition video system called ITU-R BT.601 are
They add up to 1, so a gray pixel stays . The quantity is called luma. The weights are not equal because our eyes are most sensitive to green and least sensitive to blue. Pure green gives , pure red and pure blue , whereas the plain mean gives for all three. Our pixel gives , against for the mean. (Pillow’s convert("L") documents exactly these weights. Torchvision’s rgb_to_grayscale uses for red, which differs only in the fourth digit.)
Go deeper Other weights, luma and gamma
BT.601 is the standard for standard-definition video. The standard for high-definition video, ITU-R BT.709, uses , and for red, green and blue; the pixel then has . Libraries differ in which one they use for “gray”, and for a model the difference is small, but it is a reason to convert with the same function in training and in use.
Pixel values in most images are stored with a curve (gamma) applied. Applying the weights directly to those stored values gives luma, which is what the formula above computes. The physical brightness, luminance, is a weighted sum of linear light, a slightly different number. Most machine learning code uses luma.
HSV: another way to write a colour
RGB mixes colour and brightness: making a pixel darker changes all three numbers. HSV writes the same colour as three other numbers: hue (which colour, as an angle around a colour wheel: red , green , blue ), saturation (from gray, 0, to the pure colour, 1) and value (brightness, equal to the largest of , , scaled to 0 to 1). Python’s standard colorsys module converts: the pixel has hue (an orange-red), saturation and value . Halve all three RGB numbers and only the value halves; the hue and the saturation stay the same. That makes HSV handy for tasks like “find the red things”, because changing only the brightness changes only (coloured light changes the hue too). Because hue is an angle, red sits at both and , so hue is awkward as a direct network input. Most vision networks simply take RGB and learn what they need.
Flattening an image for an MLP
The MLP of P4.3 and P4.10 takes one vector as input. The obvious way to feed it a picture is to flatten it: read the pixels row by row (and channel after channel) into one long list, exactly as P1.B1 did with a image. A MNIST digit becomes a vector with 784 entries, a colour image 3,072, and a colour image 150,528.
This works for MNIST, but it has two costs, and both lead to the next lesson.
The parameters explode. A first layer with 100 hidden units on a flattened image has parameters. On a flattened image with 1000 hidden units it has , for one layer. Every pixel gets its own weight to every unit.
The neighbours are lost. In the vector, pixel sits at position . Its right neighbour is one place away, but its neighbour below is places away, and nothing in the vector, or in the dense layer, knows that these two are close in the picture. The layer treats position 19 and position 27 as unrelated inputs, with unrelated weights. And since each position has its own weights, a shape that moves by one pixel looks like a different input. The widget below makes this visible with an drawing of a “7”.
Shift the “7” one column to the right: 14 of the 64 entries differ, and of its 18 ink pixels only 11 are still on ink. Shift it by two columns and 26 entries differ while only 4 ink pixels stay on ink. A dense layer with a separate weight for each position has no way to know that the shifted picture shows the same digit. It has to learn each position separately, from examples of the digit at every position. (Augmentation, P4.18, supplies such examples; it does not remove the cost.)
The fix is to keep the image as a grid and use the same small set of weights at every position. That is a convolution, the subject of P5.2. Everything in this lesson (the axes, the channels, the value range) stays the same; only the layers change.
Depth: three ways to see it
Intuition
Think of a colour image as three transparent sheets stacked on top of each other: one printed with how much red each pixel gets, one with green and one with blue. Each sheet is an ordinary grayscale image. Shine light through all three and the colours mix. In the channels-first layout you have a stack of three sheets. In the channels-last layout you have one sheet of pixels, and each pixel holds a little list of three numbers.
The picture breaks down in two places. A real display adds light, while sheets of colour filters would subtract it, so the image of stacked sheets is only a way of seeing the layout and not of mixing colours. And inside a network, “channels” stop meaning colours after the first layer: a channel is simply one grid of numbers (P5.5).
Math
Write one image in the NumPy layout as , with entries for row , column , channel (the values are integers in as uint8 or reals in as float). Moving to channels first is the permutation . The number of entries is , and the memory is bytes for bytes per entry.
Flattening maps to a vector in , and a dense first layer with units has parameters. For one channel, pixel goes to index , so a shift of the image by columns moves the index of every pixel by (except pixels that wrap to another row or leave the image). A weight vector that suits the original picture is then applied to different pixels.
Code
The PyTorch version of the preparation steps, using torchvision’s transforms. PyTorch is not available in the browser, so this block is not runnable here; its output was produced by a local run with PyTorch 2.9.1 and torchvision 0.24.1.
import numpy as np
import torch
from torchvision.transforms import v2
rng = np.random.default_rng(0)
arr = rng.integers(0, 256, size=(224, 224, 3), dtype=np.uint8) # (H, W, C)
t = v2.ToImage()(arr) # (C, H, W), still uint8
print(t.shape, t.dtype)
t = v2.ToDtype(torch.float32, scale=True)(t) # divide by 255
print(t.shape, t.dtype, float(t.max()) <= 1.0)
norm = v2.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
z = norm(t)
print(z.shape)
batch = torch.stack([z] * 32) # (N, C, H, W)
print(batch.shape, batch.nelement() * batch.element_size())
hwc = batch[0].permute(1, 2, 0) # back to (H, W, C)
print(hwc.shape, hwc.is_contiguous())
print(v2.Grayscale()(t).shape) # one channeltorch.Size([3, 224, 224]) torch.uint8
torch.Size([3, 224, 224]) torch.float32 True
torch.Size([3, 224, 224])
torch.Size([32, 3, 224, 224]) 19267584
torch.Size([224, 224, 3]) False
torch.Size([1, 224, 224])ToImage turns the array into a tensor, and ToDtype(..., scale=True) divides integers by 255. After permute the tensor is a view of the same memory with its axes swapped, and is_contiguous() is False: see the Go-deeper box on memory layout.
Go deeper Views, contiguity and channels-last memory
transpose in NumPy and permute in PyTorch do not copy the data. They return a view: the same memory with new rules for stepping through it. The result is no longer stored in the plain row-major order, which NumPy reports as flags['C_CONTIGUOUS'] == False and PyTorch as is_contiguous() == False. Most operations work on such a view without trouble, but some (for example PyTorch’s .view) need .contiguous() first, which makes a real copy. Separately, PyTorch can store a tensor with its channels last in memory (the “channels-last” memory format) while still reporting the shape , because on some hardware that order is faster. That is a performance setting, and it does not change what any indexing expression returns.
Go deeper Per-image standardization, and other number types
Instead of dataset-wide statistics, some pipelines standardize each image on its own: subtract that image’s mean and divide by its standard deviation (over all its pixels, or per channel). This removes differences in overall brightness and contrast between images, and needs no statistics from a dataset. It is a different choice from the per-channel dataset statistics above, and a model should be given the preparation it was trained with. Besides uint8 and float32, you will meet 16-bit integers (some medical and satellite images, with values up to 65,535) and half-precision floats such as float16 and bfloat16, which halve the memory of a float32 and are used to speed up training.
Try it in Python
The last cell reproduces the widget. It flattens the “7” (a list of strings, turned into numbers), looks up the positions of two neighbours and shifts the picture.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
The counts match the widget. Change the strings to draw your own picture, or shift it down by changing the code.
Common mistakes
Quiz
Check your understanding
A
uint8array holds the pixel value . What doesvalue + 50give in NumPy, if the result stays auint8?A
uint8holds only to , and arithmetic wraps around: and . The value does not fit in one byte. The value is what you would get by clipping after computing in a wider type, which is not what the plain addition does. NumPy does not raise an error for this array addition, which is exactly why the bug is silent.In PyTorch, what is the usual shape of a batch of 16 colour images that are 64 pixels high and 48 pixels wide?
PyTorch batches are : batch size, channels, height, width. The shape with the channels last, , is the NumPy and Keras layout. The shape with the batch axis after the channels is not a layout that PyTorch layers expect. The shape with a trailing axis of size 1 has no meaning here.
A float tensor of shape is normalized with a per-channel mean. Which shape of the mean array lets broadcasting subtract the right value from each channel?
Broadcasting lines shapes up from the right. A mean of shape is stretched along the height and the width, and its three values meet the three channels. A mean of shape would be lined up with the last axis, the width, and fail because . The shape is the right shape for a channels-last array, not this one. A mean of shape has no channel axis at all.
A grayscale image is flattened into a vector for an MLP. The digit in it moves one pixel to the right. Why can the MLP treat the result as a very different input?
Each ink pixel lands in another position of the vector, and the first layer has a separate weight for every position, so the same shape meets different weights. A shift changes no number type and no vector length: the vector always has entries. Flattening reads the pixels in a fixed row-by-row order and does not sort them by brightness.
Why does the gray conversion use the weights , and and not a plain average of red, green and blue?
The luma weights give each channel a share that matches how bright it looks to a person: green the most and blue the least. The memory of the gray image is the same whichever weights are used. An average of
uint8values can be computed. The range of the result is the same for both: the weights add up to 1, so a gray result stays between 0 and 255 foruint8input and between 0 and 1 for float input.
Exercises
- Three RGB photos are held in memory as
uint8. How many bytes is that, and about how many MiB?Show answer
Each photo has bytes, so three have bytes, which is about MiB (divide by ). - The
uint8array[250, 10]gets and, separately, . What are the two results?Show answer
for the addition () and for the subtraction (, and ). Both wrap around. - A PyTorch tensor has shape . What is the shape of the same image as a NumPy array, and which call gets it there?
Show answer
, witht.permute(1, 2, 0)(ornp.transpose(a, (1, 2, 0))for a NumPy array). A reshape to would give the right shape and scrambled pixels. - A one-channel image has the
uint8pixel value , a channel mean of and a standard deviation of . What is the normalized value?Show answer
First divide by 255: . Then , about . - A flattened grayscale image feeds a dense layer with 128 units. How many parameters does the layer have?
Show answer
: one weight per input and unit, plus one bias per unit. - What is the BT.601 gray value of the pixel , and what does the plain mean give?
Show answer
. The plain mean gives . The blue value counts for little in luma, so the gray is darker than the mean.
Next: P5.2 introduces the convolution operation, which slides a small set of weights over the picture and so uses neighbours and shifts instead of losing them. P5.3 builds hand-made kernels, P5.4 covers padding and stride, and P5.5 returns to channels: a convolution that mixes the channel axis. The same arrays also appear in augmentation (P4.18) and in normalization layers (P4.19).