Gradient

Let’s create color gradients:

image0

Here is the code that creates the gradients:


from PIL import Image
import numpy as np

a = np.zeros((300, 1200, 3), dtype=np.uint8)

full = np.zeros((100, 1200), dtype=np.uint8)
full[:100, :] = np.linspace(0, 255, 1200, dtype=np.uint8)

half = np.zeros((100, 1200), dtype=np.uint8)
half[:100, :] = np.linspace(0, 127, 1200, dtype=np.uint8)

a[:100, :, 0] = full
a[100:200, ::-1, 1] = full
a[200:, :, 1] = half
a[200:, :, 2] = full

im = Image.fromarray(a)
im.save('gradient.png')

The code first creates a grayscale gradient that is later copied into the RGB array.

image1

Hints

  • the np.linspace() function creates numbers in evenly spaced intervals

  • the parameters indicate the first and last number and the number of points

  • by default it creates floating point numbers

  • setting dtype=np.uint8 rounds the numbers

  • the [::-1] notation slices an array in the opposite direction

To create a vertical gradient, you need to transpose the image (swap x and y).

Note that you may need to create the gradient with swapped dimensions:

vertical = np.zeros((1200, 300), dtype=np.uint8)
vertical[:1200, :] = np.linspace(0, 255, 300, dtype=np.uint8)
a[:, :1200, :, 0] = vertical.T

Challenge

Mix horizontal and vertical gradients:

image2