光谱 (SPy) 标签图例

Spectral (SPy) label legend

我想在 spectral module. I wonder if there is an builtin way to do this? I haven't found anything about making legends in the spectral API 绘制的图像下方添加图例。

这是一个例子

img = np.array([111, 112, 113, 121, 122, 123, 131, 132, 133, 
                211, 212, 213, 221, 222, 223, 231, 232, 233, 
                311, 312, 313, 321, 322, 323, 331, 332, 333]).reshape((3,3,3))
labels = np.array([0, 1, 1, 2, 2, 2, 3, 3, 3]).reshape((3,3))

我可以用 labelsimg 像这样:

from spectral import imshow as spyShow
imageView = spyShow(data=img, bands=(0,1,2), classes=labels, fignum=1, interpolation='none')
imageView.set_display_mode('overlay')

现在我想在图片下方放置一个图例。

labelDictionary={0:'Unknown', 1:'Gravel', 2:'Aslphalt', 3:'Glass'}

从源代码中我看到标签颜色取自:

spectral.spy_colors

进一步用以下代码绘制:

import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap, NoNorm
cm = ListedColormap(np.array(spectral.spy_colors) / 255.)
plt.imshow(a, cmap=cm, vmin = 0, interpolation='none', norm=NoNorm())

我想我可以提取这些颜色并使用自定义函数将它们映射到标签和标签名称。这是制作图例的正确方法,还是有现成的方法,为了不重新发明轮子...

我添加了这样的图例:

from matplotlib import patches
from spectral import spy_colors
labelPatches = [ patches.Patch(color=spy_colors[x]/255.,
                 label=labelDictionary[x]) for x in np.unique(labels) ]

一旦你有了标签补丁,图例就很容易添加了:

plt.legend(handles=labelPatches, ncol=2, fontsize='medium', 
           loc='upper center', bbox_to_anchor=(0.5, -0.05));