如何从色标图像生成 matplotlib 颜色图?
How to generate a matplotlib colormap from from an image of a colour scale?
我截取了我想与 matplotlib 一起使用的色标的屏幕截图。我可以从该图像生成 matplotlib 颜色图对象的 good/easy 方法是什么?
编辑:这是我的尝试:
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)
您可以尝试这样的操作: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)
我截取了我想与 matplotlib 一起使用的色标的屏幕截图。我可以从该图像生成 matplotlib 颜色图对象的 good/easy 方法是什么?
编辑:这是我的尝试:
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)
您可以尝试这样的操作: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)