MATLAB Answers

Dimitris M

Masking out Image area using Binary Mask

Asked by Dimitris M
on 16 May 2012
Latest activity Commented on by Image Analyst
on 2 Jul 2015


I have an image and I also have a binary mask of the same size(ROI in 1, Background 0). How can I create a new image only with the ROI displayed ?

Is there any difference if the image is grayscale plane or RGB ?

Thank you


4 Answers

Answer by Kye Taylor
on 16 May 2012
 Accepted answer

Let I be the m-by-n image, and let M be the m-by-n mask.

The new image, Inew, will be m-by-n and have zeros everywhere there is a zero in M and will be the grayscale value wherever M has a one.

Inew = I.*M;

If the image is RGB (i.e. I is m-by-n-by-3), then use the command

Inew = I.*repmat(M,[1,1,3]);


Answer by Image Analyst
on 16 May 2012

See my demo - it does three different kinds of masking:

% Demo to have the user freehand draw an irregular shape over
% a gray scale image, have it extract only that part to a new image,
% and to calculate the mean intensity value of the image within that shape.
% Change the current folder to the folder of this m-file.
clc;	% Clear command window.
clear;	% Delete all variables.
close all;	% Close all figure windows except those created by imtool.
imtool close all;	% Close all figure windows created by imtool.
workspace;	% Make sure the workspace panel is showing.
fontSize = 16;
% Read in standard MATLAB gray scale demo image.
grayImage = imread('cameraman.tif');
subplot(2, 3, 1);
imshow(grayImage, []);
title('Original Grayscale Image', 'FontSize', fontSize);
set(gcf, 'Position', get(0,'Screensize')); % Maximize figure.
message = sprintf('Left click and hold to begin drawing.\nSimply lift the mouse button to finish');
hFH = imfreehand();
% Create a binary image ("mask") from the ROI object.
binaryImage = hFH.createMask();
% Display the freehand mask.
subplot(2, 3, 2);
title('Binary mask of the region', 'FontSize', fontSize);
% Calculate the area, in pixels, that they drew.
numberOfPixels1 = sum(binaryImage(:))
% Another way to calculate it that takes fractional pixels into account.
numberOfPixels2 = bwarea(binaryImage)
% Get coordinates of the boundary of the freehand drawn region.
structBoundaries = bwboundaries(binaryImage);
xy=structBoundaries{1}; % Get n by 2 array of x,y coordinates.
x = xy(:, 2); % Columns.
y = xy(:, 1); % Rows.
subplot(2, 3, 1); % Plot over original image.
hold on; % Don't blow away the image.
plot(x, y, 'LineWidth', 2);
drawnow; % Force it to draw immediately.
% Burn line into image by setting it to 255 wherever the mask is true.
burnedImage = grayImage;
burnedImage(binaryImage) = 255;
% Display the image with the mask "burned in."
subplot(2, 3, 3);
caption = sprintf('New image with\nmask burned into image');
title(caption, 'FontSize', fontSize);
% Mask the image and display it.
% Will keep only the part of the image that's inside the mask, zero outside mask.
blackMaskedImage = grayImage;
blackMaskedImage(~binaryImage) = 0;
subplot(2, 3, 4);
title('Masked Outside Region', 'FontSize', fontSize);
% Calculate the mean
meanGL = mean(blackMaskedImage(binaryImage));
% Report results.
message = sprintf('Mean value within drawn area = %.3f\nNumber of pixels = %d\nArea in pixels = %.2f', ...
meanGL, numberOfPixels1, numberOfPixels2);
% Now do the same but blacken inside the region.
insideMasked = grayImage;
insideMasked(binaryImage) = 0;
subplot(2, 3, 5);
title('Masked Inside Region', 'FontSize', fontSize);
% Now crop the image.
topLine = min(x);
bottomLine = max(x);
leftColumn = min(y);
rightColumn = max(y);
width = bottomLine - topLine + 1;
height = rightColumn - leftColumn + 1;
croppedImage = imcrop(blackMaskedImage, [topLine, leftColumn, width, height]);
% Display cropped image.
subplot(2, 3, 6);
title('Cropped Image', 'FontSize', fontSize);


Image Analyst
on 26 Jan 2015

No, sorry. I don't carry on private side conversations on MATLAB. I do it all here.

kristie bell
on 31 Mar 2015


i read your code and i find it really useful for me! Can i check, how can I apply your demo mask to a colour image?

Image Analyst
on 31 Mar 2015

To mask an RGB color image, do this:

% Mask the image using bsxfun() function
maskedRgbImage = bsxfun(@times, rgbImage, cast(mask, class(rgbImage)));

Answer by Dimitris M
on 17 May 2012

Thank you both for your nice codes !

  1 Comment

Kye Taylor
on 17 May 2012

A pleasure!

Answer by Ashmil Mohammed on 2 Jul 2015

Can I create a mask that can be used in varying illumination ? Or is there any other way I can separate out an object when the intensities change?

  1 Comment

Image Analyst
on 2 Jul 2015

I suggest you start a new discussion and attach a few of your images that illustrate the problem.

Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi test

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!