Matplotlib 创建一个 Cityscapes_Pallette_Map

Matplotlib create a Cityscapes_Pallette_Map

我想为我的语义分割输出创建一个 Cityscapes_Palette_Map 作为“颜色图”。

每个像素值的颜色定义范围从0到22如link.

我看到很多创建“连续”cmap 的示例,但我需要的是“离散”cmap 以将 int 像素值 (class) 映射到特定颜色。我想知道是否有人可以指出我正确的参考来解决我的问题。非常感谢。

欢迎来到 SO。

Matplotlib 仍然doesn't have an easy way to map integers to colors。 通常,最直接的方法是简单地在 matplotlib 外部应用映射,然后将颜色值传递给 matplotlib。

import numpy as np
import matplotlib.pyplot as plt

n = 10
x = np.random.rand(n)
y = np.random.rand(n)
color_as_integer = np.random.randint(3, size=n)

colormap = {
    0  : np.array([  0,   0,   0, 255]),     # unlabelled
    1  : np.array([ 70,  70,  70, 255]),     # building
    2  : np.array([100,  40,  40, 255]),     # fence
}

# matplotlib works with rbga values in the range 0-1
colormap = {k : v / 255. for k, v in colormap.items()}

color_as_rgb = np.array([colormap[ii] for ii in color_as_integer])

plt.scatter(x, y, s=100, c=color_as_rgb)
plt.show()

然后您可以使用代理艺术家来创建图例 here

另一种方法是结合使用 ListedColormap 和 BoundaryNorm 将整数映射到颜色,如 answer 中所述。

在这种情况下,您还可以获得概述的颜色条 here(尽管在您的情况下制作适当的图例可能更好)。