【问题标题】:Set masked pixels in a 3D RGB numpy array在 3D RGB numpy 数组中设置蒙版像素
【发布时间】:2013-11-19 20:32:26
【问题描述】:

我想使用掩码在 3d numpy 数组(RGB 图像)中设置与某些条件匹配的所有像素。我有这样的事情:

def make_dot(img, color, radius):
    """Make a dot of given color in the center of img (rgb numpy array)"""
    (ydim,xdim,dummy) = img.shape
    # make an open grid of x,y
    y,x = np.ogrid[0:ydim, 0:xdim, ]
    y -= ydim/2                 # centered at the origin
    x -= xdim/2
    # now make a mask
    mask = x**2+y**2 <= radius**2 # start with 2d
    mask.shape = mask.shape + (1,) # make it 3d
    print img[mask].shape
    img[mask] = color

img = np.zeros((100, 200, 3))
make_dot(img, np.array((.1, .2, .3)), 25)

但这在这一行中给出了ValueError: array is not broadcastable to correct shape

img[mask] = color

因为 img[mask] 的形状是 (1961,);即它被展平以仅包含“有效”像素,这是有道理的;但是我怎样才能让它“通过掩码写入”,因为它只设置掩码为 1 的像素?请注意,我想一次将三个值写入每个像素(最后一个暗淡)。

【问题讨论】:

    标签: python arrays numpy


    【解决方案1】:

    你几乎说对了。

    (ydim,xdim,dummy) = img.shape
    # make an open grid of x,y
    y,x = np.ogrid[0:ydim, 0:xdim, ]
    y -= ydim/2                 # centered at the origin
    x -= xdim/2
    # now make a mask
    mask = x**2+y**2 <= radius**2 # start with 2d
    img[mask,:] = color
    

    分配末尾的额外“,:”可让您一次性分配整个 3 个通道的颜色。

    【讨论】:

    • 完美,谢谢!仅对于未来的读者,将掩码保留为 2d(在本例中为 (100,200))是关键。一旦我这样做了,我什至不需要mask,: 部分;只是img[mask] = color 工作正常。我猜,numpy 索引的工作原理不仅仅是一点魔法。
    • 顺便说一句,我刚刚更新了 numpy 数组索引文档,以澄清什么让我感到困惑。
    猜你喜欢
    • 2020-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多