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()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
MediumA 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.
- Turn
scaninto an array and invert it: each pixel becomes 255 minus its value. - 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:
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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Data and Plots
2NumPy Arrays
Creating ArraysShape and SizeRanges of NumbersIndexing and SlicingRecap: Temperature GridPractice on your own: Online Python compiler