Steve on Image Processing and MATLAB

Concepts, algorithms & MATLAB

Image overlays

Update: See the 03-Dec-2019 post, "How to Overlay a Color on an Image Using a Mask."

Contents

Image Overlay

In response my post on "Tracing George", blog reader Riccardo asked me how to overlay the thinned binary image on top of the original image, using a different color. That is, given George:

url = 'https://blogs.mathworks.com/images/steve/36/george.jpg';
I = imread(url);
imshow(I)

and thinned George, using the method given in my previous post:

threshold = graythresh(I);
bw = im2bw(I, threshold);
bw2 = ~bw;
bw3 = bwmorph(bw2, 'thin', inf);

imshow(bw3)

how do you produce a color overlay like this:

Procedure

We want to produce an RGB (truecolor) image. Everywhere the binary image mask is zero, it should look like the original image. Everywhere the binary image mask is nonzero, it should have the specified color.

Start by making three copies of the original image, one for each channel of the desired RGB image.

out_red   = I;
out_green = I;
out_blue  = I;

Second, replace the masked pixels in each channel image with the desired color value.

out_red(bw3)   = 255;   % Class of out_red is uint8, so use 255 instead of 1.
out_green(bw3) = 255;
out_blue(bw3)  = 0;

Finally, concatenate the channel images along the third dimension to produce the desired overlay image.

out = cat(3, out_red, out_green, out_blue);
imshow(out)

File Exchange - imoverlay.m

I've often thought that this image overlay operation would be a good utility for the MATLAB File Exchange. Riccardo's question finally pushed me to write and submit imoverlay.m. I hope some of you find it useful.

help imoverlay
 IMOVERLAY Create a mask-based image overlay.
    OUT = IMOVERLAY(IN, MASK, COLOR) takes an input image, IN, and a binary
    image, MASK, and produces an output image whose pixels in the MASK
    locations have the specified COLOR.
 
    IN should be a grayscale or an RGB image of class uint8, uint16, int16,
    logical, double, or single.
 
    MASK should be a two-dimensional logical matrix.
 
    COLOR should be a 1-by-3 vector of values in the range [0, 1].  [0 0 0]
    is black, and [1 1 1] is white.
 
    OUT is a uint8 RGB image.
 
    Example
    -------
    Overlay edge detection result in green over the original image.
        
        I = imread('cameraman.tif');
        bw = edge(I, 'canny');
        rgb = imoverlay(I, bw, [0 1 0]);
        imshow(rgb)




Published with MATLAB® 7.2

|

Comments

To leave a comment, please click here to sign in to your MathWorks Account or create a new one.