Mick
Mick

Reputation: 324

Merge images using OpenCV and a mask

I've been performing some image operations using OpenCV and Python. I've managed to isolate the contour that I have an interest in. Now I have two images, one NDVI image, and one normal image. I'd like to merge the two using my mask. So if the pixel position of my mask is zero, it should use the pixel of image one and if the pixel position of my mask is one, then it should use the pixel of image two. Based on that I'd like to merge two of my pictures.

Any suggestions would be appreciated :)!

Upvotes: 2

Views: 8736

Answers (1)

alkasm
alkasm

Reputation: 23052

This is super easy with numpy indexing by mask.

There's a number of different ways you can do this. For e.g., here's two float images. Then I create a boolean mask (in this case I take a random float image and roughly half the pixels will be included, half excluded). Then for the combined image you can set it equal to one of the images, and then wherever the mask is True you insert the values from the other image:

>>> import numpy as np
>>> img1 = np.random.rand(100,100,3)
>>> img2 = np.random.rand(100,100,3)
>>> mask = np.random.rand(100,100)>.5
>>> comb_img = img2.copy()
>>> comb_img[mask] = img1[mask]

So to be clear, at all points where mask is True, this comb_img has the values of img1, and otherwise has values of img2.

Another way you can combine the two images that is maybe more explicit is to create the combined image as a blank image first, and then insert one image at the mask points and then insert the other image at the flipped mask points:

>>> comb_img = np.zeros_like(img1)
>>> comb_img[mask] = img1[mask]
>>> comb_img[~mask] = img2[~mask]

And incase you haven't seen it, for boolean numpy arrays ~ inverts it:

>>> ~np.array([True, False, True])
array([False,  True, False], dtype=bool)

Of course your mask can also be numeric, and you can just use mask==0 and mask>0 to create logical arrays for indexing.

Upvotes: 6

Related Questions