Search code examples
pythoniteratorconcatenationmask

Concatenating unknown number of masks


I have an array of boolean values of shape (height, width, num_of_instances) (for example (2448, 2048, 233)). I'd like to return a array of shape (height, width, 1), where every value is True if any of the values in the 233 masks at the same position is True. I don't always know the number of instances and height and width. Currently I am iterating over every pixel:

for j in masks.shape[0]:
   for i in masks.shape[1]:
      if any(masks[j, i, :):
          resulting_mask[j, i] = True

This is extremly slow as one would expect. So what would be quick and pythonic way of doing this?


Solution

  • Have you tried this ?

    resulting_mask = np.any(masks,axis=2)[:,:,None]