【问题标题】:Problem applying binary mask to an RGB image with numpy使用 numpy 将二进制掩码应用于 RGB 图像的问题
【发布时间】:2019-10-18 14:41:57
【问题描述】:

我正在尝试使用 numpy 将二进制掩码应用于 RGB 图像

我找到了这个https://stackoverflow.com/a/26843467/4628384,但我还没有写评论的权限。 无论如何,我遇到了问题;非常感谢任何帮助。

def masktoRGB(self,image,image_mask):

        # create mask with same dimensions as image
        mask = np.zeros_like(image)
        # copy your image_mask to all dimensions (i.e. colors) of your image
        for i in range(3):
            mask[:,:,i] = image_mask.copy()

        # apply the mask to your image

        # tried to swap axes, not a solution 
        #image = image.swapaxes(0,1)
        #this gives the error:
        masked_image = image[mask]

        print(mask.shape)
        print(image.shape)
        print(image_mask.shape)



        return masked_image

这给了我:

IndexError:索引 213 超出轴 0 的范围,大小为 212

打印输出:

(188, 212, 3) (188, 212, 3) (188, 212)

image和image_mask是同一张图片,只不过第一个是RGB,第二个是mode L

【问题讨论】:

    标签: python-3.x numpy python-imaging-library


    【解决方案1】:

    尝试使用广播和乘法:

    image * image_mask[..., None]
    

    我假设 image_mask 的类型是映射到数字 0 和 1 的 bool。因此 image 和 mask 的成对相乘会将掩码值设置为零。

    使用 np.where() 或 & 运算符可以实现类似的效果。

    问题是 image 和 image_mask 的形状不兼容。 Numpy 将首先在形状的头部添加额外的维度,直到两个张量具有相同的形状。因此 image_mask 从 (188, 212) 重塑为 (1,188, 212)。这个新形状与图像的形状不兼容 (188, 212, 3)。

    诀窍是使用花哨的索引来重塑 image_mask。您可以使用 None 作为索引在形状末尾添加大小为 1 的虚拟维度。操作 image_mask[..., None] 会将其从 (188, 212) 重塑为 (188, 212,1)。

    广播规则告诉大小为 1 的维度通过沿广播维度重复所有值来扩展。因此 numoy 会自动将 tensir 从 (188, 212,1) 重塑为 (188, 212,3)。操作非常快,因为没有创建副本。

    现在可以将位张量相乘以产生所需的结果。

    【讨论】:

    • 您的答案在技术上可能是正确的,但可以通过更清楚地显示它适合的上下文来改进它以使其更有用。
    猜你喜欢
    • 1970-01-01
    • 2018-07-21
    • 2020-04-13
    • 2015-10-11
    • 1970-01-01
    • 1970-01-01
    • 2017-04-10
    • 2021-11-28
    • 1970-01-01
    相关资源
    最近更新 更多