Python PIL-查找最近的颜色(四舍五入的颜色) [英] Python PIL - Finding Nearest Color (Rounding Colors)

查看:251
本文介绍了Python PIL-查找最近的颜色(四舍五入的颜色)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个名为Roblox的游戏,玩家在其中进行游戏,通常使用看起来像乐高玩具的积木.

There is a game called Roblox, in which the player makes the game, usually of lego-looking bricks.

在Roblox中,对于Brick颜色,您可以使用典型的RGB值,但是这需要一个额外的元素,当涉及到文件大小时,该元素不是很有效.代替使用RGB值,BrickColor的文件大小更经济.它使用整数来解释为某种颜色. 这是我的意思:

In Roblox, for the Brick colors, you can use typical RGB values, but that'd require an additional element that is not very efficient when it comes to file size. Instead of using RGB values, BrickColor is much more economic in file size. It uses an integer to be interpreted as a certain color. Here is what I mean:

这是我的代码段:

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值的颜色代码.

In my program, I need to find the color code closest to an RGB value.

这将如何完成?

推荐答案

在表格中创建颜色列表(我称之为颜色). 按到您要询问的r,g,b点的距离对列表进行排序 列表中的第一个元素是最接近的颜色

Create a list of colors in your table (I call it colors). Sort the list by the distance to the r, g, b point you are questioning The first element in the list is the closest color

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]

这篇关于Python PIL-查找最近的颜色(四舍五入的颜色)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆