How to create colour gradient in Python? How to create colour gradient in Python? python python

How to create colour gradient in Python?


A simple answer I have not seen yet is to just use the colour package.

Install via pip

pip install colour

Use as so:

from colour import Colorred = Color("red")colors = list(red.range_to(Color("green"),10))    # colors is now a list of length 10# Containing: # [<Color red>, <Color #f13600>, <Color #e36500>, <Color #d58e00>, <Color #c7b000>, <Color #a4b800>, <Color #72aa00>, <Color #459c00>, <Color #208e00>, <Color green>]

Change the inputs to any colors you want. As noted by @zelusp, this will not restrict itself to a smooth combination of only two colors (e.g. red to blue will have yellow+green in the middle), but based on the upvotes it's clear a number of folks find this to be a useful approximation


If you just need to interpolate in between 2 colors, I wrote a simple function for that. colorFader creates you a hex color code out of two other hex color codes.

import matplotlib as mplimport matplotlib.pyplot as pltimport numpy as npdef colorFader(c1,c2,mix=0): #fade (linear interpolate) from color c1 (at mix=0) to c2 (mix=1)    c1=np.array(mpl.colors.to_rgb(c1))    c2=np.array(mpl.colors.to_rgb(c2))    return mpl.colors.to_hex((1-mix)*c1 + mix*c2)c1='#1f77b4' #bluec2='green' #greenn=500fig, ax = plt.subplots(figsize=(8, 5))for x in range(n+1):    ax.axvline(x, color=colorFader(c1,c2,x/n), linewidth=4) plt.show()

result:

simple color mixing in python

update due to high interest:

colorFader works now for rgb-colors and color-strings like 'red' or even 'r'.


It's obvious that your original example gradient is not linear. Have a look at a graph of the red, green, and blue values averaged across the image:

example gradient graph

Attempting to recreate this with a combination of linear gradients is going to be difficult.

To me each color looks like the addition of two gaussian curves, so I did some best fits and came up with this:

simulated

Using these calculated values lets me create a really pretty gradient that matches yours almost exactly.

import mathfrom PIL import Imageim = Image.new('RGB', (604, 62))ld = im.load()def gaussian(x, a, b, c, d=0):    return a * math.exp(-(x - b)**2 / (2 * c**2)) + dfor x in range(im.size[0]):    r = int(gaussian(x, 158.8242, 201, 87.0739) + gaussian(x, 158.8242, 402, 87.0739))    g = int(gaussian(x, 129.9851, 157.7571, 108.0298) + gaussian(x, 200.6831, 399.4535, 143.6828))    b = int(gaussian(x, 231.3135, 206.4774, 201.5447) + gaussian(x, 17.1017, 395.8819, 39.3148))    for y in range(im.size[1]):        ld[x, y] = (r, g, b)

recreated gradient

Unfortunately I don't yet know how to generalize it to arbitrary colors.