Search code examples
dictionarymatchingpalette

Take fullcolor image and constrain it to dictionary of colors


I'm using Python, and've got a dictionary like this.

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

How do I take an RGB tuple and match it to the closest tuple in the dictionary?

Should I loop through for each element in the source and find the closest match? This seems rather inefficient.


Solution

  • I did this:

    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()))
    

    Cobbled together out of chunks of code from StackOverflow.