Ben Gorman

Ben Gorman

Life's a garden. Dig it.

Challenge

Here's a cat.

cat

Download the image, then convert it to a NumPy array. Then alter the array so that

  1. Red values become blue values
  2. Green values become red values
  3. Blue values become green values

Then plot the resulting image.

STOP

Think about what the output should look like before you create it.

Solution

Transformed cat

  1. Load the image with Image.open() from Pillow.

    import numpy as np
    from PIL import Image
     
    # Load the image
    im = Image.open('CV-cat.jpg')

    You can inspect the image's format, size, and mode like this 👇

    # Inspect the image
    print(im.format, im.size, im.mode)
  2. Convert the image to a NumPy array

    # Convert img to a numpy array
    original = np.array(im)
  3. Swap the color channels and convert the resuling array into an Image instance with Image.fromarray()

    # Re-index the color channels RGB -> BRG
    transformed = original[:, :, [1,2,0]]
     
    # Plot the transformed array
    Image.fromarray(transformed)