NumPy in practice: images as arrays

Advanced

Introduction

Every photo on your phone is a grid of numbers, and NumPy is how Python works with such grids. Libraries such as Pillow, OpenCV, scikit-image and every deep learning framework load images as NumPy arrays. Image processing is therefore a good final test of NumPy skills: shapes, dtypes, slicing, broadcasting, masks and reductions all appear at once.

How it works

Storage. A greyscale image is a 2-D array of shape (height, width); each pixel is a brightness from 0 (black) to 255 (white), stored as uint8. A colour image has shape (height, width, 3): three channels, red, green and blue. Note the order: rows (height) come first, so img[y, x] is the pixel at row y, column x.

Slicing. Slices crop, flip and downsample without copying:

crop = img[100:200, 50:150]     # rows 100-199, columns 50-149
flipped = img[:, ::-1]          # mirror left-right (same as np.fliplr)
upside_down = img[::-1]         # flip top-bottom (np.flipud)
small = img[::2, ::2]           # every second row and column

Brightness and the uint8 trap. uint8 holds only 0 to 255, and arithmetic wraps around: 250 + 10 becomes 4, so a "brighter" image gets black spots. The safe recipe widens the type, adds, clips to the valid range and converts back:

brighter = np.clip(img.astype(np.int16) + 50, 0, 255).astype(np.uint8)

Masks and reductions. A comparison gives a boolean mask of the same shape: img > 120 marks the bright pixels, and np.where(img > 120, 255, 0) makes a black-and-white thresholded image. Reductions summarise: img.mean() is the average brightness, and img.mean(axis=2) turns a colour image into greyscale by averaging the three channels (real converters weight green most).

Filters. A blur replaces each pixel by the average of its neighbourhood. With slicing, the average of a pixel and its right neighbour for every pixel at once is (img[:, :-1] + img[:, 1:]) / 2, which shows how whole-image operations are written without loops.

Example

# A greyscale image is a 2-D array of brightness values from 0 (black) to 255 (white).
img = [
    [0, 50, 100, 150],
    [50, 100, 150, 200],
    [100, 150, 200, 250],
]
print("shape:", (len(img), len(img[0])))
print("flipped left-right:", [row[::-1] for row in img])
print("crop img[0:2, 1:3]:", [row[1:3] for row in img[0:2]])
print("brighter, clipped:", [[min(255, v + 60) for v in row] for row in img])
print("threshold > 120:", [[1 if v > 120 else 0 for v in row] for row in img])
print("mean brightness:", sum(sum(row) for row in img) / 12)
Open in compiler

Line by line

  1. img is a 3 × 4 greyscale image that gets brighter towards the bottom right.
  2. Reversing each row models img[:, ::-1].
  3. Slicing rows 0–1 and columns 1–2 models img[0:2, 1:3].
  4. min(255, v + 60) models clipping after a brightness change.
  5. The comparison builds a 0/1 mask, and the mean summarises the whole image.

Expected result

shape: (3, 4)
flipped left-right: [[150, 100, 50, 0], [200, 150, 100, 50], [250, 200, 150, 100]]
crop img[0:2, 1:3]: [[50, 100], [100, 150]]
brighter, clipped: [[60, 110, 160, 210], [110, 160, 210, 255], [160, 210, 255, 255]]
threshold > 120: [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 1]]
mean brightness: 125.0

In the real world

Phone cameras, medical scanners and satellites all produce arrays. Data augmentation for training image models flips, crops and changes brightness with exactly these operations. Document scanners threshold pages to black and white, and quality checks in factories compare camera images with masks.

Common mistakes

  • Adding to uint8 images without widening the type, which wraps bright pixels to dark ones.
  • Mixing up x and y: the first index is the row (height).
  • Changing a crop and being surprised the original changed: slices are views.
  • Forgetting the channel axis when computing on colour images.

Best practices

  • Check img.shape and img.dtype right after loading an image.
  • Convert to a wider type or to float for calculations, then clip and convert back.
  • Use .copy() when you edit a crop but must keep the original.

Summary

Images are NumPy arrays of uint8 pixels: (height, width) for greyscale and (height, width, 3) for colour. Slicing crops, flips and downsamples, masks threshold, reductions summarise, and brightness changes need a wider type and np.clip to avoid uint8 overflow.

Quick check

1. What is the shape of a 640 × 480 (width × height) colour image array?
2. For uint8 pixels, 250 + 10 gives…
3. Which slice mirrors an image left to right?
4. What does np.where(img > 120, 255, 0) produce?

Key takeaways

  • Images are arrays: shape (h, w) for greyscale, (h, w, 3) for colour, usually uint8.
  • Slicing crops, flips and downsamples without copying.
  • Widen the dtype before arithmetic and clip back to 0–255, or uint8 values wrap around.

Practice problems for this lesson

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.