1

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
kabanus
  • 24,623
  • 6
  • 41
  • 74
lithium
  • 11
  • 1
  • 2
  • How big is the dictionary? Image size? A dictionary can't be used directly with `numpy` because it has to do the key look up one by one. There's no multi-key call. I'd look into converting the dictionary into another structure, at the very least the `items()` list. – hpaulj Aug 19 '19 at 07:06
  • Have a look here... https://stackoverflow.com/a/57204807/2836621 – Mark Setchell Aug 19 '19 at 08:10

0 Answers0