◆ AI All-in-One

Level 3 In-Depth AI · Vision, Audio and Multimodal

Images as Data

To a computer a picture is a grid of numbers, one per pixel per colour channel. This chapter shows how images are stored, loaded, resized and normalised into the tensors that vision models eat.

Level
●●●●● Beginner
Reading
13 min
To learn it well
40 minutes to read, an hour to practise
↗ Plan a path here

Read first

Tensors and Shapes

This leads to

Image Classification
The full path from zero — 3 concepts before this one
  1. Vectors
  2. Matrices and Matrix Multiplication
  3. Tensors and Shapes
  4. Images as Data

Read them roughly in this order. See it on the concept map →

Why it matters

Before a model can recognise a cat, find a pedestrian or read a receipt, the photo has to become numbers. Every vision system in this part of the guide starts the same way: classifiers, detectors, segmentation models, vision Transformers, CLIP and the multimodal chatbots that answer questions about your screenshots. All of them take a tensor of pixel values as input.

Getting that tensor right is unglamorous, and it is where a surprising number of real bugs hide. A model trained on colours in one order and fed them in another, or trained on values between 0 and 1 and fed values up to 255, will run without any error message and quietly give bad answers. If you understand what an image tensor contains, you can spot those bugs in seconds.

The intuition

Think of a mosaic. From across the room you see a face. Up close you see that it is made of small square tiles, each a single flat colour. A digital image is exactly that: a rectangular grid of tiles called pixels (short for "picture elements"), and each pixel stores one colour as a few numbers.

For a black-and-white picture, one number per pixel is enough: how bright, or how much ink. Here is a real handwritten digit from scikit-learn's digits dataset, the kind of image the first neural networks learned to read:

0 0 5 13 9 1 0 0 0 0 13 15 10 15 5 0 0 3 15 2 0 11 8 0 0 4 12 0 0 8 8 0 0 5 8 0 0 9 8 0 0 4 11 0 1 12 7 0 0 2 14 5 10 12 0 0 0 0 6 13 10 0 0 0 What you seeWhat the computer getsan 8 × 8 picture of a “0”an 8 × 8 grid of numbers0 = blank paper … 16 = full inkOne pixelrow 2, column 5brightness 11Shapeheight × width = 8 × 8= 64 numbersA phone photo4032 × 3024 pixels× 3 colours ≈ 36.6 millionnumbers
Fig. 1 A handwritten zero as you see it (left) and as the computer receives it (right): an 8 × 8 grid of numbers from 0 (blank) to 16 (full ink). The highlighted pixel is in row 2, column 5 and has value 11.

The computer never "sees" the round shape on the left. It gets the 64 numbers on the right. Everything a vision model learns, whether edges, textures or whole objects, it learns from patterns in such numbers.

For colour, each pixel needs three numbers: how much red, how much green and how much blue light to mix. Your screen does this physically: every pixel on it is three tiny lights. Storing the three amounts separately gives three grids of the same size, called channels.

Colour image4 × 4 pixels split 255 255 0 0 255 255 0 0 0 0 255 255 0 0 255 255 Red channel4 × 4 numbers 0 0 255 255 0 0 255 255 0 0 255 255 0 0 255 255 Green channel4 × 4 numbers 0 0 0 0 0 0 0 0 255 255 255 255 255 255 255 255 Blue channel4 × 4 numbers One pixel = three numberstop-left: [R, G, B] = [255, 0, 0] → red[255, 255, 255] → white, [0, 0, 0] → black As one tensorPillow / NumPy(H, W, C) = (4, 4, 3)channels lastPyTorch(C, H, W) = (3, 4, 4)channels firstA batch of 32(N, C, H, W)= (32, 3, 4, 4)
Fig. 2 A 4 × 4 colour image split into its red, green and blue channels. Each pixel is three numbers, one per channel. NumPy and Pillow store them as (height, width, channels); PyTorch puts channels first.

Key idea An image is a 3-D block of numbers: height × width × channels. A greyscale image has 1 channel, a colour image has 3 (red, green, blue). Everything else in this chapter is about getting those numbers into the right range, size and order.

How it works

Pixels, bit depth and resolution

Each channel value is usually stored as an 8-bit unsigned integer (uint8): a whole number from 0 to 255. The number of bits per value is the bit depth. Eight bits give 28=2562^8 = 256 levels per channel, and three channels give 2563=16,777,216256^3 = 16{,}777{,}216 possible colours. That is the "16.7 million colours" in old monitor adverts. Medical scans, raw camera files and HDR images use 10, 12 or 16 bits for finer gradations, so always check the range of your data rather than assuming 255.

The resolution is the number of pixels: width × height. A 12-megapixel phone photo is about 4032 × 3024 pixels. With three channels that is 4032×3024×3≈36.64032 \times 3024 \times 3 \approx 36.6 million numbers. Models almost never take images that large. A classic ImageNet classifier takes 224 × 224 pixels, which is 150,528 numbers. As 32-bit floats that is about 0.6 MB per image, so a batch of 256 images is about 154 MB of input alone, before the model computes anything. This cost is why images get shrunk before they go in.

The aspect ratio is width divided by height: 4:3 for most phone photos, 16:9 for video. Squashing a 4:3 photo into a 224 × 224 square distorts it. The usual fix is to resize so the shorter side matches, then crop the middle.

Rows, columns and the order of axes

A pixel is addressed by its row (counted from the top) and its column (counted from the left). So img[2, 5] is row 2, column 5, starting from 0. Note that this is (y, x), not the (x, y) order of a maths graph. Mixing the two up is a classic source of transposed images and misplaced boxes.

The three axes can be stored in two orders:

  • Channels last, shape (H,W,C)(H, W, C): the pixels of each row sit next to each other, with each pixel's R, G and B values side by side. This is how image files, Pillow, NumPy, OpenCV and matplotlib work.
  • Channels first, shape (C,H,W)(C, H, W): the whole red grid, then the whole green grid, then the whole blue grid. This channels-first layout is what PyTorch's convolution layers expect.

Models process many images at once, stacked into a batch. In PyTorch a batch of 32 colour images of 224 × 224 pixels has shape (32,3,224,224)(32, 3, 224, 224), written (N,C,H,W)(N, C, H, W) and often called NCHW. Converting a single image from (H,W,C)(H, W, C) to (C,H,W)(C, H, W) is a transpose of the axes, not a reshape. A reshape would keep the numbers in memory order and scramble the picture.

Colour spaces

RGB is one colour space, one way of describing a colour with numbers. Others exist because they make certain jobs easier:

  • Greyscale keeps only brightness, one channel. It is not the plain average of R, G and B, because the eye is most sensitive to green and least to blue. The standard weights (from the ITU-R BT.601 television standard, and the ones Pillow uses) are:
Y=0.299 R+0.587 G+0.114 BY = 0.299\,R + 0.587\,G + 0.114\,B

Here YY is the brightness, and RR, GG, BB are the channel values. The weights add up to 1, so white (255, 255, 255) stays 255.

  • HSV (hue, saturation, value) separates "which colour" from "how vivid" and "how bright". It is handy for hand-written rules like "find the orange pixels" and for colour augmentation.
  • YCbCr separates brightness from colour. JPEG compression uses it, storing colour at lower resolution than brightness, because the eye notices brightness detail more.
  • BGR is RGB with the channels in reverse order. OpenCV loads images this way for historical reasons.

One more subtlety: stored pixel values are not proportional to physical light. Standard images use the sRGB encoding, which applies a "gamma" curve so that the 256 levels are spread in a way that matches human perception. For deep learning you can mostly ignore this, as long as training and use see the same encoding.

From file to tensor

Image files are compressed. JPEG throws away detail the eye barely notices (it is "lossy") and suits photos. PNG keeps every pixel exactly (it is "lossless") and suits screenshots, diagrams and masks. Loading an image means decoding the file back into the full grid of pixels. The usual pipeline before a model is:

  1. Decode the file into an (H,W,3)(H, W, 3) array of uint8. Convert to RGB, since some files are greyscale, have a fourth transparency channel (RGBA) or use a palette.
  2. Resize so the shorter side is, say, 256 pixels, keeping the aspect ratio.
  3. Crop the central 224 × 224 square.
  4. Convert to floats and divide by 255, so values lie between 0 and 1.
  5. Normalise each channel.
  6. Transpose to (3,224,224)(3, 224, 224) and stack into a batch.

Normalisation

Neural networks train best when their inputs are centred around 0 with a spread of about 1 (the Data Cleaning and Preparation chapter explains why). Image normalisation does this per channel: subtract the channel's mean and divide by its standard deviation.

x′=x−μcσcx' = \frac{x - \mu_c}{\sigma_c}

Here xx is a pixel value already scaled to 0–1, μc\mu_c is the average value of channel cc over the training images, and σc\sigma_c is its standard deviation. For models trained on ImageNet, almost everyone uses the ImageNet statistics:

Channel Mean μ\mu Std σ\sigma
Red 0.485 0.229
Green 0.456 0.224
Blue 0.406 0.225

Worked example. Take a pure red pixel, (255, 0, 0).

  1. Scale: (255/255, 0/255, 0/255)=(1.0, 0.0, 0.0)(255/255,\ 0/255,\ 0/255) = (1.0,\ 0.0,\ 0.0).
  2. Red channel: (1.0−0.485)/0.229=0.515/0.229≈2.249(1.0 - 0.485) / 0.229 = 0.515 / 0.229 \approx 2.249.
  3. Green channel: (0.0−0.456)/0.224≈−2.036(0.0 - 0.456) / 0.224 \approx -2.036.
  4. Blue channel: (0.0−0.406)/0.225≈−1.804(0.0 - 0.406) / 0.225 \approx -1.804.

So the model sees red as (2.249,−2.036,−1.804)(2.249, -2.036, -1.804). A mid-grey pixel of about (124, 116, 104) maps to roughly (0,0,0)(0, 0, 0), the "average" colour of ImageNet photos.

The rule that matters: use exactly the preprocessing the model was trained with. A pretrained model's documentation (or its bundled transform) tells you the size, the crop and the mean and standard deviation. CLIP, for example, uses different normalisation numbers from ImageNet classifiers.

In code

First, a tiny colour image built by hand in NumPy, converted to greyscale, normalised and rearranged for PyTorch:

import numpy as np

# A tiny 4 x 4 colour image: height x width x channels (RGB), values 0-255
img = np.zeros((4, 4, 3), dtype=np.uint8)
img[:2, :2] = [255, 0, 0]       # top-left block: red
img[:2, 2:] = [0, 255, 0]       # top-right block: green
img[2:, :2] = [0, 0, 255]       # bottom-left block: blue
img[2:, 2:] = [255, 255, 255]   # bottom-right block: white

print(img.shape, img.dtype)     # (4, 4, 3) uint8
print(img[0, 3])                # [  0 255   0]  row 0, column 3 is green

# Greyscale: weighted sum of the channels (ITU-R BT.601 weights)
grey = img @ np.array([0.299, 0.587, 0.114])
print(grey[::2, ::2].round(1))  # [[ 76.2 149.7]
                                #  [ 29.1 255. ]]  green looks brighter than red

# Scale to 0-1, then standardise each channel
x = img.astype(np.float32) / 255.0
mean = np.array([0.485, 0.456, 0.406])   # ImageNet channel means
std = np.array([0.229, 0.224, 0.225])    # ImageNet channel stds
x = (x - mean) / std
print(x[0, 0].round(3))         # [ 2.249 -2.036 -1.804]  the red pixel

# HWC -> CHW (PyTorch layout), then add a batch dimension
x = x.transpose(2, 0, 1)[None]
print(x.shape)                  # (1, 3, 4, 4)

Now a real dataset. scikit-learn ships 1,797 handwritten digits as 8 × 8 greyscale images, no download needed:

import torch
from sklearn.datasets import load_digits

digits = load_digits()                  # 1,797 handwritten digits, 8 x 8 pixels
print(digits.images.shape, digits.images.max())   # (1797, 8, 8) 16.0

x = torch.tensor(digits.images, dtype=torch.float32)
x = x / 16.0                            # pixel values run 0-16 here
x = x.unsqueeze(1)                      # add a channel axis: (N, C, H, W)
print(x.shape)                          # torch.Size([1797, 1, 8, 8])

mean, std = x.mean(), x.std()           # statistics of the training data
x = (x - mean) / std
print(round(mean.item(), 3), round(std.item(), 3))   # 0.305 0.376
print(round(x.mean().item(), 3), round(x.std().item(), 3))  # 0.0 1.0

For real photo files, the standard tools are Pillow to open them and torchvision's transforms to prepare them. This is the usual preprocessing for an ImageNet-trained model (cat.jpg is any photo you have):

import torch
from PIL import Image, ImageOps
from torchvision.transforms import v2

preprocess = v2.Compose([
    v2.ToImage(),                                  # PIL image -> uint8 tensor (C, H, W)
    v2.Resize(256),                                # shorter side -> 256 px
    v2.CenterCrop(224),                            # middle 224 x 224
    v2.ToDtype(torch.float32, scale=True),         # 0-255 -> 0.0-1.0
    v2.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])

img = Image.open("cat.jpg")
img = ImageOps.exif_transpose(img).convert("RGB")  # honour phone rotation, drop alpha
x = preprocess(img).unsqueeze(0)                   # (1, 3, 224, 224), ready for a model

Common pitfalls

  • Wrong value range. Feeding 0–255 values to a model trained on normalised 0–1 inputs gives confident nonsense. Print x.min(), x.max() and x.mean() just before the model. Normalised ImageNet-style inputs should sit roughly between −2.1 and +2.6.
  • BGR versus RGB. OpenCV's cv2.imread returns BGR. Pass that to an RGB-trained model and skies turn orange. Convert with cv2.cvtColor(img, cv2.COLOR_BGR2RGB).
  • Channels in the wrong place. PyTorch layers want (N,C,H,W)(N, C, H, W). If an error says the input was "expected to have 3 channels, but got 224 channels instead", you passed (N,H,W,C)(N, H, W, C). Use permute, not view or reshape.
  • Integer overflow. Arithmetic on uint8 wraps around: np.uint8(200) + np.uint8(100) is 44, not 300. Convert to float before doing maths.
  • Rotated phone photos. Phones often save the pixels sideways and store "rotate me" in the file's EXIF metadata. Pillow ignores that unless you call ImageOps.exif_transpose.
  • Extra or missing channels. PNGs may have a fourth alpha (transparency) channel, and some JPEGs are greyscale. Call .convert("RGB") so every image has exactly three.
  • Distorting the aspect ratio. Resizing straight to a square squashes faces and cars. Resize the short side and crop, or pad.

Watch out Preprocessing at prediction time must match training exactly: same resize method, same crop, same channel order, same normalisation numbers. A mismatch raises no error. It just makes the model quietly worse, sometimes by a lot.

Where it leads

  • Convolutional networks slide small filters over exactly these grids of numbers. Image Classification trains one end to end.
  • Data Augmentation randomly flips, crops and recolours images during training so that models learn what matters and ignore what doesn't.
  • Vision Transformers cut the same tensor into 16 × 16 patches and treat them like words.
  • Video adds a time axis, giving tensors of shape (N,T,C,H,W)(N, T, C, H, W).
  • Sound can be turned into a spectrogram, an "image" of frequencies over time, so the same tools apply to audio.
  • Document AI works on scans and screenshots, where resolution matters a lot because small text vanishes when shrunk.

A bit of history

The word "pixel" appeared in the 1960s, in work on processing images sent back by space probes. Russell Kirsch's team at the US National Bureau of Standards scanned what is usually called the first digital photograph in 1957: a picture of Kirsch's baby son, 176 pixels on a side. The standard greyscale weights come from colour television. The 0.299/0.587/0.114 mix was chosen so colour broadcasts would still look right on black-and-white sets. JPEG was standardised in 1992, and PNG followed in 1996 as a patent-free lossless format.

For machine learning, the decisive step was large labelled collections of such grids: MNIST's 28 × 28 handwritten digits in the 1990s, and then ImageNet's millions of photos from 2009. Its per-channel means and standard deviations are still in almost every vision codebase today.

Try it

  1. In the NumPy example, change the white block to grey (128, 128, 128) and compute its normalised values by hand. Check them with the code.
  2. Take img and swap the channel order with img[..., ::-1]. Which blocks change colour, and which don't? This is exactly what happens with an OpenCV BGR image.
  3. Harder: with the digits dataset, display one image with matplotlib.pyplot.imshow(digits.images[0], cmap="gray"), then try digits.images[0].T. What did the transpose do to the picture?

Hint for 2: red and blue swap places, but green and white stay the same, because their first and last channels are equal.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. A colour photo is 640 pixels wide and 480 pixels tall, stored as 8-bit RGB. How many numbers does it contain?

  2. You load a photo with OpenCV's cv2.imread and pass it straight to a model trained on RGB images. The sky in its predictions behaves as if it were orange. What went wrong?

  3. You have an image array of shape (224, 224, 3) and PyTorch needs (3, 224, 224). Why is x.reshape(3, 224, 224) the wrong fix?

  4. Your model was trained on ImageNet-normalised inputs, but you feed it raw 0–255 pixel values. What usually happens?

  5. Using ImageNet statistics (green mean 0.456, std 0.224), what normalised value does a green channel value of 0 get?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Book

Computer Vision: Algorithms and Applications (2nd edition)

Richard Szeliski · 2022 · Intermediate · free PDF for personal use

The standard computer-vision textbook, from image formation and colour to features, recognition and deep learning. The author offers the PDF free on the book's site.

Docs

torchvision: Transforming and augmenting images

PyTorch team · Beginner · Free

Official guide to torchvision's transforms (including the v2 API) for resizing, cropping, converting, normalising and augmenting images, boxes and masks.

Docs

Pillow documentation

Pillow contributors · Beginner · Free

Documentation for Pillow, the standard Python library for opening, converting, resizing and saving image files.

Book

Dive into Deep Learning

Zhang, Lipton, Li & Smola · Intermediate · Free

An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/vision/images-as-data.md