samquar
samquar

Reputation: 155

Combine mask across all channels

I have some condition tested in all 3 channels of an image, so I have something like:

import numpy as np
check = np.array([[[True, True], [True, False]], [[True, False], [False, False]], [[True, True], [True, True]]])

where dimensions are: channel (RGB), height, width.
I want to get 2D array, that shows that all corresponding pixels of different channels are true, so I want to get

result = np.array([[True, False], [False, False]]) 

Currently, I'm doing it this ways:

result = np.logical_and(check[0, :, :], check[1, :, :], check[2, :, :])

But I'm sure there is a more elegant way to do this

Upvotes: 1

Views: 606

Answers (1)

FBruzzesi
FBruzzesi

Reputation: 6495

You can use numpy.all along the axis of interest:

import numpy as np

check = np.array([[[True, True], 
                   [True, False]], 
                  [[True, False], 
                   [False, False]], 
                  [[True, True], 
                   [True, True]]])

np.all(check, axis=0)
array([[ True, False],
       [False, False]])

Alternatively you can use a list comprehension on check just because you are comparing along the first axis:

np.logical_and(*[c for c in check])
array([[ True, False],
       [False, False]])

Upvotes: 1

Related Questions