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

当前回答

这产生了与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))

其他回答

为了子孙后代,我在这里添加了Python中公认的答案。

import numpy as np
import colorsys

def _get_colors(num_colors):
    colors=[]
    for i in np.arange(0., 360., 360. / num_colors):
        hue = i/360.
        lightness = (50 + np.random.rand() * 10)/100.
        saturation = (90 + np.random.rand() * 10)/100.
        colors.append(colorsys.hls_to_rgb(hue, lightness, saturation))
    return colors

如果N足够大,你会得到一些相似的颜色。世界上只有这么多。

为什么不把它们均匀地分布在光谱中,像这样:

IEnumerable<Color> CreateUniqueColors(int nColors)
{
    int subdivision = (int)Math.Floor(Math.Pow(nColors, 1/3d));
    for(int r = 0; r < 255; r += subdivision)
        for(int g = 0; g < 255; g += subdivision)
            for(int b = 0; b < 255; b += subdivision)
                yield return Color.FromArgb(r, g, b);
}

如果您想混合序列,以便相似的颜色不在彼此旁边,您可能会打乱结果列表。

是我想得不够周全吗?

就像Uri Cohen的答案,但它是一个生成器。首先要把颜色分开。确定的。

样品,左边颜色先:

#!/usr/bin/env python3
from typing import Iterable, Tuple
import colorsys
import itertools
from fractions import Fraction
from pprint import pprint

def zenos_dichotomy() -> Iterable[Fraction]:
    """
    http://en.wikipedia.org/wiki/1/2_%2B_1/4_%2B_1/8_%2B_1/16_%2B_%C2%B7_%C2%B7_%C2%B7
    """
    for k in itertools.count():
        yield Fraction(1,2**k)

def fracs() -> Iterable[Fraction]:
    """
    [Fraction(0, 1), Fraction(1, 2), Fraction(1, 4), Fraction(3, 4), Fraction(1, 8), Fraction(3, 8), Fraction(5, 8), Fraction(7, 8), Fraction(1, 16), Fraction(3, 16), ...]
    [0.0, 0.5, 0.25, 0.75, 0.125, 0.375, 0.625, 0.875, 0.0625, 0.1875, ...]
    """
    yield Fraction(0)
    for k in zenos_dichotomy():
        i = k.denominator # [1,2,4,8,16,...]
        for j in range(1,i,2):
            yield Fraction(j,i)

# can be used for the v in hsv to map linear values 0..1 to something that looks equidistant
# bias = lambda x: (math.sqrt(x/3)/Fraction(2,3)+Fraction(1,3))/Fraction(6,5)

HSVTuple = Tuple[Fraction, Fraction, Fraction]
RGBTuple = Tuple[float, float, float]

def hue_to_tones(h: Fraction) -> Iterable[HSVTuple]:
    for s in [Fraction(6,10)]: # optionally use range
        for v in [Fraction(8,10),Fraction(5,10)]: # could use range too
            yield (h, s, v) # use bias for v here if you use range

def hsv_to_rgb(x: HSVTuple) -> RGBTuple:
    return colorsys.hsv_to_rgb(*map(float, x))

flatten = itertools.chain.from_iterable

def hsvs() -> Iterable[HSVTuple]:
    return flatten(map(hue_to_tones, fracs()))

def rgbs() -> Iterable[RGBTuple]:
    return map(hsv_to_rgb, hsvs())

def rgb_to_css(x: RGBTuple) -> str:
    uint8tuple = map(lambda y: int(y*255), x)
    return "rgb({},{},{})".format(*uint8tuple)

def css_colors() -> Iterable[str]:
    return map(rgb_to_css, rgbs())

if __name__ == "__main__":
    # sample 100 colors in css format
    sample_colors = list(itertools.islice(css_colors(), 100))
    pprint(sample_colors)

这产生了与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))

Janus的回答,但更容易读懂。我还稍微调整了配色方案,并在你可以自己修改的地方做了标记

我已经把这个片段直接粘贴到一个jupyter笔记本。

import colorsys
import itertools
from fractions import Fraction
from IPython.display import HTML as html_print

def infinite_hues():
    yield Fraction(0)
    for k in itertools.count():
        i = 2**k # zenos_dichotomy
        for j in range(1,i,2):
            yield Fraction(j,i)

def hue_to_hsvs(h: Fraction):
    # tweak values to adjust scheme
    for s in [Fraction(6,10)]:
        for v in [Fraction(6,10), Fraction(9,10)]: 
            yield (h, s, v) 

def rgb_to_css(rgb) -> str:
    uint8tuple = map(lambda y: int(y*255), rgb)
    return "rgb({},{},{})".format(*uint8tuple)

def css_to_html(css):
    return f"<text style=background-color:{css}>&nbsp;&nbsp;&nbsp;&nbsp;</text>"

def show_colors(n=33):
    hues = infinite_hues()
    hsvs = itertools.chain.from_iterable(hue_to_hsvs(hue) for hue in hues)
    rgbs = (colorsys.hsv_to_rgb(*hsv) for hsv in hsvs)
    csss = (rgb_to_css(rgb) for rgb in rgbs)
    htmls = (css_to_html(css) for css in csss)

    myhtmls = itertools.islice(htmls, n)
    display(html_print("".join(myhtmls)))

show_colors()