如何基于第4通道中的值设置4通道numpy数组的前3个通道中的值?是否可以将numpy slice用作l值?
给出具有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个通道。
答案 0 :(得分:1)
这是一种方法:
>>> px0, px1 = np.where(0==a[:,:,3]%3)
>>> a[px0, px1, :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]]])
或
>>> px = np.where(0==a[:,:,3]%3)
>>> a[..., :3][px] = 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, np.s_[: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]]])