MATLAB: Overlaying ROI excluding mask inside a mask

image analysisimage processing

Hi, I wrote a code that can draw and create mask of several polygons on the image(adapted from imageanalyst's demo).
Polygon 1(snowman body) and 3(snowman head) are inside polygon 3, and I want the following binary image :
I want the desired ROI to be polygon 3 – (polygon 1+2).
The code and the current results are below,
% cd and read image
cd /users/june/owncloud/curvature
Image = imread('snowman.png')
% Read in a standard MATLAB gray scale demo image.
% freehand mask.
imshow(Image, []);
set(gcf, 'Position', get(0,'Screensize')); % Maximize figure.
% draw polygon in a loop
poly1 = drawpolygon;
poly2 = drawpolygon;
poly3 = drawpolygon;
%binary image
bi1 = poly1.createMask();
bi2 = poly2.createMask();
bi3 = poly3.createMask();
inside = bi1 & bi2
% Get coordinates of the boundary of the freehand drawn region.
structBoundariesa = bwboundaries(bi1);
xy1=structBoundariesa{1}; % Get n by 2 array of x,y coordinates.


x1 = xy1(:, 2); % column 2.


y1 = xy1(:, 1); % column 1.


structBoundariesb = bwboundaries(bi2);
xy2=structBoundariesb{1}; % Get n by 2 array of x,y coordinates.
x2 = xy2(:, 2); % column 2.
y2 = xy2(:, 1); % column 1.
structBoundariesb = bwboundaries(bi3);
xy3=structBoundariesb{1}; % Get n by 2 array of x,y coordinates.
x3 = xy3(:, 2); % column 2.
y3 = xy3(:, 1); % column 1.
% Now make it smaller so we can show more images.
subplot(1, 3, 1);
imshow(Image, []);
drawnow;
title('Original gray scale image');
% Display the freehand mask.
subplot(1, 3, 2);
imshow(binary);
title('Binary mask of the region');
% Burn region as black into image by setting it to 255 wherever the mask is true.
burnedImage = Image;
burnedImage(~bi3|inside) = 0;
% Display the image with the mask "burned in."
subplot(1, 3, 3);
imshow(burnedImage);
caption = sprintf('Masked black inside region');
title(caption);

Best Answer

Try this:
inside = bi1 & ~bi2 & ~bi3;
% Mask the image using bsxfun() function to multiply the mask by each channel individually. Works for gray scale as well as RGB Color images.
maskedRgbImage = bsxfun(@times, rgbImage, cast(inside, 'like', rgbImage));
You don't need all that stuff about boundaries.
Don't call your variable Image because there is a built-in function called image() and it could get confusing to the reader/programmer, even though MATLAB is case sensitive so it won't be a problem.