MATLAB Answers

How do I superimpose images in MATLAB?

782 views (last 30 days)
I would like to know how to superimpose images in MATLAB.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 5 Nov 2020
Edited: MathWorks Support Team on 5 Nov 2020
There are two basic ways to superimpose images in MATLAB. One involves using transparency for overlaying images objects that may not be exact rectangles, and the other involves indexing into the image data to replace pixels.
Using transparency allows you to achieve the effect of partly seeing through a pixel, rather than completely hiding the background. Indexing allows you to effectively create a new image object that is a combination of pixels from multiple image objects.
-----------------------------------------
1. Using transparency to superimpose images:
Suppose you have an image with pixels that are transparent or partially transparent, and you have another image that should serve as the background. You want the first image to let the background show through wherever there is transparency.
Note that, when using this method, you are actually dealing with multiple image objects. The superimposing is achieved by overlapping the image objects. Additionally, when using semitransparent pixels, you can achieve the effect of partially seeing through a pixel rather than completely hiding the background.
Here is an example that illustrates this method. Over a background image, you will overlay another image at a location within the background. If you are simply trying to place images within other images without using transparency, then you can ignore the code that sets the 'AlphaData' property of the image objects:
% Create the background
% This example uses a blend of colors from left to right, converted to a TrueColor image
% Use repmat to replicate the pattern in the matrix
% Use the "jet" colormap to specify the color space
bg = ind2rgb(repmat(1:64,64,1),jet(64));
% Create an image and its corresponding transparency data
% This example uses a random set of pixels to create a TrueColor image
im = rand(100,100,3);
% Make the image fade in from left to right by designing its alphadata
% Use repmat to replicate the pattern in the transparency fading
imAlphaData = repmat(0:1/size(im,2):1-1/size(im,2),size(im,1),1);
% Display the images created in subplots
hf = figure('units','normalized','position',[.2 .2 .6 .6]);
ax1 = subplot(2,3,1);
ibg = image(bg);
axis off
title('Background')
ax2 = subplot(2,3,4);
iim = image(im);
axis off
title('Image without transparency yet')
% Now set up axes that overlay the background with the image
% Notice how the image is resized from specifying the spatial
% coordinates to locate it in the axes.
ax3 = subplot(2,3,[2:3, 5:6]);
ibg2 = image(bg);
axis off
hold on
% Overlay the image, and set the transparency previously calculated
iim2 = image(im,'XData',[30 50],'YData',[10 30]);
set(iim2,'AlphaData',imAlphaData);
title(sprintf('Using transparency while overlaying images:\nresult is multiple image objects.'))
If you want to extract a circle from the image, and overlay just that
(NOTE: This part of the example requires the Image Processing Toolbox function ROIPOLY to create the circle mask.):\n
% Add another image to the background, but use the 'AlphaData' property
% to just overlay a circle instead.
%
% First define the polygon region of interest
t = 0:.1:2*pi;
[imheight,imwidth] = size(im(:,:,1));
x = round(20*cos(t)+round(imwidth/2));
y = round(20*sin(t)+round(imheight/2));
% Extract the polygon mask
imCircleAlphaData = roipoly(im,x,y);
axes(ax3);
% Overlay the image, and set the transparency previously calculated
iim3 = image(im,'XData',[0 30],'YData',[30 60]);
set(iim3,'AlphaData',double(imCircleAlphaData));
-----------------------------------------
2. Using indexing to superimpose images:
Use this method if you have an image that you want to place in a scene, but prefer to have only a single image as a resultant. The following example achieves this by replacing the scene pixels with the object image pixels.\n
% Create the scene
% This example uses a random set of pixels to create a TrueColor image
scene = rand(100,100,3);
% Create the object image
% This example uses a blend of colors from left to right, converted to a TrueColor image
% Use repmat to replicate the pattern in the matrix
% Use the "jet" colormap to specify the color space
obj = ind2rgb(repmat(1:64,64,1),jet(64));
% Display the images created in subplots
hf2 = figure('units','normalized','position',[.2 .2 .6 .6]);
axi1 = subplot(2,3,1);
iscene = image(scene);
axis off
title('Scene')
axi2 = subplot(2,3,4);
iobj = image(obj);
axis off
title('Object image')
% Now replace pixels in the scene with the object image
result = scene;
% Define where you want to place the object image in the scene
rowshift = 20;
colshift = 0;
% Perform the actual indexing to replace the scene's pixels with the object
result((1:size(obj,1))+rowshift, (1:size(obj,2))+colshift, :) = obj;
% Display the results
ax3 = subplot(2,3,[2:3, 5:6]);
iresult = image(result);
axis off
hold on
title(sprintf('Using indexing to overlay images:\nresult is one image object'))
If you want to extract a circle from the object, and overlay just that:
(AGAIN, NOTE: This part of the example requires the Image Processing Toolbox function ROIPOLY to create the circle mask.):\n
% Let's add another image to the scene.
% First define the polygon region of interest
t = 0:.1:2*pi;
[objheight,objwidth] = size(obj(:,:,1));
x = round(20*cos(t)+round(objwidth/2));
y = round(20*sin(t)+round(objheight/2));
% Since the mask is 2D, repeat it through the 3D RGB matrix
% while extracting the polygon mask
objCircleMask = repmat(roipoly(obj,x,y),[1,1,3]);
% Define where we want to place the circle object in the scene
rowshift = 0;
colshift = 30;
result2 = result;
% Perform the actual indexing. First calculate the replacement pixels
% by multiplying the scene by the negative of the mask, and then adding
% the object multiplied by the mask. Multiplying the mask chooses all
% pixels corresponding to a 1 in the mask, and removes color from the
% pixels corresponding to a 0.
replacementPixels = ( result((1:size(obj,1))+rowshift, (1:size(obj,2))+colshift, :) ...
.* double(~objCircleMask) ) + ( obj .* double(objCircleMask) );
% Now replace the pixels with the ones we just calculated
result2((1:size(obj,1))+rowshift, (1:size(obj,2))+colshift, :) = replacementPixels;
% Display the results. Notice that we placed the circle object in the scene
% that resulted from the previous object placement.
axes(ax3);
delete(iresult)
iresult2 = image(result2);
If you need to resize the object image before placing it in the scene, then you will find the Image Processing Toolbox's IMRESIZE command useful:
https://www.mathworks.com/help/images/ref/imresize.html
  3 Comments
Moritz Kb
Moritz Kb on 24 Mar 2021
Is this not possible using tiledlayout? Creating two axes with the same position is not possible since the position cannot be changed in tiledlayout.
Sad to reverse everything to subplot because tiledlayouts functionality is limited atm

Sign in to comment.

More Answers (2)

Nyn
Nyn on 19 Jan 2016
Superpouse opaque images in MATLAB:
A = big_image;
B=small_image;
B=padarray(B,[1 1]); %If you want borders
Y=position_small_image(1);
X=position_small_image(2);
A((1:size(B,1))+X,(1:size(B,2))+Y,:) = B;
A is your overwritten result.
  1 Comment
sathish kumar rb
sathish kumar rb on 22 Aug 2017
how to superimpose the lung image without background

Sign in to comment.


tan kei guan
tan kei guan on 19 Apr 2018
can this method apply to 2 real time images or videos ? i mean not a snapshot

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!