在二维阵列表示的位置更改三维阵列

2024-10-01 11:38:23 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我有colors,一个(xsize + 2, ysize + 2, 3)数组,还有newlife,一个(xsize + 2, ysize + 2)布尔数组。我想在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)

我该怎么做?你知道吗


Tags: sample方法numpy颜色地方nprandom数组
2条回答

我想这正是你想要的:

# 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

这将更改uint8dtype的颜色。这两种假设并不重要:

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]的形状。你知道吗

相关问题 更多 >