I have a dictionary that classifies each RGB value into one specific color (e.g., red, orange, yellow). What would be the most efficiently way to transform an RGB image (numpy array) based on the dictionary?
The dictionary is structured like this:
d = {(0, 0, 0): (0, 0, 0),
(1, 0, 0): (0, 0, 0),
(2, 0, 0): (0, 0, 0),
(3, 0, 0): (0, 0, 0),
(4, 0, 0): (128, 102, 64),
(5, 0, 0): (255, 0, 0),
(6, 0, 0): (255, 0, 0),
(7, 0, 0): (255, 0, 0),
(8, 0, 0): (255, 0, 0),
(9, 0, 0): (255, 0, 0),
...
...
...}
I am using for loop but this is very slow. Ideally I would like to use a numpy solution or other quicker approaches.
im = Image.open("image.jpg").convert("RGB")
w, h = im.size
list_of_pixels = list(im.getdata())
new_list_of_pixels = [d[p] for p in list_of_pixels]
new_im = Image.new('RGB', (w,h), "white")
new_im.putdata(new_list_of_pixels)
new_im.save("image_save.jpg") # save the converted image