Skip to content
Advertisement

Generate random colors (RGB)

I just picked up image processing in python this past week at the suggestion of a friend to generate patterns of random colors. I found this piece of script online that generates a wide array of different colors across the RGB spectrum.

def random_color():
    levels = range(32,256,32)
    return tuple(random.choice(levels) for _ in range(3))

I am simply interesting in appending this script to only generate one of three random colors. Preferably red, green, and blue.

Advertisement

Answer

Here:

def random_color():
    rgbl=[255,0,0]
    random.shuffle(rgbl)
    return tuple(rgbl)

The result is either red, green or blue. The method is not applicable to other sets of colors though, where you’d have to build a list of all the colors you want to choose from and then use random.choice to pick one at random.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement