生成随机颜色 (RGB)

Generate random colors (RGB)

上周我刚刚在 python 中学习了图像处理,这是在朋友的建议下生成随机颜色图案的。我在网上找到了这段脚本,它可以在 RGB 光谱中生成各种不同的颜色。

def random_color():
    levels = range(32,256,32)
    return tuple(random.choice(levels) for _ in range(3))

我只是想附加此脚本以仅生成三种随机颜色中的一种。最好是红色、绿色和蓝色。

这里:

def random_color():
    rgbl=[255,0,0]
    random.shuffle(rgbl)
    return tuple(rgbl)

结果是红色、绿色或蓝色。但是该方法不适用于其他颜色集,您必须构建一个包含所有要选择的颜色的列表,然后使用 random.choice 随机选择一个。

使用自定义颜色(例如,深红色、深绿色和深蓝色):

import random

COLORS = [(139, 0, 0), 
          (0, 100, 0),
          (0, 0, 139)]

def random_color():
    return random.choice(COLORS)

在 256(又名 8 字节)范围内生成 RGB 三元组的一种巧妙方法是

color = list(np.random.choice(range(256), size=3))

color 现在是大小为 3 的列表,其值在 0-255 范围内。可以保存在一个列表中记录颜色是否已经生成过或者没有。

您也可以使用十六进制颜色代码,

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)

例如

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

让我们尝试将它们绘制成散点图

for i in range(number_of_colors):
    plt.scatter(random.randint(0, 10), random.randint(0,10), c=color[i], s=200)

plt.show()

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

受其他答案的启发,这是更正确的代码,它生成 0-255 整数值并在需要 RGBA 时附加 alpha=255:

tuple(np.random.randint(256, size=3)) + (255,)

如果你只需要RGB:

tuple(np.random.randint(256, size=3))
import random
rgb_full=(random.randint(1,255), random.randint(1,255), random.randint(1,255))

以 (r,b,g) 的形式输出它看起来像 (255,155,100)

from numpy import random
color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))

取一个统一的随机变量作为RGB的取值,可能会产生大量的灰白黑,往往不是我们想要的颜色

cv::applyColorMap can easily generate a random RGB palette, and you can choose a favorite color map from the list here

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

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)

如果不需要那么多颜色,可以将调色板裁剪成想要的长度即可。

在pygame中,您可以这样做:

import pygame
import random

r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
rand_color = (r, g, b)

对于更少的行,这里有一个替代方法:

import pygame
import random

rand_color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))

然后您可以使用参数 rand_color 创建一个随机颜色的形状,例如:

pygame.draw.line(screen, rand_color, (0, 0), (600, 400), 20)

您实际上不需要在 pygame 中使用它,这只是一个示例。我很确定您可以在 Python.

的其余部分完成此操作

如果您不希望您的颜色从 256×256×256 种可能的全部 space 颜色中采样 -- 因为以这种方式生成的颜色可能看起来不“漂亮”,其中许多颜色太暗或太白 -- 您可能想要从颜色图中采样颜色。

cmapy contains color maps from Matplotlib(向下滚动以查看展示),并允许简单随机抽样:

import cmapy
import random
rgb_color = cmapy.color('viridis', random.randrange(0, 256), rgb_order=True)

您可以通过添加范围步骤使颜色更加鲜明:random.randrange(0, 256, 10)

您可以在这里使用 %x 运算符和 randint 来生成颜色

colors_ = lambda n: list(map(lambda i: "#" + "%06x" % random.randint(0, 0xFFFFFF),range(n)))

运行生成2种随机颜色的函数:

colors_(2)

输出 ['#883116', '#032a54']

试试这个代码

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 

以下解决方案没有任何外部包

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

示例用例:

print(pyRandColor())
# Output: [0.53, 0.57, 0.97]

注:

  • RGB255 returns 包含 0 到 255 之间的 3 个整数的列表
  • RGB1 return 0 和 1 之间的 3 位小数列表

假设您有一个数据框,或者任何可以生成随机颜色或顺序颜色的数组,如下所示。

对于随机颜色(您可以选择要生成的每种随机颜色):

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

对于连续颜色:

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