[英]Set masked pixels in a 3D RGB numpy array
I'd like to set all pixels matching some condition in a 3d numpy array (RGB image) using a mask. 我想使用蒙版在3d numpy数组(RGB图像)中设置匹配某些条件的所有像素。 I have something like this:
我有这样的事情:
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)
but that gives ValueError: array is not broadcastable to correct shape
in this line: 但是这会给出
ValueError: array is not broadcastable to correct shape
在这一行中ValueError: array is not broadcastable to correct shape
:
img[mask] = color
because the shape of img[mask] is (1961,); 因为img [mask]的形状是(1961,); ie it's flattened to contain only the "valid" pixels, which makes sense;
即它被展平为仅包含“有效”像素,这是有道理的; but how can I make it "write through the mask" as it were to set only the pixels where the mask is 1?
但是我怎么能让它“通过掩码写入”,因为它只设置掩码为1的像素? Note that I want to write three values at once to each pixel (the last dim).
请注意,我想一次向每个像素写入三个值(最后一个暗淡)。
You almost have it right. 你几乎把它做对了。
(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
the extra ",:" at the end of the assignment lets you assign the color throughout the 3 channels in one shot. 分配结尾处的额外“,:”可让您在一次拍摄中分配3个通道的颜色。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.