如何扩展调色板?

2024-10-01 07:35:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个脚本,将多个直方图组合成一个堆栈图。脚本能够处理任意数量的直方图。我希望能够根据定义的调色板给堆栈图中的直方图上色,并且在不足以给脚本要处理的直方图数量上色时,也能够扩展该调色板。你知道吗

我已经创建了一些函数来处理颜色平均值的获取,并考虑过通过一些自动方式混合颜色来扩展已定义的调色板,然后通过添加这些混合颜色来扩展调色板,但我不确定如何以结构化的、合理的方式来实现这一点。我要求指导和建议如何扩展调色板在一个自动化的方式。你知道吗

style1 = [
    "#FC0000",
    "#FFAE3A",
    "#00AC00",
    "#6665EC",
    "#A9A9A9"
]

def clamp(x): 
    return(max(0, min(x, 255)))

def RGB_to_HEX(RGB_tuple):
    # This function returns a HEX string given an RGB tuple.
    r = RGB_tuple[0]
    g = RGB_tuple[1]
    b = RGB_tuple[2]
    return "#{0:02x}{1:02x}{2:02x}".format(clamp(r), clamp(g), clamp(b))

def HEX_to_RGB(HEX_string):
    # This function returns an RGB tuple given a HEX string.
    HEX = HEX_string.lstrip('#')
    HEX_length = len(HEX)
    return tuple(
        int(HEX[i:i + HEX_length // 3], 16) for i in range(
            0,
            HEX_length,
            HEX_length // 3
        )
    )

def mean_color(colorsInHEX):
    # This function returns a HEX string that represents the mean color of a
    # list of colors represented by HEX strings.
    colorsInRGB = []
    for colorInHEX in colorsInHEX:
        colorsInRGB.append(HEX_to_RGB(colorInHEX))
    sum_r = 0
    sum_g = 0
    sum_b = 0
    for colorInRGB in colorsInRGB:
        sum_r += colorInRGB[0]
        sum_g += colorInRGB[1]
        sum_b += colorInRGB[2]
    mean_r = sum_r / len(colorsInRGB)
    mean_g = sum_g / len(colorsInRGB)
    mean_b = sum_b / len(colorsInRGB)
    return RGB_to_HEX((mean_r, mean_g, mean_b))

def extend_palette(
    colors               = None, # a list of HEX string colors
    numberOfColorsNeeded = None # number of colors to which list should be extended
    )
    # magic happens here
    return colors_extended 

print(
    extend_palette(
        colors = style1,
        10
    )
)

print(
    extend_palette(
        colors = style1,
        50
    )
)

Tags: tostringreturndefrgb直方图meanlength