I wrote the two methods below to automatically select N distinct colors. It works by defining a piecewise linear function on the RGB cube. The benefit of this is you can also get a progressive scale if that's what you want, but when N gets large the colors can start to look similar. I can also imagine evenly subdividing the RGB cube into a lattice and then drawing points. Does anyone know any other methods? I'm ruling out defining a list and then just cycling through it. I should also say I don't generally care if they clash or don't look nice, they just have to be visually distinct.

public static List<Color> pick(int num) {
    List<Color> colors = new ArrayList<Color>();
    if (num < 2)
        return colors;
    float dx = 1.0f / (float) (num - 1);
    for (int i = 0; i < num; i++) {
        colors.add(get(i * dx));
    }
    return colors;
}

public static Color get(float x) {
    float r = 0.0f;
    float g = 0.0f;
    float b = 1.0f;
    if (x >= 0.0f && x < 0.2f) {
        x = x / 0.2f;
        r = 0.0f;
        g = x;
        b = 1.0f;
    } else if (x >= 0.2f && x < 0.4f) {
        x = (x - 0.2f) / 0.2f;
        r = 0.0f;
        g = 1.0f;
        b = 1.0f - x;
    } else if (x >= 0.4f && x < 0.6f) {
        x = (x - 0.4f) / 0.2f;
        r = x;
        g = 1.0f;
        b = 0.0f;
    } else if (x >= 0.6f && x < 0.8f) {
        x = (x - 0.6f) / 0.2f;
        r = 1.0f;
        g = 1.0f - x;
        b = 0.0f;
    } else if (x >= 0.8f && x <= 1.0f) {
        x = (x - 0.8f) / 0.2f;
        r = 1.0f;
        g = 0.0f;
        b = x;
    }
    return new Color(r, g, b);
}

当前回答

这个OpenCV函数使用HSV颜色模型在0<=H<=360º周围生成n个均匀分布的颜色,最大S=1.0, V=1.0。函数在bgr_mat中输出BGR颜色:

void distributed_colors (int n, cv::Mat_<cv::Vec3f> & bgr_mat) {
  cv::Mat_<cv::Vec3f> hsv_mat(n,CV_32F,cv::Vec3f(0.0,1.0,1.0));
  double step = 360.0/n;
  double h= 0.0;
  cv::Vec3f value;
  for (int i=0;i<n;i++,h+=step) {
    value = hsv_mat.at<cv::Vec3f>(i);
    hsv_mat.at<cv::Vec3f>(i)[0] = h;
  }
  cv::cvtColor(hsv_mat, bgr_mat, CV_HSV2BGR);
  bgr_mat *= 255;
}

其他回答

这个问题出现在相当多的SO讨论中:

生成独特颜色的算法 生成独特的颜色 在图形中生成明显不同的RGB颜色 如何为任意自然数n生成n种不同的颜色?

提出了不同的解决方案,但没有一个是最优的。幸运的是,科学来拯救我们

任意N

彩色显示分类图像(免费下载) 一个个性化地图着色的网络服务(免费下载,一个网络服务解决方案应该在下个月可用) 选择高对比度颜色集的算法(作者提供了一个免费的c++实现) 高对比度的颜色集(问题的第一个算法)

最后两本将通过大多数大学图书馆/代理免费提供。

N是有限且相对较小的

在这种情况下,可以使用列表解决方案。关于这个主题,有一篇非常有趣的文章是免费的:

《彩色字母表和彩色编码的局限性》

有几个颜色列表可以考虑:

Boynton列出了11种几乎不会被混淆的颜色(可在前一节的第一篇论文中找到) Kelly的22种最大对比度的颜色(可以在上面的论文中找到)

我还遇到了一个麻省理工学院学生的这个调色板。 最后,下面的链接在不同颜色系统/坐标之间的转换可能是有用的(例如,文章中的一些颜色没有在RGB中指定):

http://chem8.org/uch/space-55036-do-blog-id-5333.html https://metacpan.org/pod/Color::Library::Dictionary::NBS_ISCC 色彩理论:如何将孟塞尔HVC转换为RGB/HSB/HSL

对于Kelly和Boynton的列表,我已经将其转换为RGB(除了白色和黑色,这应该很明显)。一些c#代码:

public static ReadOnlyCollection<Color> KellysMaxContrastSet
{
    get { return _kellysMaxContrastSet.AsReadOnly(); }
}

private static readonly List<Color> _kellysMaxContrastSet = new List<Color>
{
    UIntToColor(0xFFFFB300), //Vivid Yellow
    UIntToColor(0xFF803E75), //Strong Purple
    UIntToColor(0xFFFF6800), //Vivid Orange
    UIntToColor(0xFFA6BDD7), //Very Light Blue
    UIntToColor(0xFFC10020), //Vivid Red
    UIntToColor(0xFFCEA262), //Grayish Yellow
    UIntToColor(0xFF817066), //Medium Gray

    //The following will not be good for people with defective color vision
    UIntToColor(0xFF007D34), //Vivid Green
    UIntToColor(0xFFF6768E), //Strong Purplish Pink
    UIntToColor(0xFF00538A), //Strong Blue
    UIntToColor(0xFFFF7A5C), //Strong Yellowish Pink
    UIntToColor(0xFF53377A), //Strong Violet
    UIntToColor(0xFFFF8E00), //Vivid Orange Yellow
    UIntToColor(0xFFB32851), //Strong Purplish Red
    UIntToColor(0xFFF4C800), //Vivid Greenish Yellow
    UIntToColor(0xFF7F180D), //Strong Reddish Brown
    UIntToColor(0xFF93AA00), //Vivid Yellowish Green
    UIntToColor(0xFF593315), //Deep Yellowish Brown
    UIntToColor(0xFFF13A13), //Vivid Reddish Orange
    UIntToColor(0xFF232C16), //Dark Olive Green
};

public static ReadOnlyCollection<Color> BoyntonOptimized
{
    get { return _boyntonOptimized.AsReadOnly(); }
}

private static readonly List<Color> _boyntonOptimized = new List<Color>
{
    Color.FromArgb(0, 0, 255),      //Blue
    Color.FromArgb(255, 0, 0),      //Red
    Color.FromArgb(0, 255, 0),      //Green
    Color.FromArgb(255, 255, 0),    //Yellow
    Color.FromArgb(255, 0, 255),    //Magenta
    Color.FromArgb(255, 128, 128),  //Pink
    Color.FromArgb(128, 128, 128),  //Gray
    Color.FromArgb(128, 0, 0),      //Brown
    Color.FromArgb(255, 128, 0),    //Orange
};

static public Color UIntToColor(uint color)
{
    var a = (byte)(color >> 24);
    var r = (byte)(color >> 16);
    var g = (byte)(color >> 8);
    var b = (byte)(color >> 0);
    return Color.FromArgb(a, r, g, b);
}

下面是十六进制和每通道8位的RGB值:

kelly_colors_hex = [
    0xFFB300, # Vivid Yellow
    0x803E75, # Strong Purple
    0xFF6800, # Vivid Orange
    0xA6BDD7, # Very Light Blue
    0xC10020, # Vivid Red
    0xCEA262, # Grayish Yellow
    0x817066, # Medium Gray

    # The following don't work well for people with defective color vision
    0x007D34, # Vivid Green
    0xF6768E, # Strong Purplish Pink
    0x00538A, # Strong Blue
    0xFF7A5C, # Strong Yellowish Pink
    0x53377A, # Strong Violet
    0xFF8E00, # Vivid Orange Yellow
    0xB32851, # Strong Purplish Red
    0xF4C800, # Vivid Greenish Yellow
    0x7F180D, # Strong Reddish Brown
    0x93AA00, # Vivid Yellowish Green
    0x593315, # Deep Yellowish Brown
    0xF13A13, # Vivid Reddish Orange
    0x232C16, # Dark Olive Green
    ]

kelly_colors = dict(vivid_yellow=(255, 179, 0),
                    strong_purple=(128, 62, 117),
                    vivid_orange=(255, 104, 0),
                    very_light_blue=(166, 189, 215),
                    vivid_red=(193, 0, 32),
                    grayish_yellow=(206, 162, 98),
                    medium_gray=(129, 112, 102),

                    # these aren't good for people with defective color vision:
                    vivid_green=(0, 125, 52),
                    strong_purplish_pink=(246, 118, 142),
                    strong_blue=(0, 83, 138),
                    strong_yellowish_pink=(255, 122, 92),
                    strong_violet=(83, 55, 122),
                    vivid_orange_yellow=(255, 142, 0),
                    strong_purplish_red=(179, 40, 81),
                    vivid_greenish_yellow=(244, 200, 0),
                    strong_reddish_brown=(127, 24, 13),
                    vivid_yellowish_green=(147, 170, 0),
                    deep_yellowish_brown=(89, 51, 21),
                    vivid_reddish_orange=(241, 58, 19),
                    dark_olive_green=(35, 44, 22))

对于所有Java开发人员,以下是JavaFX的颜色:

// Don't forget to import javafx.scene.paint.Color;

private static final Color[] KELLY_COLORS = {
    Color.web("0xFFB300"),    // Vivid Yellow
    Color.web("0x803E75"),    // Strong Purple
    Color.web("0xFF6800"),    // Vivid Orange
    Color.web("0xA6BDD7"),    // Very Light Blue
    Color.web("0xC10020"),    // Vivid Red
    Color.web("0xCEA262"),    // Grayish Yellow
    Color.web("0x817066"),    // Medium Gray

    Color.web("0x007D34"),    // Vivid Green
    Color.web("0xF6768E"),    // Strong Purplish Pink
    Color.web("0x00538A"),    // Strong Blue
    Color.web("0xFF7A5C"),    // Strong Yellowish Pink
    Color.web("0x53377A"),    // Strong Violet
    Color.web("0xFF8E00"),    // Vivid Orange Yellow
    Color.web("0xB32851"),    // Strong Purplish Red
    Color.web("0xF4C800"),    // Vivid Greenish Yellow
    Color.web("0x7F180D"),    // Strong Reddish Brown
    Color.web("0x93AA00"),    // Vivid Yellowish Green
    Color.web("0x593315"),    // Deep Yellowish Brown
    Color.web("0xF13A13"),    // Vivid Reddish Orange
    Color.web("0x232C16"),    // Dark Olive Green
};

以下是根据上面的顺序未排序的凯利颜色。

以下是按色调排序的方凯利颜色(注意一些黄色的对比不是很明显)

这产生了与Janus Troelsen的溶液相同的颜色。但是它使用的不是生成器,而是开始/停止语义。它也是完全向量化的。

import numpy as np
import numpy.typing as npt
import matplotlib.colors

def distinct_colors(start: int=0, stop: int=20) -> npt.NDArray[np.float64]:
    """Returns an array of distinct RGB colors, from an infinite sequence of colors
    """
    if stop <= start: # empty interval; return empty array
        return np.array([], dtype=np.float64)
    sat_values = [6/10]         # other tones could be added
    val_values = [8/10, 5/10]   # other tones could be added
    colors_per_hue_value = len(sat_values) * len(val_values)
    # Get the start and stop indices within the hue value stream that are needed
    # to achieve the requested range
    hstart = start // colors_per_hue_value
    hstop = (stop+colors_per_hue_value-1) // colors_per_hue_value
    # Zero will cause a singularity in the caluculation, so we will add the zero
    # afterwards
    prepend_zero = hstart==0 

    # Sequence (if hstart=1): 1,2,...,hstop-1
    i = np.arange(1 if prepend_zero else hstart, hstop) 
    # The following yields (if hstart is 1): 1/2,  1/4, 3/4,  1/8, 3/8, 5/8, 7/8,  
    # 1/16, 3/16, ... 
    hue_values = (2*i+1) / np.power(2,np.floor(np.log2(i*2))) - 1
    
    if prepend_zero:
        hue_values = np.concatenate(([0], hue_values))

    # Make all combinations of h, s and v values, as if done by a nested loop
    # in that order
    hsv = np.array(np.meshgrid(hue_values, sat_values, val_values, indexing='ij')
                    ).reshape((3,-1)).transpose()

    # Select the requested range (only the necessary values were computed but we
    # need to adjust the indices since start & stop are not necessarily multiples
    # of colors_per_hue_value)
    hsv = hsv[start % colors_per_hue_value : 
                start % colors_per_hue_value + stop - start]
    # Use the matplotlib vectorized function to convert hsv to rgb
    return matplotlib.colors.hsv_to_rgb(hsv)

样品:

from matplotlib.colors import ListedColormap
ListedColormap(distinct_colors(stop=20))

ListedColormap(distinct_colors(start=30, stop=50))

我认为这个简单的递归算法补充了公认的答案,以产生不同的色调值。我为hsv做了它,但也可以用于其他颜色空间。

它在循环中产生色调,在每个循环中尽可能彼此分离。

/**
 * 1st cycle: 0, 120, 240
 * 2nd cycle (+60): 60, 180, 300
 * 3th cycle (+30): 30, 150, 270, 90, 210, 330
 * 4th cycle (+15): 15, 135, 255, 75, 195, 315, 45, 165, 285, 105, 225, 345
 */
public static float recursiveHue(int n) {
    // if 3: alternates red, green, blue variations
    float firstCycle = 3;

    // First cycle
    if (n < firstCycle) {
        return n * 360f / firstCycle;
    }
    // Each cycle has as much values as all previous cycles summed (powers of 2)
    else {
        // floor of log base 2
        int numCycles = (int)Math.floor(Math.log(n / firstCycle) / Math.log(2));
        // divDown stores the larger power of 2 that is still lower than n
        int divDown = (int)(firstCycle * Math.pow(2, numCycles));
        // same hues than previous cycle, but summing an offset (half than previous cycle)
        return recursiveHue(n % divDown) + 180f / divDown;
    }
}

我在这里找不到这种算法。我希望这对你有所帮助,这是我在这里的第一篇文章。

HSL颜色模型可能非常适合“排序”颜色,但如果您正在寻找视觉上独特的颜色,您肯定需要Lab颜色模型。

CIELAB被设计成相对于人类色觉而言在感知上是一致的,这意味着这些数值中相同数量的数值变化对应着大约相同数量的视觉感知变化。

一旦你知道了这一点,从广泛的颜色范围中找到N种颜色的最优子集仍然是一个(NP)困难问题,有点类似于旅行推销员问题,所有使用k-mean算法或其他方法的解决方案都不会有真正的帮助。

也就是说,如果N不是太大,如果你从一个有限的颜色集开始,你会很容易找到一个非常好的不同颜色的子集,根据一个简单的随机函数的Lab距离。

我编写了这样一个工具供我自己使用(你可以在这里找到:https://mokole.com/palette.html),下面是我在N=7时得到的:

它都是javascript,所以请随意查看页面的源代码,并根据自己的需要进行调整。

这在MATLAB中是微不足道的(有一个hsv命令):

cmap = hsv(number_of_colors)