Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 5: Computer Vision and CNNs

Images as tensors

P5.135 min●○○ BeginnerReviewed Dec 3, 2026

Why this matters for machine learning

Every vision model starts from an array of numbers, so you need to know exactly what is in it: its shape, its number type and its value range. A wrong layout, a missing division by 255 or a forgotten normalization is the most common reason a vision model silently fails.

Before this: Tensors, shapes and broadcasting, NumPy: arrays and vectorization, Multi-layer perceptrons

After this lesson you can

  • Read a pixel with img[row, col] (row first, origin top-left) and say how many numbers it holds
  • Give the shape of one image and of a batch in NumPy and PyTorch, and convert between the two layouts with transpose or permute
  • Convert between uint8 (0 to 255) and float (0 to 1) without overflow, truncation or a factor-255 error, and normalize each channel
  • Compute grayscale with luma weights and the memory of an image or a batch, and explain why flattening loses neighbours and shifts everything

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 3×33\times3 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 H×WH\times W 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 32×3232\times32 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 8×88\times8 pixels with the numbers written in each cell. Press 8× to see a window of 4×44\times4 pixels. Then try the other buttons.

Zoom in until the numbers appear

Zoom
Show
Values
or click a pixel

Selected: row 14, column 9 (row first, origin top-left)

NumPy: img[14, 9] = [200, 60, 50]

PyTorch: t[:, 14, 9] = [200, 60, 50]

Shape (H, W, C) = (32, 32, 3)

Shape (C, H, W) = (3, 32, 32)

uint8: 3,072 bytes

The picture is made by code, row by row; the numbers are what the computer stores. In Gray, each pixel is round(0.299 R + 0.587 G + 0.114 B). Red, Green and Blue show one channel as a shade of that colour. At 4× and 8× the numbers are written in the cells (8× has the larger print, handy on a phone); with Colour they read top to bottom as R, G, B.

A 32 by 32 colour picture drawn by code. Zoom 1×, 2×, 4× or 8×; from 4× on, each pixel shows its numbers (with Colour they read top to bottom as red, green, blue). Switch between Colour, Gray and one channel, and between uint8 (0 to 255) and float (0 to 1). Click a pixel, press the arrow buttons or use the arrow keys when the picture is focused. Below the picture: the NumPy and PyTorch index of the selected pixel, the shape in both layouts, and the memory in bytes.

Things to try, and what you should see:

  1. Zoom to 4×, Colour. The pixel at row 14, column 9 is a wall pixel with the numbers 200200, 6060, 5050: a lot of red, a little green and blue. Mixed together, those three give the brick red you see at 1×.
  2. Switch to Gray. The same pixel is now one number, 101101, and the shape line loses its last axis.
  3. 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.
  4. 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 “xx goes right and yy 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: (H,W)(H,W), (H,W,C)(H,W,C), (C,H,W)(C,H,W), (N,C,H,W)(N,C,H,W)

Each axis of the array has a meaning, and the order depends on the library.

ShapeMeaning
(H,W)(H,W)one grayscale image (NumPy)
(H,W,C)(H,W,C)one image, channels last: expected by NumPy-style code, PIL and Matplotlib
(C,H,W)(C,H,W)one image, channels first: PyTorch
(N,C,H,W)(N,C,H,W)a batch of NN images in PyTorch
(N,H,W,C)(N,H,W,C)a batch, channels last: NumPy, and Keras by default

Here HH is the height in pixels, WW the width, CC the number of channels and NN the number of images in a batch. A few familiar sizes: an MNIST digit is 28×2828\times28 with one channel; a CIFAR-10 image (60,000 small colour images in 10 classes) is 32×3232\times32 with three. In PyTorch a grayscale image is still written with its channel axis, (1,H,W)(1,H,W), because the layers expect it. An image with an extra opacity channel (RGBA) has C=4C=4, 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 32×3232\times32 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 (H,W,C)→(C,H,W)(H,W,C)\to(C,H,W) 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 (N,C,H,W)(N,C,H,W) 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. 00 is black (or none of that colour) and 255255 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: float=uint8/255\text{float}=\text{uint8}/255. The pixel (200,100,50)(200,100,50) becomes (0.784,0.392,0.196)(0.784,0.392,0.196). 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 uint8 has only 256 values and arithmetic wraps around. Adding 50 to the values 100100, 200200, 220220 gives 150150, 250250 and 1414: 220+50=270220+50=270, and 270−256=14270-256=14. A “brighter” picture gets dark spots, and nothing raises an error. Do arithmetic in a wider type (int16 or 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 [0,1][0,1] straight to uint8 cuts off the fraction: 0.90.9 becomes 00, and only exactly 1.01.0 survives, so the picture is black. The fix is np.round(x * 255).astype(np.uint8).

The first cell below runs all three.

uint8 and float: three traps

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: H⋅W⋅C⋅bH\cdot W\cdot C\cdot b, with b=1b=1 for uint8 and b=4b=4 for float32.

  • A 224×224224\times224 RGB image (the usual input size of many ImageNet models) has 224⋅224⋅3=150,528224\cdot224\cdot3=150{,}528 entries: 150,528150{,}528 bytes (147 KiB) as uint8, and 602,112602{,}112 bytes (588 KiB) as float32.
  • A batch of 32 such images as float32 takes 32⋅602,112=19,267,58432\cdot602{,}112=19{,}267{,}584 bytes, which is 18.4 MiB (about 19.3 million bytes), before any layer has computed anything.
  • A single 1920×10801920\times1080 photo as uint8 has 6,220,8006{,}220{,}800 bytes, about 5.9 MiB.

(One MiB is 1024×10241024\times1024 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 224×224224\times224 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 μc\mu_c and divide by its standard deviation σc\sigma_c,

xc′=xc−μcσc,c∈{R,G,B},x'_c=\frac{x_c-\mu_c}{\sigma_c},\qquad c\in\{\text{R},\text{G},\text{B}\},

where xcx_c is already a float between 0 and 1. The three channels have different means (the ImageNet values below are 0.4850.485 for red and 0.4060.406 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

μ=(0.485, 0.456, 0.406),σ=(0.229, 0.224, 0.225).\begin{aligned} \mu&=(0.485,\,0.456,\,0.406),\\ \sigma&=(0.229,\,0.224,\,0.225). \end{aligned}

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 μc\mu_c and σc\sigma_c over the training set only (using the test set would be leakage, P3.A11).

The worked example is our pixel (200,100,50)(200,100,50). As floats it is (0.784,0.392,0.196)(0.784,0.392,0.196). Normalized with the ImageNet values:

xR′=0.784−0.4850.229=1.307,xG′=0.392−0.4560.224=−0.285,xB′=0.196−0.4060.225=−0.933.\begin{aligned} x'_\text{R}&=\frac{0.784-0.485}{0.229}=1.307,\\ x'_\text{G}&=\frac{0.392-0.456}{0.224}=-0.285,\\ x'_\text{B}&=\frac{0.196-0.406}{0.225}=-0.933. \end{aligned}

For a whole (C,H,W)(C,H,W) tensor, the mean and the standard deviation are written as arrays of shape (3,1,1)(3,1,1), so that broadcasting (P1.B14) stretches each across the height and the width. A mean of shape (3,)(3,) 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 (H,W,C)(H,W,C) array the right shape is (3,)(3,), 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.

Shapes, memory, normalization, gray

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

Y=0.299 R+0.587 G+0.114 B.Y=0.299\,R+0.587\,G+0.114\,B .

They add up to 1, so a gray pixel (v,v,v)(v,v,v) stays vv. The quantity YY is called luma. The weights are not equal because our eyes are most sensitive to green and least sensitive to blue. Pure green (0,255,0)(0,255,0) gives Y≈149.7Y\approx149.7, pure red 76.276.2 and pure blue 29.129.1, whereas the plain mean gives 8585 for all three. Our pixel (200,100,50)(200,100,50) gives 0.299⋅200+0.587⋅100+0.114⋅50=124.20.299\cdot200+0.587\cdot100+0.114\cdot50=124.2, against 116.7116.7 for the mean. (Pillow’s convert("L") documents exactly these weights. Torchvision’s rgb_to_grayscale uses 0.29890.2989 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 0.21260.2126, 0.71520.7152 and 0.07220.0722 for red, green and blue; the pixel (200,100,50)(200,100,50) then has Y=117.65Y=117.65. 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 0∘0^\circ, green 120∘120^\circ, blue 240∘240^\circ), saturation (from gray, 0, to the pure colour, 1) and value (brightness, equal to the largest of RR, GG, BB scaled to 0 to 1). Python’s standard colorsys module converts: the pixel (200,100,50)(200,100,50) has hue 20∘20^\circ (an orange-red), saturation 0.750.75 and value 0.7840.784. 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 VV (coloured light changes the hue too). Because hue is an angle, red sits at both 0∘0^\circ and 360∘360^\circ, 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 3×33\times3 image. A 28×2828\times28 MNIST digit becomes a vector with 784 entries, a 32×3232\times32 colour image 3,072, and a 224×224224\times224 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 32×32×332\times32\times3 image has 3072⋅100+100=307,3003072\cdot100+100=307{,}300 parameters. On a flattened 224×224224\times224 image with 1000 hidden units it has 150,528⋅1000+1000=150,529,000150{,}528\cdot1000+1000=150{,}529{,}000, for one layer. Every pixel gets its own weight to every unit.

The neighbours are lost. In the vector, pixel (r,c)(r,c) sits at position W⋅r+cW\cdot r+c. Its right neighbour is one place away, but its neighbour below is WW 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 8×88\times8 drawing of a “7”.

Flatten an 8 by 8 picture, then shift it

Shift: 0 columns

Original

Shifted

The 64 numbers, row by row. Original on top, shifted below. Ink = 1.

Selected pixel: row 2, column 3, so position 19 in the vector (8 × 2 + 3).

Its right neighbour is position 20, 1 place away. Its neighbour below is position 27, 8 places away.

After the shift, 0 of the 64 entries differ. Of the 18 ink pixels, 18 are still on ink.

Selected = blue frame, right neighbour = pink frame, neighbour below = green frame, in the original and in the vectors. Pixels past the edge are filled with 0. In the vectors the frame is a bar above and below the cell, so ink (dark) and no ink stay visible.

An 8 by 8 picture flattened into 64 numbers, row by row (ink is 1). Select a pixel (click, or arrow keys): its right neighbour is 1 place away in the vector and its neighbour below is 8 places away. Shift the picture left or right by up to 2 columns and watch how many of the 64 entries change and how many ink pixels still land on ink.

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 (C,H,W)(C,H,W) you have a stack of three sheets. In the channels-last layout (H,W,C)(H,W,C) 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 X∈RH×W×C\mathbf{X}\in\mathbb{R}^{H\times W\times C}, with entries Xr,c,kX_{r,c,k} for row rr, column cc, channel kk (the values are integers in {0,…,255}\{0,\dots,255\} as uint8 or reals in [0,1][0,1] as float). Moving to channels first is the permutation Xk,r,c′=Xr,c,kX'_{k,r,c}=X_{r,c,k}. The number of entries is HWCHWC, and the memory is HWC⋅bHWC\cdot b bytes for bb bytes per entry.

Flattening maps X\mathbf{X} to a vector in RHWC\mathbb{R}^{HWC}, and a dense first layer with mm units has HWC⋅m+mHWC\cdot m+m parameters. For one channel, pixel (r,c)(r,c) goes to index Wr+cWr+c, so a shift of the image by ss columns moves the index of every pixel by ss (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 channel
torch.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 (H,W,C)(H,W,C) array into a (C,H,W)(C,H,W) 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 (N,C,H,W)(N,C,H,W) tensor with its channels last in memory (the “channels-last” memory format) while still reporting the shape (N,C,H,W)(N,C,H,W), 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 8×88\times8 “7” (a list of strings, turned into numbers), looks up the positions of two neighbours and shifts the picture.

Flatten, neighbours and shifts

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

  1. A uint8 array holds the pixel value 220220. What does value + 50 give in NumPy, if the result stays a uint8?

  2. In PyTorch, what is the usual shape of a batch of 16 colour images that are 64 pixels high and 48 pixels wide?

  3. A float tensor x\mathbf{x} of shape (3,224,224)(3, 224, 224) is normalized with a per-channel mean. Which shape of the mean array lets broadcasting subtract the right value from each channel?

  4. A 48×4848\times48 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?

  5. Why does the gray conversion use the weights 0.2990.299, 0.5870.587 and 0.1140.114 and not a plain average of red, green and blue?

Exercises

  1. Three 1920×10801920\times1080 RGB photos are held in memory as uint8. How many bytes is that, and about how many MiB?
    Show answerEach photo has 1920⋅1080⋅3=6,220,8001920\cdot1080\cdot3=6{,}220{,}800 bytes, so three have 18,662,40018{,}662{,}400 bytes, which is about 17.817.8 MiB (divide by 102421024^2).
  2. The uint8 array [250, 10] gets +10+10 and, separately, −20-20. What are the two results?
    Show answer[4,20][4, 20] for the addition (260−256=4260-256=4) and [230,246][230, 246] for the subtraction (10−20=−1010-20=-10, and −10+256=246-10+256=246). Both wrap around.
  3. A PyTorch tensor has shape (3,120,160)(3,120,160). What is the shape of the same image as a NumPy (H,W,C)(H,W,C) array, and which call gets it there?
    Show answer(120,160,3)(120,160,3), with t.permute(1, 2, 0) (or np.transpose(a, (1, 2, 0)) for a NumPy array). A reshape to (120,160,3)(120,160,3) would give the right shape and scrambled pixels.
  4. A one-channel image has the uint8 pixel value 191191, a channel mean of 0.50.5 and a standard deviation of 0.250.25. What is the normalized value?
    Show answerFirst divide by 255: 191/255=0.749191/255=0.749. Then (0.749−0.5)/0.25=0.996(0.749-0.5)/0.25=0.996, about 11.
  5. A flattened 28×2828\times28 grayscale image feeds a dense layer with 128 units. How many parameters does the layer have?
    Show answer784⋅128+128=100,480784\cdot128+128=100{,}480: one weight per input and unit, plus one bias per unit.
  6. What is the BT.601 gray value of the pixel (0,100,200)(0,100,200), and what does the plain mean give?
    Show answer0.587⋅100+0.114⋅200=58.7+22.8=81.50.587\cdot100+0.114\cdot200=58.7+22.8=81.5. The plain mean gives 100100. 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).

Key takeaways

  • An image is a grid of pixels, and a colour pixel is three numbers (red, green, blue). Index it with img[row, col]: row first, counting from the top-left corner. NumPy, PIL and Matplotlib use (H,W,C)(H,W,C); PyTorch stores it as (C,H,W)(C,H,W), and a batch as (N,C,H,W)(N,C,H,W).
  • Moving between layouts is a permutation of the axes, not a reshape: transpose(2, 0, 1) in NumPy and permute(2, 0, 1) in PyTorch change (H,W,C)(H,W,C) into (C,H,W)(C,H,W). A reshape would keep the numbers in the same memory order and scramble the pixels.
  • Pixels are uint8 (0 to 255) or floats (0 to 1). Divide by 255 to convert, and round and clip to go back. Adding to a uint8 array wraps around (220+50220+50 gives 1414), a float image with values up to 255 is 255 times too bright, and casting a 0-to-1 float to uint8 gives a black image.
  • A 224×224224\times224 RGB image takes 150,528150{,}528 bytes as uint8 and 602,112602{,}112 as float32, and a batch of 32 of them takes about 18.4 MiB. Per-channel normalization is (xc−μc)/σc(x_c-\mu_c)/\sigma_c, with the mean and standard deviation shaped (3,1,1)(3,1,1) for a (C,H,W)(C,H,W) tensor.
  • Grayscale is a weighted sum with the BT.601 luma weights 0.2990.299, 0.5870.587, 0.1140.114, not the plain mean, because green looks brighter than blue. Flattening an image for an MLP keeps all the numbers and forgets which pixels are neighbours; a one-pixel shift moves most of the ink to other positions of the vector. Convolutions (P5.2) fix this.
Found a mistake? Tell us