语义分割中骰子损失中输出掩码和原始掩码之间的维度不匹配

时间:2021-07-14 11:31:11

标签: deep-learning computer-vision pytorch image-segmentation

我正在做多类语义分割(4 个类 + 背景)。我的掩码维度是 (256, 256, 3),输出掩码维度是 (256, 256, 5)。我选了 5,因为这是班级数。

骰子损失函数

inputs = inputs.view(-1)
targets = targets.view(-1)
        
intersection = (inputs * targets).sum() ---> error                       
dice = (2.*intersection + smooth)/(inputs.sum() + targets.sum() + smooth)  
        
return 1 - dice

我该怎么做才能使两个维度相同?掩码是从 TIF 文件中提取的。

我在下面附上了我的面具图片。 My mask image

2 个答案:

答案 0 :(得分:0)

我相信你必须先对目标掩码进行单热编码。 我建议您先阅读这篇好文章,以便更好地掌握语义分割 https://www.jeremyjordan.me/semantic-segmentation/ 的所有细微之处。

确保预测和目标形状匹配,无需使用 view(-1) 压平张量。

同样作为个人建议,Pytorch 张量优先选择通道。

答案 1 :(得分:0)

我假设您显示的目标分割是一个 RGB 编码的地图。您希望将此 3 通道图像转换为 1 通道标签图。

假设 seg 是形状为 (b, 3, h, w) 的地面实况分割图。标签到颜色映射可以任意设置为:

colors = torch.FloatTensor([[0, 0, 0],
                            [1, 1, 0],
                            [1, 0, 0],
                            [0, 1, 0],
                            [0, 0, 1]])

为每种颜色构建一个匹配像素的掩码,并在这些像素位置的新张量中分配相应的标签:

b, _, h, w = seg.shape
gt = torch.zeros(b,1,h,w)
seg_perm = seg.permute(0,2,3,1)

for label, color in enumerate(colors):
    mask = torch.all(seg_perm == color, dim=-1).unsqueeze(1)
    gt[mask] = label

以下面的分割图为例:

>>> seg = tensor([[[[1., 1., 0., 0.],
                    [1., 0., 0., 0.]],

                   [[0., 1., 0., 0.],
                    [0., 1., 0., 1.]],

                   [[0., 0., 0., 0.],
                    [0., 0., 1., 0.]]]])

用于可视化目的:

>>> T.ToPILImage()(seg[0].repeat_interleave(100,2).repeat_interleave(100,1))

enter image description here

生成的标签图将:

>>> gt
tensor([[[[2., 1., 0., 0.],
          [2., 3., 4., 3.]]]])