Python PIL-查找最近的颜色(舍入颜色)

2024-06-26 00:00:42 发布

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

有一个叫机器人的游戏,玩家在里面做游戏,通常是用乐高积木做的。

在Roblox中,对于砖块颜色,可以使用典型的RGB值,但这需要一个额外的元素,当涉及到文件大小时,该元素的效率不是很高。BrickColor没有使用RGB值,而是在文件大小上更经济。它使用一个整数来解释为某种颜色。Here is what I mean:Color Codes

以下是我的代码片段:

import Image
f = raw_input('Image:\n')
im = Image.open(f)
rgb_im = im.convert('RGB')
r, g, b = rgb_im.getpixel((x, y))

在我的程序中,我需要找到最接近RGB值的颜色代码。

如何才能做到这一点?


Tags: image游戏元素颜色玩家机器人rgb效率
2条回答

扩展mattsap的答案:

我们不需要对所有颜色进行排序,因为我们只需要查找最接近的。i、 我们可以避免计算上昂贵的sort,而是使用min

我们也不需要计算颜色之间的绝对距离,因为我们只对相对距离感兴趣。i、 我们也可以避免毕达哥拉斯的“平方根”部分。

这就提供了:

colours = ( (255, 255, 255, "white"),
            (255, 0, 0, "red"),
            (128, 0, 0, "dark red"),
            (0, 255, 0, "green") )


def nearest_colour( subjects, query ):
    return min( subjects, key = lambda subject: sum( (s - q) ** 2 for s, q in zip( subject, query ) ) )


print( nearest_colour( colours, (64, 0, 0) ) ) # dark red
print( nearest_colour( colours, (0, 192, 0) ) ) # green
print( nearest_colour( colours, (255, 255, 64) ) ) # white

当然,一旦你考虑到不同的颜色空间以及每种颜色成分对人眼感知的贡献,就会有一个完整的兔子洞要钻下去,as per this question,但在大多数情况下,这可能是过度的杀伤力。

在表中创建颜色列表(我称之为颜色)。 按你所询问的r,g,b点的距离来排序 列表中的第一个元素是最接近的颜色

def distance(c1, c2):
    (r1,g1,b1) = c1
    (r2,g2,b2) = c2
    return math.sqrt((r1 - r2)**2 + (g1 - g2) ** 2 + (b1 - b2) **2)

colors = list(rgb_code_dictionary.keys())
closest_colors = sorted(colors, key=lambda color: distance(color, point))
closest_color = closest_colors[0]
code = rgb_code_dictionary[closest_color]

相关问题 更多 >