我想使用蒙版在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的像素?请注意,我想一次向每个像素写入三个值(最后一个暗淡)。
答案 0 :(得分:5)
你几乎是对的。
(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个通道中分配颜色。