Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Mask an image with another image

I'm newbie with Python and OpenCV.

I have two Numpy Array, both with the same shape (240, 240). One of them will be a mask, like the following picture, and the other one will be an image.

The values in the mask array are 0 or 1. And the values in the img are float, and has no limits, from 0.0 to ....

image description

I want to use the mask to cut out the image:

  • Where the mask pixels are black, the output array will have a black pixel.
  • Where the mask pixels are white, the output array will have the same colour of the other array.

I can do the above algorithm with this code:

for i in range(0, mask.shape[0]):
    if mask[i] = 0:
        output[i] = 0
    else
        output[i] = img[i]

But I'm wondering is there is a function in OpenCV to do it.

I have also tried this:

import numpy as np

output = np.dstack((img, mask))

But output has a (240, 240, 2) shape.

Is there an OpenCV function to do that?