使用matplotlib将灰度图像转换为RGB热图像
问题描述:
如何将M×N灰度图像或换句话说是矩阵或2-D数组转换为RGB热图,或换句话说,将M x N x 3阵列?使用matplotlib将灰度图像转换为RGB热图像
实施例:
[[0.9, 0.3], [0.2, 0.1]]
应该成为
[[red, green-blue], [green-blue, blue]]
其中红色是[1, 0, 0]
,蓝色是[0, 0, 1]
等。
答
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
类派生的一个实例。由于Colormap
中定义的__call__
函数,它的工作原理。这里是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倍)。
+0
+1。使用描述的方法(而不是imshow),您可以保证获取具有相同尺寸的图像。如果你想要一个不同大小的图像,那么你可以从imshow中获得它(需要一些调整),因为它已经为你插入了图像。 – heltonbiker 2013-03-14 20:45:27
另请参阅:http://stackoverflow.com/questions/14869321/is-there-a-way-to-convert-pyplot-imshow-object-to-numpy-array/14877059#14877059。记住要让你自己接受答案。 – tacaswell 2013-03-15 03:32:27
我同意,这与问题类似,尽管这更加清楚。 (我搜索了一段时间,找不到这个问题。)我很新的stackoverflow;我们合并还是什么? – rd11 2013-03-15 12:41:46
不要担心,你需要不采取任何行动。我已经将其标记为可能的重复,如果其他4人与3k +代表同意这将关闭作为一个副本(这只是意味着没有新的答案,并永久链接到另一个问题)。如果其他人不同意,评论将保留,但我的近距离投票将会消失。我同意你在识别真正的问题方面做得更好(根据关于使用'imshow'的回答中的评论)。 – tacaswell 2013-03-15 14:44:40