DEV Community

Cover image for Creating gradient images using only Python NumPy
Manish Aradwad
Manish Aradwad

Posted on

Creating gradient images using only Python NumPy

Here’s the backstory of this article:

I was working on a Computer Vision Project as a part of an internship and I needed a script which can generate custom B/W gradient images. By custom gradient, I mean images like this:

Cross Gradient

Linear Gradient

Parabolic Gradient

Along with the above structures, I also wanted to vary the spread of the gradient and combine different such structures to get the following samples:

Combination of Cross and Parabolic Gradient

Combination of Linear and Parabolic Gradient

Combination of Two Parabolic Gradients

I tried to search online but couldn’t find the solution which I really wanted. To help others like me, I decided to write this article. I use NumPy arrays with loops to generate such gradient images.

Code:

Gradients are essentially uneven arrays of numbers. So first, we have to write a function for uneven array creation. Refer this for explanation:

We can use this function for creating different types of gradients as follows:

Finally, we can write a function which returns a gradient of one of the above types with random parameters:

Finally, when we run the custom_gradient() function, it will return one of the gradient image type. Complete code is available in this notebook.

Thanks for reading :)

Have a nice day!

Top comments (0)