如何將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]
等。
如何將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倍)。
+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