gpt4 book ai didi

python - 将维度高度、宽度、 channel 数的图像转换为n_masks、image_height、image_width

转载 作者:太空宇宙 更新时间:2023-11-04 01:50:39 24 4
gpt4 key购买 nike

我有一个 RGB 图像,它包含不同颜色的蒙版,每种颜色代表一个特定的类别。我想将其转换为格式 - n_masks, image_height, image_width 其中 n_masks 是图像中存在的掩码数。矩阵沿第 0 轴的每个切片代表一个二进制掩码。
到目前为止,我已经能够将它转换为 image_height, image_width 的格式,其中每个数组值代表它属于哪个类,但我有点被它打动了。下面是我将其转换为 image_height,image_width 格式的代码-

def mask_to_class(mask):
target = torch.from_numpy(mask)
h,w = target.shape[0],target.shape[1]
masks = torch.empty(h, w, dtype=torch.long)
colors = torch.unique(target.view(-1,target.size(2)),dim=0).numpy()
target = target.permute(2, 0, 1).contiguous()
mapping = {tuple(c): t for c, t in zip(colors.tolist(), range(len(colors)))}
for k in mapping:
idx = (target==torch.tensor(k, dtype=torch.uint8).unsqueeze(1).unsqueeze(2))
validx = (idx.sum(0) == 3)
masks[validx] = torch.tensor(mapping[k], dtype=torch.long)
return masks

它将假设格式 (512,512,3) 的图像转换为 (512,512),其中每个像素值代表它所属的类,但我不知道如何进一步进行。
P.S- 我在 pytorch 中对其进行编码,但也欢迎任何涉及 numpy 的方法。

最佳答案

假设您已经有了 (512,512) 掩码。您可以先使用 mask.unique() 获取所有类的像素值。然后对于每个类值,torch.where(mask==cls_val, torch.tensor(1), torch.tensor(0)) 将返回某个特定类的掩码。最后,您堆叠所有输出。

mask = torch.tensor([[1,2,3],
[2,4,5],
[1,2,3]])
cls = mask.unique()
res = torch.stack([torch.where(mask==cls_val, torch.tensor(1), torch.tensor(0)) for cls_val in cls])

#tensor([[[1, 0, 0],
# [0, 0, 0],
# [1, 0, 0]],
#
# [[0, 1, 0],
# [1, 0, 0],
# [0, 1, 0]],
#
# [[0, 0, 1],
# [0, 0, 0],
# [0, 0, 1]],
#
# [[0, 0, 0],
# [0, 1, 0],
# [0, 0, 0]],
#
# [[0, 0, 0],
# [0, 0, 1],
# [0, 0, 0]]])

关于python - 将维度高度、宽度、 channel 数的图像转换为n_masks、image_height、image_width,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58121654/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com