【问题标题】:Select value based on dimension in 3D numpy array根据 3D numpy 数组中的维度选择值
【发布时间】:2020-05-03 14:41:25
【问题描述】:

我有多个二进制分割掩码。将它们组合起来形成一个 3D 阵列。如果将第 3 维中的一个像素相加,它的总和应为 1,即一个像素在其第 3 维中应该只有一个 1

[[0, 0],
 [1, 0]],

[[1, 1],
 [0, 1]]

不幸的是,我的 3D 数组没有给出这个条件:

[[0, 0],
 [1, 1]],

[[1, 0],
 [1, 0]],

[[1, 1],
 [1, 0]]

正如所见,2,1 的值在所有三个通道中都相等。

如果在较高通道中存在1,我想将较低通道中的值设置为0。 我怎样才能实现第二个示例中的数组结果:

[[0, 0],
 [0, 1]],

[[0, 0],
 [0, 0]],

[[1, 1],
 [1, 0]]

【问题讨论】:

  • 你最后一个代码块的倒数第二行不是错了吗?它的[1, 1]

标签: python arrays numpy multidimensional-array


【解决方案1】:

使用Numpy's advanced indexing 相当容易:

import numpy as np

img = np.array([[[0, 0],
                 [1, 1]],
                [[1, 0],
                 [1, 0]],
                [[1, 1],
                 [1, 0]]])

print(img)

print(np.sum(img, axis=2))

# check for ones in the first position in the third axis  
# and get a mask for boolean indexing  
mask = img[:, :, 0] == 1

print(mask)
img_2 = img.copy()

# apply the mask to the second element in the third axis
# and set the values to zero there IF there was a one
# in the other place: when the boolean mask is True
img_2[:,:,1][mask] = 0 

print(img_2)

print(np.sum(img_2, axis=2))

【讨论】:

    猜你喜欢
    • 2014-02-20
    • 2022-11-26
    • 2014-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-08
    • 2015-11-15
    • 1970-01-01
    相关资源
    最近更新 更多