如何在 python 中将多个 numpy 掩码合并为 1 个单一掩码?

How do I merge multiple numpy masks into 1 single mask in python?

我有一组二维蒙版,看起来像这样:

[
  #mask0
 [[0.3,0.3],
  [0,0]],
  #mask1
  [[0.4,0],
  [0.4,0.4]]
]

而且我想一个接一个地合并掩码,其中每个掩码覆盖它之前的掩码,(我不想要所有掩码的总和)。 通过覆盖,我的意思是如果第二个掩码的值不为 0,它将设置新值,否则保留以前掩码的值。 所以对于这个例子,结果将是

[[0.4,0.3],
  [0.4,0.4]]]

当然,在我的例子中,我并没有只有 2 个 2x2 的面具,我有多个更大比例的面具,这只是为了演示。

蒙版代表一些灰度值的圆圈,我想将它们一个接一个地粘贴。 像这样:

我如何使用 NumPy 和干净高效的代码来实现这一点? 如果有不同的方法来解决这个问题,我也很想听听。

如果您有沿第一个轴排列的 3D 蒙版阵列,您可以沿第一个轴缩小并将蒙版与 np.where:

合并
In [2]: import functools

In [3]: functools.reduce(lambda m0, m1: np.where(m1 == 0, m0, m1), masks)
Out[3]:
array([[0.4, 0.3],
       [0.4, 0.4]])

如果你有多张图片并且你想在每张图片上应用,你可以像下面这样使用 apply_along_axis

from functools import reduce

images = np.random.rand(10, 4, 64, 64) # (n,masksAmount,imgSize,imgSize)
print(images.shape)

def apply_mask(image):
    image = reduce(lambda m0, m1: np.where(m1 == 0, m0, m1), image)
    return image

images = np.apply_along_axis(apply_mask, 1, images) # (n,imgSize,imgSize)
print(images.shape)

输出:

(10, 4, 64, 64) # shape
(10, 64, 64)    # shape

例子

image = np.array([[[0.3, 0.3], [0, 0]], [[0.4, 0], [0.4, 0.4]]])
images = np.repeat(image[None,...],4,0)
print(images.shape)

images = np.apply_along_axis(apply_mask, 1, images)
print(images.shape)
print(images)

输出:

(4, 2, 2, 2) # (n,masksAmount,imgSize,imgSize)

(4, 2, 2)    # (n,imgSize,imgSize)

# images =>
[[[0.4 0.3]
  [0.4 0.4]]

 [[0.4 0.3]
  [0.4 0.4]]

 [[0.4 0.3]
  [0.4 0.4]]

 [[0.4 0.3]
  [0.4 0.4]]]