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.
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.
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.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With