【发布时间】:2019-03-06 23:34:20
【问题描述】:
如何根据第 4 通道中的值设置 4 通道 numpy 数组的前 3 个通道中的值?是否可以使用 numpy 切片作为左值来做到这一点?
给定一个具有 4 个通道的 3 x 2 像素 numpy 数组
a = np.arange(24).reshape(3,2,4)
array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7]],
[[ 8, 9, 10, 11],
[12, 13, 14, 15]],
[[16, 17, 18, 19],
[20, 21, 22, 23]]])
我可以选择第 4 通道为模 3 的切片。
px = np.where(0==a[:,:,3]%3)
(array([0, 1], dtype=int64), array([0, 1], dtype=int64))
a[px]
array([[ 0, 1, 2, 3],
[12, 13, 14, 15]])
现在我想将 a 中这些行中的前 3 个通道设置为 0,以便结果如下所示:
a
array([[[ 0, 0, 0, 3],
[ 4, 5, 6, 7]],
[[ 8, 9, 10, 11],
[ 0, 0, 0, 15]],
[[16, 17, 18, 19],
[20, 21, 22, 23]]])
我试过了
a[px][:,0:3] = 0
但这会使数组保持不变。
我阅读了Setting values in a numpy arrays indexed by a slice and two boolean arrays,但不明白如何使用布尔索引仅设置前 3 个频道。
【问题讨论】: