Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random colors (RGB)

Tags:

python

random

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.

like image 986
Travis A. Avatar asked Mar 11 '15 23:03

Travis A.


People also ask

How do you generate random RGB colors in python?

Using random() function to generate random colors To begin, import the random function in Python to obtain a random color. The variable r stands for red, g stands for green, and b stands for blue. We already know that the RGB format contains an integer value ranging from 0 to 255.

How do you create a color object with a random color?

Random rand = new Random(); As colours are separated into red green and blue, you can create a new random colour by creating random primary colours: // Java 'Color' class takes 3 floats, from 0 to 1. float r = rand.


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

like image 134
varagrawal Avatar answered Sep 21 '22 06:09

varagrawal


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

like image 45
Khalil Al Hooti Avatar answered Sep 24 '22 06:09

Khalil Al Hooti