gpt4 book ai didi

python - 在 3D RGB numpy 数组中设置蒙版像素

转载 作者:太空狗 更新时间:2023-10-30 02:46:32 25 4
gpt4 key购买 nike

我想使用蒙版设置 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]的shape是(1961,);也就是说,它被展平为仅包含“有效”像素,这是有道理的;但是我怎样才能让它“通过掩码写入”,因为它只设置掩码为 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 个 channel 的颜色。

关于python - 在 3D RGB numpy 数组中设置蒙版像素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20081442/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com