我希望使用掩码在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 的像素?请注意,我想一次将三个值写入每个像素(最后一个维度)。
(100,200)
)是关键。一旦我这样做了,我甚至不需要mask,:
部分;只需要img[mask] = color
就可以了。我猜numpy索引工作中有更多的魔法。 - GaryO