I’m building a generative art program in Python and part of the process is to randomize the color I’ll be drawing with. How do I create a random RGB value in Python?
Basically you’ve just got to combine Python’s
random module with a drawing library of your choice (I typically use
opencv). To randomize the color, you can do something like:
import random import time from typing import Tuple def generate_random_rgb_tuple( seeded_random ) -> Tuple[int, int, int]: return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) random.seed(time.time()) print(generate_random_rgb_tuple(random))
The important part is just the definition of
generate_random_rgb_tuple, but I’ve found it is best practice to seed your
random with some value for better debugging. The output of this run, for me, was
(195, 111, 116) which you can then pass to whatever RGB-compatible drawing library you want to use.
I regularly post about tech topics I run into. You can get a periodic email containing updates on new posts and things I’ve built by subscribing here.
Hi I'm Hamilton and I wrote / built this! I like doing lots of things, but mostly I like to build (and then share those buildings). Some things I'm currently building: art, software, and prose. To stay up-to-date with my latest buildings, subscribe to my email list or follow one of my many other accounts. #buildit #shipit #justhamit