Sub topic 1
An image is a grid of sampled numbers
Prerequisites
This chapter assumes you can read basic Python and NumPy, and that you know what a byte is and how an 8-bit integer ranges from 0 to 255. You should also recognise common image file types such as JPEG and PNG. You do not need any image-processing background.
The working model
A digital image is a rectangular grid of numbers. Each cell of the grid is a pixel, short for "picture element". Each pixel holds one or more numbers, called samples, that say how bright or what colour that spot is.
Three ideas sit behind that definition:
- Sampling. A real scene has continuous light falling across continuous space. A camera sensor measures that light only at a finite set of positions. Each measurement becomes one grid cell.
- Quantisation. Each measurement is a continuous quantity, such as a voltage. It is rounded to one of a fixed number of integer levels so that it fits in a few bits.
- Layout. The numbers are stored in a defined order, so any program knows which number belongs to which row, column and channel.
After capture, the image is only these numbers plus some metadata. Nothing in the array says "this is a face". Any meaning comes from how software interprets the numbers.
Indexing: rows first
In NumPy, OpenCV, Pillow (after conversion to an array) and most other Python tools, an image is an array with shape (height, width, channels). The first index is the row, counted from the top. The second index is the column, counted from the left. The origin (0, 0) is the top-left pixel.
This differs from the mathematical convention (x, y), where x runs horizontally and y runs upward. In an image array, img[y, x] is the correct order. Mixing these up is one of the most common beginner errors, and it often produces no error message when the image is square.
import numpy as np
img = np.zeros((2, 3, 3), dtype=np.uint8) # (height, width, channels)
img[0, 0] = (255, 0, 0) # red
img[0, 1] = (0, 255, 0) # green
img[0, 2] = (0, 0, 255) # blue
img[1, 0] = (255, 255, 255) # white
img[1, 1] = (128, 128, 128) # mid grey
# img[1, 2] stays (0, 0, 0): black
print(img.shape, img.dtype, img.nbytes) # (2, 3, 3) uint8 18The array has 2 rows and 3 columns, so it is 3 pixels wide and 2 pixels tall. Each pixel has 3 samples. The whole image is 2 × 3 × 3 = 18 samples, and since each is one byte, 18 bytes.
The table below lists what each part of the shape tells you.
| Shape entry | Name | Meaning | Value here |
|---|---|---|---|
| First | height | Number of rows | 2 |
| Second | width | Number of columns | 3 |
| Third | channels | Samples per pixel | 3 |
| dtype | sample type | Bits and signedness of each sample | `uint8` |
From scene to numbers
The path from a scene to an array has several steps. Each one throws away information, which is why a stored image is always an approximation of what was in front of the camera.
Sampling decides how finely the scene is divided. Quantisation decides how finely each measurement is divided. The next chapters treat these as two separate dials: resolution for the first, bit depth for the second.
What gets lost
If the grid is too coarse, fine detail cannot be recorded. A thin line narrower than a pixel is either smeared across neighbours or missed. Repeating patterns can produce false patterns called aliasing, such as moiré on a fine fabric. This loss happens at capture time and cannot be undone afterwards.
If quantisation is too coarse, smooth gradients break into visible steps, called banding. With 8 bits there are 256 levels per channel, which is usually enough for display but can show banding in a smooth sky or a dark gradient.
A pixel is a sample, not a little square
It is natural to picture a pixel as a tiny coloured square. That is how screens often draw it, but the sample itself is a measurement at a point (or a small area average at capture). The square is a display choice. When software resizes or rotates an image, it must estimate values between samples, and different estimation methods give different results. This is why resizing is a real computation rather than a simple copy.
Reading and checking an image array
When you load an image from a file, the first thing to check is the shape and dtype. The code below builds a small gradient and inspects it. It is self-contained, so you can run it as shown.
import numpy as np
# A 4x6 greyscale gradient: brightness rises left to right.
height, width = 4, 6
row = np.linspace(0, 255, width).round().astype(np.uint8)
gray = np.tile(row, (height, 1))
print(gray.shape) # (4, 6) -> no channel axis for one-channel images
print(gray.dtype) # uint8
print(gray[0]) # [ 0 51 102 153 204 255]
print(gray[3, 5]) # 255, row 3 (bottom), column 5 (right)
print(gray.min(), gray.max()) # 0 255Notice that this array has no third axis. Some libraries drop the channel axis for single-channel images, giving (height, width). Others keep it as (height, width, 1). Code that assumes one form will fail or silently broadcast wrongly when given the other. Check ndim before indexing channels.
Common errors
- Swapping height and width.
shapeis(height, width, ...), but many APIs, such as Pillow'sImage.sizeand OpenCV'sresize, take(width, height). The order flips between an array and a size argument. - Wrong dtype assumptions. A
uint8array wraps around on overflow. Adding 100 to 200 gives 44, not 300. Convert to a wider type before arithmetic. - Treating the array as the picture. The same numbers can mean different colours depending on the colour space and channel order. The array alone does not say which.
- Assuming a fixed range. Integer images usually span 0 to 255, but float images often span 0.0 to 1.0. Mixing them without rescaling gives images that look black or fully white.
The following snippet shows the overflow problem and its fix.
import numpy as np
a = np.array([200, 250], dtype=np.uint8)
print(a + 100) # [44 94] wrapped around
print(a.astype(np.int32) + 100) # [300 350]
print(np.clip(a.astype(np.int32) + 100, 0, 255).astype(np.uint8)) # [255 255]Edge cases
- Non-square pixels. Some video formats store pixels that are meant to be displayed wider or taller than they are stored. The array looks fine, but the picture appears stretched unless the display applies a pixel aspect ratio.
- Orientation metadata. A phone photo may be stored sideways, with an EXIF tag telling viewers to rotate it. The array you load might be rotated relative to what you saw in a gallery, depending on the library.
- Zero or one dimensions. An array of shape
(1, 1, 3)is a valid image of a single pixel. An empty array, such as(0, 5, 3), has no pixels. Many functions fail on it. - More than 2D. Video adds a time axis, and medical scans add a depth axis. These are still grids of sampled numbers, with one more index.
What comes next
The grid is only part of the picture. The remaining chapters in this tutorial each take one piece of the description. Resolution sets how many samples there are. Bit depth sets how many levels each sample can take. Channels set how many samples describe each pixel. Colour spaces then say what those numbers mean as colour.
Exercise
An array img has shape (480, 640, 3) and dtype uint8. (a) How many pixels wide and tall is the image? (b) What does img[10, 200] return, and which pixel does it refer to? (c) A colleague writes img[200, 10] to read the same pixel. What goes wrong?
Show answer
(a) The image is 640 pixels wide and 480 pixels tall, because shape is (height, width, channels). (b) It returns a 3-element array holding the three samples of the pixel in row 10 (the 11th row from the top) and column 200 (the 201st from the left). (c) The indices are in (row, column) order, so img[200, 10] reads row 200, column 10, a different pixel. Both indices happen to be in range here, so no error is raised and the wrong pixel is returned silently. Had the colleague swapped values like img[500, 10], the row index would exceed 479 and raise an IndexError.
Exercise
What does this code print, and why? a = np.array([250], dtype=np.uint8); print(a + 10). How would you get 260 instead?
Show answer
It prints [4]. A uint8 can hold 0 to 255, so 250 + 10 = 260 wraps around modulo 256 to 4. To get 260, convert to a wider type first, for example a.astype(np.int32) + 10. If the result must go back into an image, clip it to 255 with np.clip before converting to uint8.