A Photo Is a Tensor

A neural network cannot look at a photo. It can only do arithmetic on numbers, so before any model sees a picture, the picture has to become a tensor: a block of numbers with a known shape, a known data type and a known range of values. This page explains what those numbers are, how a JPEG or PNG file turns into them, how PyTorch arranges them, and how photos of every size are brought to the one size a model expects.

Pixels and colour channels

A digital photo is a rectangle of tiny squares called pixels, arranged in rows and columns like the cells of a spreadsheet. A photo 4000 pixels wide and 3000 pixels tall holds 12 million of them. Each pixel shows one colour, and that colour is stored as three numbers: how much red, how much green and how much blue light to mix. A screen builds every colour it shows from those three lights.

In an ordinary photo each of the three numbers is a whole number from 0 (none of that light) to 255 (as much as possible). Pure red is (255, 0, 0), white is (255, 255, 255), black is (0, 0, 0), and a middle grey has the same value in all three, such as (128, 128, 128). One byte holds exactly the 256 values from 0 to 255, which is why this range is everywhere.

Read the photo one colour at a time and it splits into three grids of the same size: a grid of red values, a grid of green values and a grid of blue values. Each of these grids is a channel. Below is a tiny 3 by 4 corner of a photo where blue sky meets a yellow flower, written out as its three channels.

Red channel
  1. 70
  2. 72
  3. 238
  4. 242
  5. 68
  6. 235
  7. 240
  8. 244
  9. 66
  10. 233
  11. 239
  12. 241
Green channel
  1. 130
  2. 132
  3. 198
  4. 201
  5. 128
  6. 195
  7. 200
  8. 203
  9. 127
  10. 193
  11. 199
  12. 202
Blue channel
  1. 200
  2. 203
  3. 31
  4. 28
  5. 198
  6. 35
  7. 30
  8. 26
  9. 196
  10. 37
  11. 33
  12. 29

The sky pixels have a low red value and a high blue value; the yellow flower pixels (highlighted) are high in red and green and low in blue, because yellow light is a mix of red and green. Nothing in the numbers says "sky" or "flower". A model has to learn such things from patterns in these grids.

Not every image has three channels. A greyscale image stores one number per pixel, its brightness, so it is a single grid. An image with transparency, such as many PNG files, adds a fourth channel called alpha that says how opaque each pixel is. The Pillow library, which Python programs use to open image files, names these layouts modes: RGB for three 8-bit channels, L for 8-bit greyscale and RGBA for colour with transparency.

True or false?

A colour photo of 100 by 100 pixels holds 30,000 numbers.

True. It has 10,000 pixels, and each pixel stores a red, a green and a blue value, so there are three grids of 10,000 numbers each.

A pixel with the values (200, 200, 200) is a light shade of red.

False. Equal red, green and blue values give a grey. With all three at 200 it is a light grey; a red needs a red value clearly above the other two.

Decoding an image file

Those grids are large. A 4000 by 3000 colour photo holds 36 million values, and at one byte each that is 36 megabytes. A JPEG file of the same photo is usually only a few megabytes, because an image file does not store the grids as they are. It stores them compressed: written in a compact code that takes far fewer bytes but cannot be read as pixels directly.

Decoding is the step that reads that code and rebuilds the grid of pixel values from it. It always comes first: whatever a program does to a photo, it does to the decoded pixels, never to the bytes of the file.

  • photo.jpg compressed bytes
  • Decode Pillow
  • Pixel grid 3 channels, 0 to 255
  • photo.jpg to Decode
  • Decode to Pixel grid

Formats compress in two different ways, and the difference shows up in the decoded pixels. PNG is lossless: decoding gives back exactly the pixels that were saved, bit for bit. JPEG, as cameras and phones use it, is lossy: to make the file small it throws away fine detail the eye barely notices, so decoding gives pixels close to the original but not identical. For classifying photos that small loss rarely matters, but it does mean that saving a picture as JPEG and opening it again changes its numbers slightly.

In Python, Pillow opens the file and decodes it. Image.open is lazy: it reads only the file's header to learn the format, the size and the mode, and decodes the pixels when they are first needed.

from PIL import Image

img = Image.open("photo.jpg")   # reads the header, pixels are decoded on first use
print(img.format)               # the file format, for example JPEG
print(img.mode)                 # the pixel layout, for example RGB
print(img.size)                 # (width, height) in pixels

rgb = img.convert("RGB")        # three channels, whatever the file held

Two details of the decoded image are easy to trip over. img.size is given as (width, height), width first. And phone photos often store their pixels sideways, together with a note that tells viewers to turn them upright: the EXIF orientation tag. Gallery apps follow that note, but Pillow does not apply it on its own, so a photo that shows upright in a gallery app can come out of Image.open lying on its side. ImageOps.exif_transpose(img) applies the note and turns the pixels upright.

True or false?

Opening a JPEG file and decoding it gives back exactly the pixel values the camera captured.

False. JPEG is lossy: it discards some detail to keep the file small, so the decoded values are close to the original ones but not identical. PNG is the format that decodes bit for bit.

Two files of very different size in bytes can decode to pixel grids of exactly the same shape.

True. The shape depends only on the width, the height and the number of channels. How many bytes the file takes depends on the format, the compression and how much detail the picture has.

The shape of an image tensor

Once decoded, the three channel grids become one tensor with three dimensions. PyTorch and its image library torchvision put the dimensions in a fixed order: channels, height, width, written (C, H, W). The first index picks a channel, the second a row, the third a column. You can picture the tensor as the three grids lying one behind the other.

  • B
  • G
  • red channel
  • W = 320 (width, dim 2)
  • H = 240
  • (height, dim 1)
  • C = 3 (channels, dim 0)

torchvision offers transforms: small objects you call on an image to get a changed image back, so that several of them can be chained one after the other. Its v2 transforms convert a Pillow image into this layout.v2.ToImage() turns it into a tensor (a tv_tensors.Image, which behaves like an ordinary tensor and also marks it as an image for the transforms). A picture 320 pixels wide and 240 tall becomes a tensor of shape (3, 240, 320).

from PIL import Image
from torchvision.transforms import v2

img = Image.new("RGB", (320, 240))   # Pillow takes (width, height)
x = v2.ToImage()(img)

print(img.size)    # (320, 240): width, height
print(x.shape)     # torch.Size([3, 240, 320]): channels, height, width

Notice that the two numbers swap places. Pillow reports (width, height), the tensor holds height before width, and the channels come first. Reading a shape wrongly is one of the most common mistakes with images, so it pays to check x.shape rather than assume.

Models do not take one image at a time. They take a batch, and a batch of images adds one more dimension in front: (N, C, H, W), where N is the number of images. x.unsqueeze(0) turns a single image of shape (3, 240, 320) into a batch of one, (1, 3, 240, 320), and torch.stack joins several images along that new first dimension.

DimensionMeaningOne imageBatch of 8
Nnumber of images(none)8
Cchannels (red, green, blue)33
Hheight in pixels (rows)240240
Wwidth in pixels (columns)320320

torch.stack has one strict condition: every tensor it joins must have the same size. Eight photos of eight different sizes cannot be stacked into one batch tensor, which is the reason the last section of this page exists.

True or false?

A photo 640 pixels wide and 480 pixels tall becomes a tensor of shape (3, 640, 480).

False. The order is channels, height, width, so the shape is (3, 480, 640). Width comes last even though Pillow lists it first.

A batch of 16 colour images of 224 by 224 pixels has the shape (16, 3, 224, 224).

True. The batch dimension N comes in front of channels, height and width.

Whole numbers and floats

The tensor that comes out of v2.ToImage() holds the pixel values exactly as the file stored them: whole numbers from 0 to 255, with the data type torch.uint8 (an unsigned 8-bit integer, one byte per value). ToImage converts the layout, not the values.

Networks, however, compute with floating-point numbers, and they expect image values from 0.0 to 1.0. The conversion is a single division: each value is divided by 255, the largest value a byte can hold.

$$x_{\text{float}} = \dfrac{x_{\text{uint8}}}{255}$$

from 0..255 to 0..1

uint8 valuefloat32 valueMeaning
00.0none of this colour
510.2a fifth of the full value
128about 0.502about half
2551.0the full value

Dividing every value by the same number keeps every proportion between them, so the picture does not change. A pixel that was twice as bright as its neighbour still is; only the scale of the numbers is new. Converting back multiplies by 255 again.

In torchvision v2 the conversion is v2.ToDtype(torch.float32, scale=True). The scale=True is what makes it divide. scale defaults to False, and without it the values only change type: the whole number 255 becomes the float 255.0, and the values stay between 0 and 255. A model given such values receives inputs 255 times larger than it expects, and nothing raises an error to warn you.

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

img = Image.open("photo.jpg").convert("RGB")

x = v2.ToImage()(img)
print(x.dtype, x.min().item(), x.max().item())   # torch.uint8, values within 0..255

to_float = v2.ToDtype(torch.float32, scale=True)
y = to_float(x)
print(y.dtype, y.min().item(), y.max().item())   # torch.float32, values within 0.0..1.0

Older code does both steps with ToTensor(). It is deprecated in torchvision; the documented replacement is v2.ToImage() followed by v2.ToDtype(torch.float32, scale=True), which gives the same result up to float precision.

True or false?

`v2.ToDtype(torch.float32)` turns pixel values from 0 to 255 into values from 0 to 1.

False. Without `scale=True` only the data type changes: 255 becomes 255.0. The values are divided by 255 only when `scale=True` is passed.

Converting an image from uint8 to float values between 0 and 1 leaves the picture looking the same.

True. Every value is divided by the same number, 255, so all the proportions between pixels and channels stay as they were.

Resizing and cropping to one size

Photos arrive in every size and shape: wide landscapes, tall portraits, small thumbnails, huge camera files. A batch needs them all at one size, and a model is built for a fixed input size. The usual way to get there keeps the photo's proportions and works in two steps.

First, resize so that the shorter side reaches the target length and the longer side scales by the same factor. Then crop the centre: cut a square of the target size out of the middle, which removes the extra length of the longer side.

Resizing does not just delete or copy pixels. Each new pixel is computed from the old pixels around its position. By default this is bilinear interpolation, a weighted average of the nearest neighbours. It comes with antialiasing, which smooths the image before shrinking it so that fine detail does not turn into jagged patterns.

  • original
  • 600 x 400
  • Resize(224)
  • 336 x 224, red strips are cut
  • CenterCrop(224)
  • 224 x 224

Follow a photo 600 pixels wide and 400 tall to a target of 224, a size used by many image models (each model states its own). Resizing the shorter side, the height, from 400 to 224 shrinks everything by the same factor, so the width becomes \(600 \times 224 / 400 = 336\). The centre crop then keeps the middle 224 columns and cuts 56 from the left and 56 from the right. A tall portrait loses its top and bottom instead.

In torchvision v2 the two steps are v2.Resize(224) and v2.CenterCrop(224). Passing a single number to Resize sets only the shorter side. The documentation recommends resizing the uint8 tensor and converting to floats afterwards, which is faster.

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

prepare = v2.Compose([
    v2.ToImage(),                            # PIL image to (C, H, W) uint8 tensor
    v2.Resize(224),                          # shorter side to 224, proportions kept
    v2.CenterCrop(224),                      # middle 224 x 224 square
    v2.ToDtype(torch.float32, scale=True),   # 0..255 to 0.0..1.0
])

img = Image.open("photo.jpg").convert("RGB")
x = prepare(img)
print(x.shape)   # torch.Size([3, 224, 224]) for any photo

The trade-off sits in what the crop removes. Resizing then cropping never stretches the picture, so a round object stays round, but it throws away the edges of the longer side. A subject in the middle of the frame survives; a bird near the left edge of a wide shot may be cut out. The alternative, v2.Resize((224, 224)) with a pair of numbers for height and width, keeps the whole picture but squeezes it to the new proportions, so a wide photo comes out squashed sideways.

When a photo is smaller than the crop, CenterCrop does not enlarge it. It pads the missing area with zeros, which show as black borders. Resizing first avoids this, because after Resize the shorter side already matches the crop.

True or false?

`v2.Resize(224)` turns every photo into a 224 by 224 square.

False. A single number sets only the shorter side, and the longer side keeps the proportions: a 600 by 400 photo becomes 336 by 224. A square needs a crop afterwards, or a pair of numbers that distorts the picture.

Resizing the shorter side and cropping the centre keeps the proportions of everything that remains in the picture.

True. Both sides are scaled by the same factor, and the crop only cuts. Nothing is stretched; what is lost is the edges of the longer side.

`v2.CenterCrop(224)` applied to a 100 by 100 image enlarges it to 224 by 224.

False. CenterCrop never scales. It pads the image with zeros, black pixels, around the original 100 by 100 and returns the 224 by 224 result.