Back to How-to

Overlay tutorial

The function below is meant to be a quick illustration of how to overlay images using transparency.

function overlay_tutorial

color_matrix = [1 1 1; 0 0 0; 0 1 0; 1 0 1];

background = ones(50, 100);
[X,Y] = ndgrid(1:50, 1:100);
c1 = sqrt((X - 25) .^ 2 + (Y - 30) .^ 2) < 10;
c2 = sqrt((X - 25) .^ 2 + (Y - 30) .^ 2) < 20;
background(find(~c1 & c2)) = 4;

foreground = ones(50, 100);
c3 = X < 30 & X > 25;
foreground(find(c3)) = 3;
c4 = Y < 40 & Y > 35;
foreground(find(c4)) = 2;
transparency = ones(size(foreground));
transparency(find(c3)) = 0;
transparency(find(c4)) = 0.5;

set(gcf, 'Colormap', color_matrix);
image(background); colorbar;
hold on;
im_fore = imagesc(foreground);
set(im_fore, 'AlphaData', 1 - transparency);