Reputation: 99
Is there an efficient way of applying color map dictionary to grayscale image to convert to RGB image using numpy functions?
For eg. I have a a grayscale image as numpy array .
grayscale_image = array([[0., 0., 3.],
[0., 2., 0.]])
and a color map like
color_map = {3: (1,2,3), 2: (4,5,6)}
How can I generate RGB image like
rgb_image =
array([[[0., 0., 0.],
[0., 0., 0.],
[1., 2., 3.]],
[[0., 0., 0.],
[4., 5., 6.],
[0., 0., 0.]]])
Upvotes: 2
Views: 1317
Reputation: 92461
You can take advantage of numpy's very convenient indexing if you make your color map an array instead of a dictionary. If you have 256 shades of gray, you will have a color map of shape [256, 3]
. Then you can directly index:
import numpy as np
gray = np.array([
[0, 0, 3],
[0, 2, 0]
])
color_map = np.array([
[0,0,0],
[0,0,0],
[4,5,6],
[1,2,3],
# ... remaining color map values
])
rgb = color_map[gray]
Result:
array([[[0, 0, 0],
[0, 0, 0],
[1, 2, 3]],
[[0, 0, 0],
[4, 5, 6],
[0, 0, 0]]])
Upvotes: 3