29
votes

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.

14

14 Answers

18
votes

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.

63
votes

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.

45
votes

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()

enter image description here

6
votes
color = lambda : [random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)]
3
votes

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)
3
votes

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))
3
votes

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).

2
votes

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.

2
votes

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 shorter code, 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)
1
votes

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))
0
votes
import random
rgb_full="(" + str(random.randint(1,256))  + "," + str(random.randint(1,256))  + "," + str(random.randint(1,256))  + ")"
0
votes

To generate a random hex color:

from math import floor
from random import random

def random_hex_color(uppercase=False):
    hex_parts = '0123456789abcdef'
    
    color = '#'
    for i in range(6):
        color += hex_parts[floor(random() * 16)]
    
    if uppercase == True:
        return color.upper()
    else:
        return color

To generate a random RGB color:

from random import randint

def random_rgb_color():
    r = randint(0, 255)
    g = randint(0, 255)
    b = randint(0, 255)
    
    return tuple([r, g, b])

Both methods work as intended.

0
votes

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']

0
votes

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