Challenge¶
Download this image of a Red-headed Woodpecker.
Then convert it to a binary, black and white image like this one.
Solution¶
Here's a solution that uses
- Pillow to load the image
- NumPy to convert manipulate the array
- Matplotlib to plot the result
import numpy as np
from matplotlib import pyplot as plt
from PIL import Image
# Load the image
im = Image.open('CV-woodpecker.jpg')
# Inspect the image
print(im.format, im.size, im.mode) # JPEG (224, 224) RGB
# Convert im to a NumPy array
arr3D = np.array(im)
# Convert the array from 3D to 2D by taking the average value per pixel
arr2D = np.mean(arr3D, axis=2)
# Convert the array to binary by thresholding using the global median value
arrBinary = np.where(arr2D > np.median(arr2D), 1, 0)
# Plot the binary image
plt.imshow(
X=arrBinary,
vmin=0,
vmax=1,
interpolation='none',
cmap='gray',
)