Auto color selection PIL

Leif K-Brooks eurleif at ecritters.biz
Wed Sep 27 19:43:50 EDT 2006


Xiaolei wrote:
> I'm trying to plot some points in an image.  Each point has an
> associating type and I'd like to have different colors (preferrably of
> high contrast) for different types.  The number of types in the data
> file is unknown a priori.  Is there a way to do this at runtime?

If you don't know how many colors are needed even at run time, this code 
might be helpful. But it generates colors that look similar pretty 
quickly, so I wouldn't use it unless you have to. (Anyone know of a 
better algorithm for this?)

from itertools import count
from colorsys import hsv_to_rgb

def hues():
     yield 0.0
     for i in count():
         for j in xrange(2**i):
             yield (1.0 / 2**(i+1)) + ((1.0 / 2**i) * j)

def colors():
     for hue in hues():
         r, g, b = hsv_to_rgb(hue, 1.0, 1.0)
         yield int(r*255), int(g*255), int(b*255)



More information about the Python-list mailing list