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.