如何将M x N灰度图像,或者换句话说矩阵或2-D数组转换为RGB热图,或者换句话说是M x N x 3数组?
示例:
[[0.9, 0.3], [0.2, 0.1]]
应该成为
[[red, green-blue], [green-blue, blue]]
其中红色为[1, 0, 0]
,蓝色为[0, 0, 1]
等。
答案 0 :(得分:14)
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)
cmap
是matplotlib的LinearSegmentedColormap
类的实例,它派生自Colormap
类。它起作用的原因是__call__
中定义的Colormap
函数。这是来自matplotlib的git repo的文档字符串供参考,因为它没有在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.
"""
更简单的选项是使用img
或plt.imshow
显示plt.matshow
,然后将结果复制或保存为RGB或RGBA图像。这对我的应用来说太慢了(在我的机器上慢了~30倍)。