我拍了一张我想用matplotlib的色标的截图。我可以从这张图片生成matplotlib色彩映射对象的好/简单方法是什么?
编辑:这是我的尝试:
from PIL import Image
import matplotlib
from matplotlib import pyplot as plt
import numpy as np
img = Image.open('pet_colourbar.png')
data = img.load()
# Loop through pixels and extract rgb value
rgb_colours = []
for i in range(img.size[1]):
rgb = [x/255 for x in data[0, i]] # scale values 0-1
rgb_colours.append(rgb)
pet_cmap = matplotlib.colors.ListedColormap(rgb_colours[::-1]) # reverse order
# Plot example gradient
gradient = np.linspace(0, 1, 256)
gradient = np.vstack((gradient, gradient))
plt.imshow(gradient, aspect='auto', cmap=pet_cmap)
答案 0 :(得分:1)
您可以尝试这样的事情:LinearSegmentedColormap
允许从颜色列表中创建颜色映射。因此,您已将img转换为此类列表:
from matplotlib.image import imread
from matplotlib.colors import LinearSegmentedColormap
img = imread('/path/to/img')
# img is 30 x 280 but we need just one col
colors_from_img = img[:, 0, :]
# commonly cmpas have 256 entries, but since img is 280 px => N=280
my_cmap = LinearSegmentedColormap.from_list('my_cmap', colors_from_img, N=280)
然后像往常一样使用新创建的cmap:
y = random_sample((100, 100))
imshow(y, cmap=my_cmap)