Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 49 ยท Working with Real Data

Arrays as Images and Plots

Treat images as 3D uint8 arrays. Generate gradients, slice color channels, convert to grayscale, flip, crop and threshold, then draw arrays with matplotlib.

A digital image is just numbers on a grid. A grayscale picture is a 2D array of brightness values. A color picture is a 3D array with an extra axis of three color channels: red, green and blue. Once you see that, every image operation (cropping, flipping, brightening, thresholding) becomes an array operation you already know.

This lesson builds pictures from scratch, so you need no image files, then manipulates them with slicing and math, and displays them with matplotlib. Along the way you will meet the classic uint8 overflow trap. It relies on indexing and slicing, views, and boolean masks.

An image is a (height, width, channels) array

By convention a color image has shape (height, width, 3) and dtype uint8: each channel value is an integer from 0 (none) to 255 (full). Row 0 is the top of the picture. A pixel is img[row, col], which returns its three channel values.

flowchart LR
    A["img shape<br/>(H, W, 3)"] --> B["img[..., 0]<br/>red plane (H, W)"]
    A --> C["img[..., 1]<br/>green plane (H, W)"]
    A --> D["img[..., 2]<br/>blue plane (H, W)"]
    A --> E["img[r, c]<br/>one pixel: 3 values"]

Slicing the last axis gives a color plane; fixing the first two axes gives a pixel.

Let us create a gradient. Red will grow from left to right, green from top to bottom, and blue stays constant. np.linspace produces the ramps, and broadcasting spreads each ramp across the full image.

Python Generating an RGB gradient

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

ax.imshow draws a uint8 RGB array directly. Float images are expected to lie between 0.0 and 1.0 instead, and values outside the range are clipped. Mixing the two conventions is a frequent cause of all-white or all-black pictures.

Drawing shapes with masks

To paint shapes, build coordinate grids with np.mgrid, write the shape as a boolean condition, and assign a color to the pixels where it is true. This is masked assignment in action.

Channels, flips and crops

Slices make the common edits one-liners. Reversing the last axis swaps red and blue; reversing the column axis mirrors the picture; a block of rows and columns is a crop. All of them return views, so they cost nothing and share memory with the original.

Python Channel slicing, flips and crops

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Because a crop is a view, writing into it changes the original image. Use img[20:60, 20:60].copy() when you want an independent patch.

Grayscale and thresholding

Converting to grayscale means mixing the three channels into one brightness value. Human eyes are most sensitive to green and least to blue, so a common recipe is the weighted sum 0.299 R + 0.587 G + 0.114 B. That is a dot product along the last axis, written with the @ operator (Vectors, Dot Products and the @ Operator).

Thresholding turns a grayscale picture into black and white: pixels brighter than a cutoff become True.

Python Grayscale, threshold and a column profile

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice the three levels in np.unique(gray8): the dark background, the disc and the square each have a single gray value, because each shape is a flat color. The third plot is not an image at all: averaging over rows (axis=0) gives one number per column, and a plain line plot shows the profile. Plotting any 1D array with ax.plot(arr) is the quickest way to inspect it.

The uint8 overflow trap

Pixel math on uint8 wraps around silently, because 8-bit unsigned integers only hold 0 to 255. Adding to brighten an image can turn white pixels black.

Python Brightening safely

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The pattern for image math is always the same: convert to a wider integer or to float, compute, np.clip to the legal range, then convert back to uint8. See Data Types for why wraparound happens and Type Conversion for the casting rules.

To work with real image files, libraries such as Pillow or imageio read a JPEG or PNG into exactly this kind of array and write it back. The examples here generate their own pictures, and the next lesson, Working with Real Images, shows the file round trip with Pillow.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the usual shape and dtype of an RGB image array 100 pixels high and 200 wide?

    Images are stored as (height, width, channels), and 8-bit channels use uint8 with values 0 to 255.
  2. 2. What does img[:, ::-1] do?

    The second index selects columns; reversing them mirrors the picture horizontally. img[::-1] would flip rows, and img[..., ::-1] reverses channels.
  3. 3. Why can np.array([200], dtype=np.uint8) + 100 give a surprising result?

    Unsigned 8-bit integers wrap silently on array arithmetic: 300 mod 256 = 44. Widen the dtype or use floats and clip.
  4. 4. Which expression converts an (H, W, 3) RGB array img into grayscale using weights w of shape (3,)?

    Matrix-multiplying the last axis by the weights computes a weighted sum per pixel and yields shape (H, W).

Summary

  • A color image is a (height, width, 3) array, usually uint8; grayscale is (height, width). Row 0 is the top.
  • Generate pictures with np.linspace, np.mgrid and boolean masks; paint with masked assignment.
  • img[..., 0] selects a channel, img[:, ::-1] mirrors, img[::-1] flips vertically, and img[r0:r1, c0:c1] crops, all as views.
  • Grayscale is a weighted sum of channels, img @ [0.299, 0.587, 0.114]; thresholding is a comparison that gives a boolean mask.
  • uint8 arithmetic wraps. Widen or use floats, np.clip, then cast back.
  • ax.imshow draws image arrays (uint8 0 to 255, or float 0 to 1) and ax.plot draws 1D arrays.

Next, move from pictures to waveforms in Signals, Convolution and the FFT.