Python: Randomly generate and RGB Tuple

Date: 2019-09-30 | python | rgb | random | tutorial |

problem

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?

solution

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.

did this help?

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.

Want more like this?

The best / easiest way to support my work is by subscribing for future updates and sharing with your network.