Equivalent to Matlab’s ind2rgb in Python

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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, :]


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x