1

I want to create a gradient of N distinct colors ranging from a dark color to a light color, all visually equidistant apart.

Similar like in this answer but for Python instead of R (can only use standard lib though, not eg. numpy).

I'd like a function where I can give as arguments the dark color, e.g. RGB(103,0,13), and the light color, e.g. RGB(255,245,240), and the number of shades. Similar like the output from ColorBrewer (but there I can't define the two end colors and I am limited to maximum 9 shades).

enter image description here

edit: What I tried so far: convert the RGB values to HLS using colorsys.rgb_to_hls(r, g, b) and interpolating the Hue between the dark and the light colors.

Community
  • 1
  • 1
BioGeek
  • 21,897
  • 23
  • 83
  • 145

1 Answers1

2

Here's one way. Note, however, that the example gradient you posted above is a non-linear gradient of some kind. The function below generates linear gradients.

def generateColorGradient(RGB1, RGB2, n):
    dRGB = [float(x2-x1)/(n-1) for x1, x2 in zip(RGB1, RGB2)]
    gradient = [tuple([int(x+k*dx) for x, dx in zip(RGB1, dRGB)]) for k in range(n)]
    return gradient

print generateColorGradient((103,0,13), (255,245,240), 9)

# OUTPUT
# [(103, 0, 13), (122, 30, 41), (141, 61, 69), (160, 91, 98), (179, 122, 126), (198, 153, 154), (217, 183, 183), (236, 214, 211), (255, 245, 240)]
Brionius
  • 13,858
  • 3
  • 38
  • 49
  • 3
    _"the example gradient you posted above is a non-linear gradient of some kind."_ Perhaps the OP is using a more exotic definition of "visually equidistant" than "evenly spaced RGB values". There are a number of [equations](http://en.wikipedia.org/wiki/Color_difference) that describe the human perception of color difference. Your algorithm works well with the CIE76 formula if you convert to Lab color space before doing the gradient, and converting back to RGB afterwards. – Kevin Jun 03 '14 at 13:52
  • Interesting. I did not know that a formula existed for perceptive color. – Brionius Jun 03 '14 at 14:22