Home > Software design >  Equivalent to Matlab's ind2rgb in Python
Equivalent to Matlab's ind2rgb in Python

Time:04-30

In Matlab, there is a function ind2rgb function that can be used like this:

y = ind2rgb(im2uint8(rescale(cfs)),jet(256));

From the Matlab website:

RGB = ind2rgb(X,map) converts the indexed image X and corresponding colormap map to RGB (truecolor) format.

Is there an equivalent method in Python?

CodePudding user response:

I don't know about an inbuilt equivalent but you can easily do this using numpy arrays:

import numpy as np

# Create a 5x5 array of indices for demo
img = np.random.randint(0, 10, (5, 5)) 

# Create a fake grayscale colormap for demo
cmap = np.vstack((np.linspace(0, 1, n), np.linspace(0, 1, n), np.linspace(0, 1, n))).T  

Now, the ith row of cmap gives you the color, and every element of img tells you which index in cmap is the color for that pixel so you just need to take the ith row for each element i in img. Because numpy's indexing works with broadcasting, you can give the entire img array as the row indexer, and you'll get an array of shape (img_rows, img_cols, cmap_cols)

rgb_img = cmap[img, :]
print(rgb_img.shape) # (5, 5, 3)

In other words, ind2rgb(img, cmap) is equivalent to cmap[img, :]

  • Related