0

我正在使用 Python,并且有这样的字典。

COLORTABLE = {
0: (0, 0, 0),
1: (109, 111, 113),
2: (7, 145, 205),
3: (105, 156, 65),
4: (244, 126, 32),
5: (214, 22, 59),
6: (110, 26, 17),
7: (248, 222, 215),
8: (255, 255, 255),
9: (209, 211, 212),
10: (115, 207, 242),
11: (155, 204, 102),
12: (255, 236, 0),
13: (214, 128, 170),
14: (129, 36, 104),
15: (142, 104, 76),
}

如何获取 RGB 元组并将其与字典中最接近的元组匹配?

我应该遍历源中的每个元素并找到最接近的匹配吗?这似乎相当低效。

4

1 回答 1

0

我这样做了:

HEXATABLE = {}
for key, value in COLORTABLE.items():
    HEXATABLE[key] = rgb2hex(value)

def rgb2hex(rgb):
    return (rgb[0] << 16) + (rgb[1] << 8) + rgb[2];

def hex2rgb(hexcolor):
    r = ( hexcolor >> 16 ) & 0xFF;

    g = ( hexcolor >> 8 ) & 0xFF;

    b = hexcolor & 0xFF;

    return r, g, b

def takeClosest(num,collection):
   return min(collection,key=lambda x:abs(x-num))


for x in range(img.get_width()):
    for y in range(img.get_height()):
        color = rgb2hex(tuple(img.get_at((x, y))))
        newcolor = hex2rgb(takeClosest(color, HEXATABLE.values()))

由 StackOverflow 的代码块拼凑而成。

于 2013-07-17T03:05:37.213 回答