I have an image loaded with opencv with img.shape = (208, 117, 3)
. I also have a boolean numpy array with mask.shape = (208, 117)
. How to I make all pixels in the img
(0,0,0)
wherever the mask
has False, otherwise leave the pixels as they are?
Asked
Active
Viewed 1,540 times
1

Alexander Soare
- 2,825
- 3
- 25
- 53
-
Just let broadcasting take care of the shapes and https://stackoverflow.com/questions/38193958/how-to-properly-mask-a-numpy-2d-array – sshashank124 Jan 04 '20 at 17:32
-
Hmm, that didn't solve it for me. That solution has a different sized output. I want the output img to be the same size. Just all pixels where my mask had false should go to zero. – Alexander Soare Jan 04 '20 at 17:41
-
Rough pseudocode: `a[mask] = (0, 0, 0)` is roughly what you want. The mask only gives you access to the relevant pixels, you still need to set them to something – sshashank124 Jan 04 '20 at 17:44
-
@sshashank124 your answers inspired me. See my answer below. Thank you. – Alexander Soare Jan 04 '20 at 17:47
-
The image is a numpy array, right? Have you read the NumPy docs? – AMC Jan 04 '20 at 18:40
-
Not all of them. But yes, I do frequently visit the docs. – Alexander Soare Jan 04 '20 at 19:08
-
in c++ there is an opencv .setTo function which accepts a mask (which you would have to invert first). Maybe that function exists in python, too? – Micka Jan 04 '20 at 23:34
-
1@Micka looks like not, https://stackoverflow.com/questions/41829511/opencv-python-equivalent-of-setto-in-c/41850675 But still I think the method in the answer is good – Alexander Soare Jan 05 '20 at 09:48
1 Answers
3
Answer is
img[~mask,:] = [0,0,0]
That ,:
takes care of the other dimension so you don't get mismatch issues.

Alexander Soare
- 2,825
- 3
- 25
- 53