Superimposing Plots on an Image Example

From MATLAB Techniques for Image Processing by Steve Eddins.

Contents

The basic technique for superimposing lines and markers on images is to:

  1. Display the image using imshow
  2. Call hold on
  3. Superimpose lines or markers in the desired locations using plot.

Using "hold on"

bw = imread('circles.png');
imshow(bw)

Compute the outer boundary of the circles.

b = bwboundaries(bw);
x = b{1}(:,2);
y = b{1}(:,1);

If we call plot, it resets the figure first, erasing the image.

plot(x,y,'r','LineWidth',3)

Obviously that isn't what we want. To keep plot from resetting the figure, call hold on first.

imshow(bw)
hold on
plot(x,y,'r','LineWidth',3)
hold off

How to guarantee line visibility

Using a red line works well on black-and-white or gray-scale images. But what if you have a color image with red pixels? No matter what color you pick for the line, you might not be able to see the line over pixels with similar colors.

Here are two good techniques to guarantee line visibility. Both techniques superimpose two lines instead of one.

Use two lines - vary the color and LineWidth

imshow(bw)
hold on
plot(x,y,'k','LineWidth',3)
plot(x,y,'w','LineWidth',1)
hold off

Use two lines - vary the color and pattern

This second technique doesn't work very well when you're plotting lines with many closely-spaced points, so let's modify the example. We'll superimpose a rectangle over a color image.

rgb = imread('peppers.png');
imshow(rgb)

rect_x = [100 400 400 100 100];
rect_y = [100 100 300 300 100];

hold on
plot(rect_x,rect_y,'w','LineStyle','-','LineWidth',3);
plot(rect_x,rect_y,'k','LineStyle',':','LineWidth',3);
hold off

How to guarantee marker visibility

You can use a similar technique to guarantee marker visibility: Use contrasting colors for MarkerFaceColor and MarkerEdgeColor. Let's illustrate by superimposing binary object centroids over the original image.

I = imread('coins.png');
imshow(I)
bw = im2bw(I,graythresh(I));
bw = imfill(bw,'holes');
L = bwlabel(bw);
s = regionprops(L,'Centroid');

centroids = cat(1,s.Centroid);
centroids_x = centroids(:,1);
centroids_y = centroids(:,2);

imshow(I)
hold on
plot(centroids_x,centroids_y,'LineStyle','none', ...
    'Marker','o', ...
    'MarkerFaceColor','w', ...
    'MarkerEdgeColor','k');
hold off