Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating color ranges in Python

Tags:

python

colors

I want to generate a list of color specifications in the form of (r, g, b) tuples, that span the entire color spectrum with as many entries as I want. So for 5 entries I would want something like:

  • (0, 0, 1)
  • (0, 1, 0)
  • (1, 0, 0)
  • (1, 0.5, 1)
  • (0, 0, 0.5)

Of course, if there are more entries than combination of 0 and 1 it should turn to use fractions, etc. What would be the best way to do this?

like image 931
Sverre Rabbelier Avatar asked May 18 '09 09:05

Sverre Rabbelier


People also ask

How do you generate random colors in Python?

Using random() function to generate random colors To begin, import the random function in Python to obtain a random color. The variable r stands for red, g stands for green, and b stands for blue. We already know that the RGB format contains an integer value ranging from 0 to 255.

What does color () do in Python?

color() function draws a color on the image using current fill color, starting at specified position & method.


2 Answers

Use the HSV/HSB/HSL color space (three names for more or less the same thing). Generate N tuples equally spread in hue space, then just convert them to RGB.

Sample code:

import colorsys N = 5 HSV_tuples = [(x*1.0/N, 0.5, 0.5) for x in range(N)] RGB_tuples = map(lambda x: colorsys.hsv_to_rgb(*x), HSV_tuples) 
like image 76
kquinn Avatar answered Oct 02 '22 13:10

kquinn


Color palettes are interesting. Did you know that the same brightness of, say, green, is perceived more intensely than, say, red? Have a look at http://poynton.ca/PDFs/ColorFAQ.pdf. If you would like to use preconfigured palettes, have a look at seaborn's palettes:

import seaborn as sns
palette = sns.color_palette(None, 3)

Generates 3 colors from the current palette.

like image 30
serv-inc Avatar answered Oct 02 '22 12:10

serv-inc