Reputation: 543
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.
Upvotes: 53
Views: 260052
Reputation: 384
Using random.randint()
:
from random import randint
r = randint(0, 255)
g = randint(0, 255)
b = randint(0, 255)
rand_color = (r, g, b)
You can also use random.randrange()
for less typing.
from random import randrange
r = randrange(255)
g = randrange(255)
b = randrange(255)
rand_color = (r, g, b)
You can even do this using one line!
from random import randrange
rand_color = (randrange(255), randrange(255), randrange(255))
To shorten this code even more, you can use list comprehension:
from random import randrange
rand_color = [randrange(255) for _ in range(3)]
If you wanted random RGBA values, you could use the random.random()
function, combined with the built-in round()
function (as described here):
from random import randrange, random
rand_color = list(randrange(255), randrange(255), randrange(255), round(random(), 1))
Upvotes: 9
Reputation: 455
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, 256, dtype=np.uint8).reshape(1, 256, 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.
Upvotes: 2
Reputation: 24
from random import randint,choice
from PIL import ImageColor
#random choice colorlist
colorlist = ["#23a9dd","#BE6E46","#CDE7B0","#A3BFA8"]
#random r g b select
r = randint(0, 255)
g = randint(0, 255)
b = randint(0, 255)
#random choice selector
qcl = choice(RandomColorButton.colorlist)
rand_color = (r, g, b)
#random choice selected convert in RGB int
print(ImageColor.getcolor(qcl, "RGB"))
print(rand_color)
Upvotes: -3
Reputation: 71
The following code generates a random RGB number (0-255, 0-255, 0-255)
.
color = lambda : [random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)]
Upvotes: 7
Reputation: 45
import random
rgb_full=(random.randint(1,255), random.randint(1,255), random.randint(1,255))
Upvotes: 0
Reputation: 8560
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
Upvotes: 0
Reputation: 7284
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 255RGB1
return list of 3 decimals between 0 & 1Upvotes: 2
Reputation: 144
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
Upvotes: 0
Reputation: 436
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']
Upvotes: 1
Reputation: 1868
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)
.
Upvotes: 7
Reputation: 510
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))
Upvotes: 1
Reputation: 68708
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))
Upvotes: 6
Reputation: 4506
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()
Upvotes: 65
Reputation: 3032
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.
Upvotes: 95
Reputation: 716
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.
Upvotes: 27
Reputation: 29324
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)
Upvotes: 4