Python Pillow: Generate Gradient Image with NumPy

In this tutorial, we will use python pillow and numpy to generate gradient image. You can create one by following our tutorial.

Python Pillow - Generate Gradient Image with NumPy for Beginners

1.Key to generate gradient image

To generate gradient image, we should use numpy to create a numpy array with the shape (width, height, 3).

2.Create gradient image numpy data

def get_gradient_2d(start, stop, width, height, is_horizontal):
    if is_horizontal:
        return np.tile(np.linspace(start, stop, width), (height, 1))
        return np.tile(np.linspace(start, stop, height), (width, 1)).T
def get_gradient_3d(width, height, start_list, stop_list, is_horizontal_list):
    result = np.zeros((height, width, len(start_list)), dtype=np.float)

    for i, (start, stop, is_horizontal) in enumerate(zip(start_list, stop_list, is_horizontal_list)):
        result[:, :, i] = get_gradient_2d(start, stop, width, height, is_horizontal)

    return result

3.Create image by numpy data

from PIL import Image

array = get_gradient_3d(512, 256, (0, 0, 192), (255, 255, 64), (True, False, False))
Image.fromarray(np.uint8(array)).save('data/dst/color_gradient.jpg', quality=95)

Run this code, you will see this gradient image.

Python Pillow: Generate Gradient Image with NumPy