An Image Is a Grid of Numbers
A colour image file holds, for every pixel, three numbers: how much red,
green and blue light it has. Decoding the file turns them into a tensor.
torchvision puts the colour channels first, so a colour image of 48 rows
and 64 columns becomes a tensor of shape (3, 48, 64): three planes of
48 by 64, one per channel. A batch adds one more dimension in front, giving
(N, C, H, W), the layout every torchvision model expects.

The values come in two forms. A decoded file gives uint8, whole numbers from 0 (none of that colour) to 255 (full). Networks compute with float32, and the pretrained ones in this course expect values from 0.0 to 1.0 before their own normalisation step. Many silent mistakes in vision code are a tensor in one form where the other was expected: the code runs, and the numbers are wrong.
Reading Files with Pillow and ToImage
Pillow reads the file: Image.open(path) returns a Pillow image whose
size is (width, height), note the order, and whose mode says what each
pixel holds: RGB for colour, L for grey, RGBA for colour with
transparency. v2.ToImage() then turns it into a uint8 tensor in
(C, H, W) layout, keeping the channels the file has: a grey image gives
one channel and an image with transparency gives four. Calling
.convert("RGB") before ToImage gives three channels whatever the file
holds, which is what a model trained on colour images needs.
ToImage returns a tv_tensors.Image: an ordinary tensor with a label
that tells torchvision's transforms "this is an image", which matters once
boxes and masks travel with it. torchvision's datasets read files with
Pillow too. torchvision also has its own decoders, such as
torchvision.io.decode_image, but they are deprecated since torchvision
0.29 and will be removed in favour of a separate library, TorchCodec, so the
course does not use them.
PNG is lossless: decoding gives back exactly the numbers that were saved. JPEG is lossy: it saves space by discarding detail the eye hardly notices, so the decoded numbers differ a little from the originals, most at sharp edges. A model never sees the picture you saved, only what decoding gives back.
From uint8 to float
v2.ToDtype(torch.float32, scale=True) converts and divides by 255, so
0 to 255 becomes 0.0 to 1.0. Without scale=True, or with .float(), the
type changes but the values stay 0.0 to 255.0. Nothing fails at that point;
the error shows up later as a model that predicts nonsense or a picture that
displays as white.
Channels First and Channels Last
PyTorch uses channels first. Matplotlib, Pillow and NumPy image code use
channels last, (H, W, C). tensor.permute(1, 2, 0) reorders the
dimensions: the new first dimension is the old dimension 1 (rows), then 2
(columns), then 0 (channels). It moves no data, only how the tensor is read.
A one-channel image is shown by passing the single plane, image[0], with a
grey colour map.
Exercise: Decode, Convert and Display
You will make three small test images, decode them and print shape, dtype and range after each step, then save a figure. Predict each line before you run the script.
Starting state: the course environment from the setup lesson.
Effects: creates four small files and images.png in the lesson folder.
No network access.
Output: Outputs shown below are illustrative. Every shape, dtype and maximum should match; the JPEG change can differ slightly with another JPEG library.
-
In a terminal with the course environment active and
TORCH_HOMEset (see Set up the pinned CPU environment), create the lesson folder. macOS and Linux:mkdir -p ~/cv-practice/decode-and-inspect-images cd ~/cv-practice/decode-and-inspect-imagesWindows PowerShell:
mkdir $HOME\cv-practice\decode-and-inspect-images cd $HOME\cv-practice\decode-and-inspect-images -
Save this as
make_images.py:"""Write three small test images: a colour PNG, the same picture as a JPEG, and a grey PNG.""" import torch from PIL import Image height, width = 48, 64 rows = torch.arange(height).view(height, 1).expand(height, width) cols = torch.arange(width).view(1, width).expand(height, width) red = (cols * 4).clamp(max=255) # brighter to the right green = (rows * 5).clamp(max=255) # brighter downwards blue = torch.full((height, width), 40) blue[16:32, 24:40] = 255 # a blue square in the middle image = torch.stack([red, green, blue]).to(torch.uint8) # (3, 48, 64) # Pillow wants (H, W, C) arrays, so the channels move to the end. Image.fromarray(image.permute(1, 2, 0).numpy()).save("colour.png") Image.fromarray(image.permute(1, 2, 0).numpy()).save("colour.jpg", quality=75) Image.fromarray(image[1].numpy()).save("grey.png") # one channel: the green plane torch.save(image, "original.pt") print("wrote colour.png, colour.jpg, grey.png; tensor", tuple(image.shape), image.dtype)The picture is built from numbers you can predict: red grows to the right, green grows downwards and a blue square sits in the middle.
Image.fromarraytakes a NumPy array in(H, W, C)layout, so the channels move to the end before saving; a two-dimensional array becomes a grey image.quality=75is a typical JPEG setting. The grey file is the green plane alone, andoriginal.ptkeeps the exact numbers for comparison. Run it withpython make_images.py:wrote colour.png, colour.jpg, grey.png; tensor (3, 48, 64) torch.uint8 -
Before running the next script, write down your prediction for each line it prints: the shapes, the dtypes and the maximum values.
Save this as
inspect_images.py:"""Read the test images and report shape, dtype and value range after each step.""" import matplotlib.pyplot as plt import torch from PIL import Image from torchvision.transforms import v2 to_image = v2.ToImage() def report(label, t): print(f"{label:<22} shape={tuple(t.shape)} dtype={t.dtype} min={t.min().item():g} max={t.max().item():g}") png_file = Image.open("colour.png") print("Pillow:", png_file.size, png_file.mode) png = to_image(png_file) print("ToImage gives:", type(png).__name__) report("PNG", png) jpg = to_image(Image.open("colour.jpg")) report("JPEG", jpg) original = torch.load("original.pt") print("PNG equals original:", torch.equal(png, original)) change = (jpg.int() - original.int()).abs() print("JPEG largest change:", change.max().item(), "| mean change:", round(change.float().mean().item(), 2)) grey_file = Image.open("grey.png") print("Pillow:", grey_file.size, grey_file.mode) grey = to_image(grey_file) report("grey PNG", grey) grey_rgb = to_image(grey_file.convert("RGB")) report("grey PNG as RGB", grey_rgb) scaled = v2.ToDtype(torch.float32, scale=True)(png) report("ToDtype scale=True", scaled) unscaled = v2.ToDtype(torch.float32)(png) report("ToDtype no scale", unscaled) channels_last = scaled.permute(1, 2, 0) report("permute(1, 2, 0)", channels_last) fig, axes = plt.subplots(1, 3, figsize=(9, 3)) axes[0].imshow(channels_last.numpy()) axes[0].set_title("PNG, float 0-1") axes[1].imshow(jpg.permute(1, 2, 0).numpy()) axes[1].set_title("JPEG, uint8") axes[2].imshow(grey[0].numpy(), cmap="gray") axes[2].set_title("grey, one channel") for ax in axes: ax.axis("off") fig.savefig("images.png", dpi=100, bbox_inches="tight") print("saved images.png")Run it with
python inspect_images.py. Illustrative output:Pillow: (64, 48) RGB ToImage gives: Image PNG shape=(3, 48, 64) dtype=torch.uint8 min=0 max=255 JPEG shape=(3, 48, 64) dtype=torch.uint8 min=0 max=255 PNG equals original: True JPEG largest change: 81 | mean change: 2.19 Pillow: (64, 48) L grey PNG shape=(1, 48, 64) dtype=torch.uint8 min=0 max=235 grey PNG as RGB shape=(3, 48, 64) dtype=torch.uint8 min=0 max=235 ToDtype scale=True shape=(3, 48, 64) dtype=torch.float32 min=0 max=1 ToDtype no scale shape=(3, 48, 64) dtype=torch.float32 min=0 max=255 permute(1, 2, 0) shape=(48, 64, 3) dtype=torch.float32 min=0 max=1 saved images.png
Reading the Result
Pillow reports the size as width then height, (64, 48); the tensor
is (3, 48, 64), height before width. The PNG comes back identical to the tensor that was saved; the JPEG does
not. Its average change is about 2 levels out of 255, but one value moved by
81: it is in the blue channel at the edge of the blue square, where the
colour jumps from 40 to 255 and JPEG's compression blurs the step. The grey
file has mode L and becomes one channel, and its maximum is 235 because
the green plane reached 47 times 5. Converting to RGB copies that plane into
three identical channels. scale=True is the difference between a maximum of 1 and of 255,
and permute moved the 3 to the end.
Open images.png. It shows three panels: the colour picture from the
float tensor, the JPEG (Matplotlib accepts uint8 from 0 to 255 too), and
the grey plane drawn with a grey colour map. Each tensor goes to Matplotlib
through .numpy(), which shares the same memory; Matplotlib works with
NumPy arrays, and handing it a tensor directly relies on a conversion that
NumPy has deprecated. The JPEG panel looks the same
as the first to the eye; the largest change, 81 levels, is at the square's
edge.
Success: your predictions match the printed shapes, dtypes and maxima,
and images.png shows the gradient with the blue square in all three
panels (grey in the third).
If something differs:
| What you see | Likely cause | Next step |
|---|---|---|
TypeError: Invalid shape (3, 48, 64) for image data | A channels-first tensor passed to imshow | permute(1, 2, 0) first, or pass one plane |
Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers) and a white picture | A float tensor still on the 0 to 255 scale | Convert with scale=True |
FileNotFoundError: [Errno 2] No such file or directory: 'colour.png' | Running from another folder, or step 2 not run | cd into the lesson folder and run make_images.py |
| A JPEG change other than 81 or 2.19 | A different JPEG library inside Pillow | Check the environment with check_setup.py; the lesson's point, that the JPEG changes and the PNG does not, still holds |
Reset: run python make_images.py again; it overwrites the four files.
Independent task: at the end of inspect_images.py, add a figure that
shows unscaled.permute(1, 2, 0).numpy() with plt.imshow and saves it as
unscaled.png. Predict what the message and the picture will be, then run
it.
Hint 1: How does Matplotlib treat the values of a float image?
Hint 2: For floats it expects 0.0 to 1.0; anything above 1 is shown at full brightness.
-
Clean up. macOS and Linux:
cd ~/cv-practice ls rm -rf decode-and-inspect-imagesWindows PowerShell:
cd $HOME\cv-practice ls Remove-Item -Recurse decode-and-inspect-imagesCheck that
lslistsdecode-and-inspect-imagesbefore you remove it. The environment,weightsanddatastay for later lessons.
Check Your Understanding
- A grey PNG 160 pixels wide and 120 high has a brightest pixel of 200.
Predict the shape, dtype and maximum after each step:
v2.ToImage()(Image.open(path)); then the same with.convert("RGB")beforeToImage; thenv2.ToDtype(torch.float32, scale=True); thenpermute(1, 2, 0). - Why does
plt.imshowneed thepermute, when PyTorch is happy without it?
Answer and Reasoning
Independent task
Matplotlib logs Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers). Got range [0.0..255.0].
and the picture is almost entirely white. For a float image it treats 1.0
as full brightness, so every value of 1 or more becomes full: every red
value except column 0, every green value except row 0, and every blue
value. Only the top row and left column keep some colour. No error is
raised, which is why the printed maximum is the better check.
Understanding check
(1, 120, 160), uint8, 200: a grey file has one channel andToImagekeeps it, height first. Then(3, 120, 160), uint8, 200: converting to RGB copies the plane three times without changing values. Then(3, 120, 160), float32, about 0.784, which is 200 divided by 255. Then(120, 160, 3), float32, 0.784:permutemoves dimensions, not values.- A tensor has no idea which dimension is the channel; each library
decides by convention. PyTorch's layers expect
(C, H, W)and Matplotlib expects(H, W, C), so a(3, 48, 64)tensor looks to Matplotlib like an image 3 rows high with 64 channels, which is invalid.permute(1, 2, 0)changes only how the same numbers are read.