Menu
CoddyTech

Images as Arrays

Part of the Data and Plots section of Coddy's Machine Learning journey. Lesson 29 of 60.

A black and white photo is a grid of numbers, one brightness per pixel. So a 2D array is an image, and ax.imshow draws it:

plus = np.array([[0, 0, 1, 0, 0],
                 [0, 0, 1, 0, 0],
                 [1, 1, 1, 1, 1],
                 [0, 0, 1, 0, 0],
                 [0, 0, 1, 0, 0]])
fig, ax = plt.subplots()
ax.imshow(plus, cmap="gray")
plt.show()

A 5 by 5 image of a white plus sign on black, each pixel showing its value: 1 on the white cross, 0 on the black corners

cmap="gray" picks the gray color map: the smallest value black, the largest white. Row 0 is drawn on top, as the array is written.

Photos usually store 0 (black) to 255 (white). Later in this journey, a model reads handwritten digits stored exactly like this.

challenge icon

Challenge

Medium

A scanner read a printed letter but stored it inverted: bright ink on dark paper. The nested list scan holds each pixel's brightness, 0 to 255.

  1. Turn scan into an array and invert it: each pixel becomes 255 minus its value.
  2. Draw it with the gray color map, titled Letter E, and show it.

Yours should look like this one, a scanned L after the fix:

A small black letter L on a white background, 7 pixels tall and 5 wide, titled Letter L

Your program prints nothing. Coddy describes your image, row by row.

Try it yourself

import numpy as np
import matplotlib.pyplot as plt

scan = [[255, 255, 255, 255, 255],
        [255, 30, 0, 0, 0],
        [255, 0, 0, 0, 0],
        [255, 255, 255, 200, 0],
        [255, 0, 0, 0, 0],
        [255, 0, 0, 0, 15],
        [255, 255, 255, 255, 255]]

# Write your code below
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Data and Plots

Practice on your own: Online Python compiler