Overlaying Binary Masks on Images in Matlab

There are often times when we want to see the boundaries of an annotation overlaid on an image for easier inspection. Using the ‘AlphaData’ layer in matlab this becomes extremely easy and efficient.

For example, we start with an image io:


And some associated binary mask, iob, in this case indicating which pixels belong to nuclei:


We quickly turn this into solely a boundary image, iob_p, using the bwperim command:

  1. iob_p=bwperim(iob);


The last piece we need is a color patch the same size as the original image, in this case we’ll use green [0,1,0]:

  1. green=zeros(size(io,1),size(io,2),3);
  2. green(:,:,2)=1;


From there, it’s a simple process of first displaying the image, then overlaying the green patch, and then setting the transparency according to the binary mask:

  1. figure,imshow(io)
  2. hold all
  3. h=imshow(green);
  4. set(h,'AlphaData',iob_p)


This produces a very lovely bounded image:


Full source here

Leave a Reply

Your email address will not be published. Required fields are marked *