Reputation: 25914
I have a single channel image gray_image
, with pixels values [0 .. 255]
and a lookup table mapping those values to colors:
lookup = {
0: [0, 0, 0],
1: [23, 54, 35],
...
255: [200, 52, 20],
}
What is the fastest way to create a new 3 channel image where each pixel is colored based on the lookup of its value in the original images, e.g.
color_image[y, x] = lookup[gray_image[y, x]]
Instead of iterating through every pixel and setting it individually?
Upvotes: 2
Views: 887
Reputation: 15365
palette = np.array([lookup[index] for index in range(256)], dtype=np.uint8)
color_image = palette[gray_image]
the other answer didn't make sure to sort the dictionary by key (python dicts only recently got a stable order of pairs) and it didn't make sure that all index values exist.
Upvotes: 1
Reputation: 13723
Assuming that the keys of the lookup table are properly ordered, you could convert the dictionary into an array and then apply NumPy's advanced indexing like this:
import numpy as np
palette = np.array([row for row in lookup.values()])
color_image = palette[gray_image]
If the keys of your dictionary are not ordered, the code above won't work. In that case you could convert the dictionary into an array as follows:
palette = np.zeros(shape=(256, 3), dtype=np.uint8)
for key in lookup.keys():
palette[key] = lookup[key]
This approach implicitly defines a default value of [0, 0, 0]
, i.e. if the lookup table does not contain a certain index, let's say n
, then those pixels with gray level n
will be mapped to [0, 0, 0]
(black).
Upvotes: 1