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.

15 Answers

A neat way to generate RGB triplets within the 256 (aka 8-byte) range is

color = list(np.random.choice(range(256), size=3))

color is now a list of size 3 with values in the range 0-255. You can save it in a list to record if the color has been generated before or no.

3

You could also use Hex Color Code,

Name    Hex Color Code  RGB Color Code
Red     #FF0000         rgb(255, 0, 0)
Maroon  #800000         rgb(128, 0, 0)
Yellow  #FFFF00         rgb(255, 255, 0)
Olive   #808000         rgb(128, 128, 0)

For example

import matplotlib.pyplot as plt
import random

number_of_colors = 8

color = ["#"+''.join([random.choice('0123456789ABCDEF') for j in range(6)])
             for i in range(number_of_colors)]
print(color)

['#C7980A', '#F4651F', '#82D8A7', '#CC3A05', '#575E76', '#156943', '#0BD055', '#ACD338']

Lets try plotting them in a scatter plot

for i in range(number_of_colors):
    plt.scatter(random.randint(0, 10), random.randint(0,10), c=color[i], s=200)

plt.show()
1

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.

0
color = lambda : [random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)]
2

If you don't want your color to be sampled from the full possible space of 256×256×256 colors -- since colors produced this way may not look "pretty", many of them being too dark or too white -- you may want to sample a color from a colormap.

The package cmapy contains color maps from Matplotlib (scroll down for showcase), and allows simple random sampling:

import cmapy
import random
rgb_color = cmapy.color('viridis', random.randrange(0, 256), rgb_order=True)

You can make the colors more distinct by adding a range step: random.randrange(0, 256, 10).

Inspired by other answers this is more correct code that produces integer 0-255 values and appends alpha=255 if you need RGBA:

tuple(np.random.randint(256, size=3)) + (255,)

If you just need RGB:

tuple(np.random.randint(256, size=3))
1

In pygame, you can do this:

import pygame
import random

r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
rand_color = (r, g, b)

For less lines, here is an alternative:

import pygame
import random

rand_color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))

Then you can create a shape with the argument rand_color for a random color, for example:

pygame.draw.line(screen, rand_color, (0, 0), (600, 400), 20)

You don't really need to use it in pygame, that was just an example. I'm pretty sure you can do this in the rest of Python.

With custom colours (for example, dark red, dark green and dark blue):

import random

COLORS = [(139, 0, 0), 
          (0, 100, 0),
          (0, 0, 139)]

def random_color():
    return random.choice(COLORS)
0

Taking a uniform random variable as the value of RGB may generate a large amount of gray, white, and black, which are often not the colors we want.

The cv::applyColorMap can easily generate a random RGB palette, and you can choose a favorite color map from the list here

Example for C++11:

#include <algorithm>
#include <numeric>
#include <random>
#include <opencv2/opencv.hpp>

std::random_device rd;
std::default_random_engine re(rd());

// Generating randomized palette
cv::Mat palette(1, 255, CV_8U);
std::iota(palette.data, palette.data + 255, 0);
std::shuffle(palette.data, palette.data + 255, re);
cv::applyColorMap(palette, palette, cv::COLORMAP_JET);

// ...

// Picking random color from palette and drawing
auto randColor = palette.at<cv::Vec3b>(i % palette.cols);
cv::rectangle(img, cv::Rect(0, 0, 100, 100), randColor, -1);

Example for Python3:

import numpy as np, cv2

palette = np.arange(0, 255, dtype=np.uint8).reshape(1, 255, 1)
palette = cv2.applyColorMap(palette, cv2.COLORMAP_JET).squeeze(0)
np.random.shuffle(palette)
# ...

rand_color = tuple(palette[i % palette.shape[0]].tolist())
cv2.rectangle(img, (0, 0), (100, 100), rand_color, -1)

If you don't need so many colors, you can just cut the palette to the desired length.

Output in the form of (r,b,g) its look like (255,155,100)

from numpy import random
color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))

Below solution is without any external package

import random

def pyRandColor():
    randNums = [random.random() for _ in range(0, 3)]

    RGB255 = list([ int(i * 255) for i in randNums ])
    RGB1 = list([ round(i, 2) for i in randNums ])
    return RGB1

Example use-case:

print(pyRandColor())
# Output: [0.53, 0.57, 0.97]

Note:

  • RGB255 returns list of 3 integers between 0 and 255
  • RGB1 return list of 3 decimals between 0 & 1

You can use %x operator coupled with randint here to generate colors

colors_ = lambda n: list(map(lambda i: "#" + "%06x" % random.randint(0, 0xFFFFFF),range(n)))

Run the function to generate 2 random colors:

colors_(2)

Output ['#883116', '#032a54']

Try this code

import numpy as np

R=np.array(list(range(255))
G=np.array(list(range(255))
B=np.array(list(range(255))
np.random.shuffle(R)
np.random.shuffle(G)
np.random.shuffle(B)
def get_color():

    for i in range(255):
         yield (R[i],G[i],B[i])
palette=get_color()
random_color=next(palette) # you can run this line 255 times 
1

Let's suppose that you have a data frame, or any array you could generate random colors or sequential colors as follow bellow.

For random colors (you could choose each random colors you will generate):

arraySize = len(df.month)
colors = ['', ] * arraySize
color = ["red", "blue", "green", "gray", "purple", "orange"]
for n in range(arraySize):
    colors[n] = cor[random.randint(0, 5)]

For sequential colors:

import random    
arraySize = len(df.month)
colors = ['', ] * arraySize
color = ["red", "blue", "green", "yellow", "purple", "orange"]
i = 0
for n in range(arraySize):
    if (i >= len(color)):
        i = 0
    colors[n] = color[i]
    i = i+1
import random
rgb_full=(random.randint(1,255), random.randint(1,255), random.randint(1,255))
4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest