Grayscale Translation of Rainbow Color Maps in Python

Asked 2 years ago, Updated 2 years ago, 171 views

Is there a way to read the jpeg image saved in Rainbow color map in Python and grayscale it according to the color map?
I would like RGB values in a color map, usually expressed in 256 colors, to match numbers from 0 to 255 according to the order of the map, but if I grayscale it normally, the maximum value will arrive near the center of the color map (https://matplotlib.org/users/colormaps.html.

I have found a method using MATLAB (https://stackoverflow.com/questions/7440340/jet-colormap-to-grayscale), but I am not familiar with MATLAB, so if you have someone who is bright on both sides, please let me know how to do the same with Python.
It would be great if Python's module had the same function (?) linked rgb2ind.

If you have any other thoughts, please let me know.

python matplotlib matlab

2022-09-30 18:57

1 Answers

Based on the recommendations in the comments, we will summarize the contents of the article below (not as it is).
How I can specify how rainbow color scheme should be converted to grayscale
Comments related to the question image of the original article are summarized separately.

Copy code from original article response (but transcript not verified)

import numpy as np
import matplotlib.colors
import matplotlib.pyplot asplt

image=plt.imread("data/jetcolimage.png")
print image.shape, image.max()

r=np.linspace(0,1,256)
norm = matplotlib.colors.Normalize(0,1)
cmap=plt.cm.jet
mapvals=cmap(normal(r))[:,:3]

default_value_from_cm(color):
    color=matplotlib.colors.to_rgb(color)
    # if color is already gray scale, don't change it
    if np.std(color)<0.1:
        return np.mean (color)
    #otherwise return value from colormap
    distance=np.sum(mapvals-color)**2,axis=1)
    return [np.argmin(distance)]

newim=np.zeros_like(image)
for i in range (image.shape[0]):
    for jin range(image.shape[1]):
        c=image[i,j,:3]
        newim[i,j] = get_value_from_cm(c)


config,(ax,ax2) = plt.subplots(ncols=2)
ax.imshow(image)
ax2.imshow(newim,cmap="gray")

ax.axis("off")
ax2.axis("off")
plt.show()

In the article below, it seems that "How to change (image) from one color map to another" involves converting values that do not belong to the grayscale or color map to the nearest value.
How can I change colors in contents (obtained from non-Python) with Python?


2022-09-30 18:57

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.