How to extract rgb values of this colorbar image in python?

Question:

Image

I want to make a colormap used in the attached image colorbar. So far I tried the code given below but didn’t get the result I was looking for.

import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
import numpy as np

img = plt.imread('Climat.png')
colors_from_img = img[:, 0, :]
my_cmap = LinearSegmentedColormap.from_list('my_cmap', colors_from_img, N=651)
y = random_sample((100, 100))
imshow(y, cmap=my_cmap);plt.colorbar()

Looking for your suggestions. Thank you in advance.

Asked By: shewag

||

Answers:

bicarlsen has given you the correct direction. Restrict the points from which you extract the colors to the colored rectangles:

import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
import numpy as np

img = plt.imread('Climat.png')
colors_from_img = img[80::88, 30, :]
my_cmap = LinearSegmentedColormap.from_list('my_cmap', colors_from_img[::-1], N=len(colors_from_img))
y = np.random.random_sample((100, 100))
plt.imshow(y, cmap=my_cmap)
plt.colorbar()
plt.show()

Sample output:

enter image description here

P.S.: Initially, I thought a more general approach with

colors_from_img = np.unique(img[:, 30, :], axis=0)

was possible but as the input image is rasterized, all kinds of mixed colors are present where the black lines separate colored rectangles.

Answered By: Mr. T
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.