Mask an image with another image

asked 2020-02-23 00:24:38 -0500

Elric gravatar 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?

edit retag flag offensive close merge delete

Comments

2

use copyTo

LBerger gravatar imageLBerger ( 2020-02-23 04:08:48 -0500 )edit