If your images are the same size, this is pretty easy. Suppose you have two images in grayscale, mainImage
and backImage
. Then you can set the mainImage
pixels that are black to backImage
values by writing:
mainImage(mainImage == 0) = backImage(mainImage == 0);
and this will set the mainImage
black pixels backImage
.
If the images are in color then you have to be a bit more careful. The easiest, most understandable way to do this in my mind is to find the zero values in each color plane and then set the mainImage
where they are all zero to the backImage
. I made a little messy very that converts to linear space and sets the pixels as follows:
[Ny, Nx, Nz] = size(mainImage);
dSize = Ny*Nx;
% Get the location of the black pixels:
bR = mainImage(:,:,1) == 0;
bG = mainImage(:,:,2) == 0;
bB = mainImage(:,:,3) == 0;
blackPixels = find(bR & bG & bB);
mainImage(blackPixels) = backImage(blackPixels);
mainImage(blackPixels + dSize) = backImage(blackPixels+dSize);
mainImage(blackPixels + 2*dSize) = backImage(blackPixels+dSize*2);