Ben Gorman

Ben Gorman

Life's a garden. Dig it.

Challenge

Download this image of a Red-headed Woodpecker.

Woodpecker color

Then convert it to a binary, black and white image like this one.

Woodpecker binary

Your image will probably look a bit different because I haven't told you exactly how to convert it to binary. That's okay - just make sure your output resembles a bird.

Solution

Here's a solution that uses

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',
)