Generate random colors (RGB)

2020-05-24 02:39发布

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.

6条回答
【Aperson】
2楼-- · 2020-05-24 02:52

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))
查看更多
beautiful°
3楼-- · 2020-05-24 02:57

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.

查看更多
女痞
4楼-- · 2020-05-24 03:05

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.

查看更多
何必那么认真
5楼-- · 2020-05-24 03:06

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楼-- · 2020-05-24 03:09
color = lambda : [random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)
查看更多
闹够了就滚
7楼-- · 2020-05-24 03:12

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)
查看更多
登录 后发表回答