使用matplotlib将灰度图像转换为RGB热图图像

rd1*_*d11 5 python matplotlib

如何将M x N灰度图像(或者换句话说矩阵或2-D阵列)转换为RGB热图,或者换句话说是M x N x 3阵列?

例:

 [[0.9, 0.3], [0.2, 0.1]] 
Run Code Online (Sandbox Code Playgroud)

应该成为

[[red, green-blue], [green-blue, blue]] 
Run Code Online (Sandbox Code Playgroud)

红色是[1, 0, 0],蓝色是[0, 0, 1]等等.

rd1*_*d11 15

import matplotlib.pyplot as plt

img = [[0.9, 0.3], [0.2, 0.1]]

cmap = plt.get_cmap('jet')

rgba_img = cmap(img)
rgb_img = np.delete(rgba_img, 3, 2)
Run Code Online (Sandbox Code Playgroud)

cmap是matplotlib LinearSegmentedColormap类的一个实例,它是从Colormap类派生的.它的工作原理是因为__call__定义了函数Colormap.这是来自matplotlib的git repo的docstring供参考,因为它没有在API中描述.

def __call__(self, X, alpha=None, bytes=False):
    """
    *X* is either a scalar or an array (of any dimension).
    If scalar, a tuple of rgba values is returned, otherwise
    an array with the new shape = oldshape+(4,). If the X-values
    are integers, then they are used as indices into the array.
    If they are floating point, then they must be in the
    interval (0.0, 1.0).
    Alpha must be a scalar between 0 and 1, or None.
    If bytes is False, the rgba values will be floats on a
    0-1 scale; if True, they will be uint8, 0-255.
    """
Run Code Online (Sandbox Code Playgroud)

更简单的选项是显示img,使用plt.imshowplt.matshow,然后将结果复制或保存为RGB或RGBA图像.这对我的应用来说太慢了(在我的机器上慢了~30倍).