我正在通过 imshow
使用 MxNx4 数组 A
的输入绘制图像,这是一个为矩形 MxN 网格定义的 RGBA 数组。此着色是从 V
生成的,这是一个 MxN 数组,指示这些点中的每一个点的标量值。 IE。我有一个函数 f
,它接受一个标量值并返回一个 RGBA 元组:f(V) = A
我想制作一个颜色条,将 f,V
作为输入。这可能吗?
最佳答案
要创建颜色图,您必须指定红/绿/蓝分量如何在线性范围内变化。看起来您已经有了一个函数 f
,它可以为您设置 r/g/b 分量。困难的部分是第 4 个 channel ,即 alpha channel 。我将在给定由您的 f
指定的 RGB 颜色映射的情况下设置 alpha channel 。
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
# some data
a = np.sort(np.random.randn(10, 10))
# use the default 'jet' colour map for showing the difference later
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.imshow(a, cmap=cm.get_cmap('jet'))
fig.savefig('map1.png')
# let's use jet and modify the alpha channel
# you would use your own colour map specified by f
my_cmap = cm.get_cmap('jet')
# this is a hack to get at the _lut array, which stores RGBA vals
my_cmap._init()
# use some made-up alphas, you would use the ones specified by f
alphas = np.abs(np.linspace(-1.0, 1.0, my_cmap.N))
# overwrite the alpha channel of the jet colour map
my_cmap._lut[:-3,-1] = alphas
# plot data with our modified colour map
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.imshow(a, cmap=my_cmap)
fig.savefig('map2.png')
这是 map1.png
:
这是 map2.png
:
希望这对您有所帮助。
关于python - 从 matplotlib 中的 RGBA 函数创建颜色条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13015070/