在由2d ndarray表示的位置处改变3D ndarray

时间:2017-11-25 07:25:36

标签: python numpy

这是我第一次使用numpy,我在一个地方遇到了麻烦。

所以,我有colors(xsize + 2, ysize + 2, 3) ndarray和newlife(xsize + 2, ysize + 2) nararray of booleans。我想在newlife为真的所有位置为颜色中的所有三个值添加-5到5之间的随机值。换句话说,newlife将2D矢量映射到我是否要在该位置的colors中为颜色添加随机值。

我已经尝试了一百万种变体:

colors[np.nonzero(newlife)] += (np.random.random_sample((xsize + 2,ysize + 2, 3)) * 10 - 5)

但我不断得到像

这样的东西

ValueError: operands could not be broadcast together with shapes (589,3) (130,42,3) (589,3)

我该怎么做?

2 个答案:

答案 0 :(得分:1)

我认为这可以满足您的需求:

# example data
colors = np.random.randint(0, 100, (5,4,3))
newlife = np.random.randint(0, 2, (5,4), bool)

# create values to add, then mask with newlife
to_add = np.random.randint(-5,6, (5,4,3))
to_add[~newlife] = 0

# modify in place
colors += to_add

答案 1 :(得分:0)

这会在假设uint8 dtype的情况下就地更改颜色。这两个假设都不是必要的:

import numpy as np

n_x, n_y = 2, 2
colors = np.random.randint(5, 251, (n_x+2, n_y+2, 3), dtype=np.uint8)
mask = np.random.randint(0, 2, (n_x+2, n_y+2), dtype=bool)

n_change = np.count_nonzero(mask)
print(colors)
print(mask)
colors[mask] += np.random.randint(-5, 6, (n_change, 3), dtype=np.int8).view(np.uint8)
print(colors)

理解这一点的最简单方法是查看colors[mask]的形状。