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


I have an array of 2d masks that looks something like this:


And I want to merge the masks one after another, where every mask overrides the mask before it, (I don’t want the sum of all masks).
By override, I mean that if the value of the second mask wasn’t 0, it will set the new value, otherwise keep what it was from the previous masks.
So for this example, the result will be


Of course, In my case I don’t have only 2 masks 2×2, I have multiple masks in a larger scale, this was just to demonstrate.

The masks represent circles in some grayscale value and I want to paste them one on top of another.
Like this:


How can I achieve this using NumPy with a clean and efficient code?
And if there is a different way to approach this I’d love to hear it too.


If you have a 3D array of masks arranged along the first axis, you can reduce along the first axis and merge your masks with np.where:

In [2]: import functools

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

Answered By – ddejohn

Answer Checked By – Marie Seifert (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *