通过我们上面的对话,您有一个 2D NumPy 整数 ID 数组,其中该数组中的每个元素确定所述像素的类 ID,从而为您提供语义分割输出。
我建议您分三个阶段进行。
-
创建一个大小为N x 4 的RGB 颜色图,其中N 是分割中的输出类总数。因此,每个类 i 都被分配了一个 RGBA 颜色像素值,您将使用它来为输出着色。
-
展平输入整数 NumPy 数组,使其成为一维 NumPy 数组,我们可以使用它来索引 (1)
-
最后索引到 (1) 中的 RGB 颜色映射。这将创建一个(R x C) x 4 2D NumPy 数组,其中包含将语义标签映射到颜色的输出彩色图像。当然,我们需要将其恢复为原始输入尺寸,因此重新调整此数组,使其变为 R x C x 4 供您显示。最后,因为我们现在有一个图像的 Alpha 通道,所以您可以将其显示在原始图像之上。
步骤 #1 - 生成颜色图
matplotlib 有一套不错的工具可以为您生成此颜色图。您可以从此使用cm 模块。首先,决定你想为你的目的使用什么颜色图。可以在此处找到它们的完整列表:https://matplotlib.org/3.1.1/tutorials/colors/colormaps.html。我会选择 Viridis,因为这是 matplotlib 中当前使用的默认设置。
假设你系统中的类总数为N,首先生成颜色图,然后用N元素创建一个从0到1的线性间隔数组,从头到尾均匀地创建颜色这张彩色地图的结尾。另请注意,这将生成一个N x 4 颜色映射,最后一列是 Alpha 通道。这对以后非常重要。具体来说,此方法会将标签为 0 的任何像素着色为属于颜色图的下端,因为这是语义分割输出,标签 0 应对应于背景,因此我们应将此标签的 alpha 通道设置为 0要透明。我们可以将其余颜色设置为您想要的 alpha,在您的代码中为 0.3。
from matplotlib import cm
import numpy as np
N = ... # You define this here
colours = cm.get_cmap('viridis', N) # Change the string from 'viridis' to whatever you want from the above link
cmap = colours(np.linspace(0, 1, N)) # Obtain RGB colour map
cmap[0,-1] = 0 # Set alpha for label 0 to be 0
cmap[1:,-1] = 0.3 # Set the other alphas for the labels to be 0.3
第 2 步 - 获取语义分割输出并找到合适的颜色
这是直截了当的。假设fused_mosaic 是我们之前讨论过的二维整数数组,将这个数组展平并索引您的颜色图:
output = cmap[fused_mosaic.flatten()]
步骤 #3 - 重塑为所需的输出
这又是直截了当的:
R, C = fused_mosaic.shape[:2]
output = output.reshape((R, C, -1))
output 现在将包含语义分割图中每个对象的 RGBA 渲染图像。然后,您最终可以使用它并将其显示在图像顶部。使用您的代码,这将是:
fig, ax = image_show(full_im) # Don't know what this does but it's from your code
ax.imshow(output)
为了将所有内容联系在一起,这就是我最终要做的:
## Step #1
from matplotlib import cm
import numpy as np
N = ... # You define this here
colours = cm.get_cmap('viridis', N) # Change the string from 'viridis' to whatever you want from the above link
cmap = colours(np.linspace(0, 1, N)) # Obtain RGB colour map
cmap[0,-1] = 0 # Set alpha for label 0 to be 0
cmap[1:,-1] = 0.3 # Set the other alphas for the labels to be 0.3
## Step #2
output = cmap[fused_mosaic.flatten()]
## Step #3
R, C = fused_mosaic.shape[:2]
output = output.reshape((R, C, -1))
## Overlay
fig, ax = image_show(full_im) # Don't know what this does but it's from your code
ax.imshow(output)