if(~isdeployed)
cd(fileparts(which(mfilename)));
end
clc;
clear;
close all;
imtool close all;
workspace;
fontSize = 16;
grayImage = imread('cameraman.tif');
subplot(2, 3, 1);
imshow(grayImage, []);
title('Original Grayscale Image', 'FontSize', fontSize);
set(gcf, 'Position', get(0,'Screensize'));
message = sprintf('Left click and hold to begin drawing.\nSimply lift the mouse button to finish');
uiwait(msgbox(message));
hFH = imfreehand();
binaryImage = hFH.createMask();
subplot(2, 3, 2);
imshow(binaryImage);
title('Binary mask of the region', 'FontSize', fontSize);
numberOfPixels1 = sum(binaryImage(:))
numberOfPixels2 = bwarea(binaryImage)
structBoundaries = bwboundaries(binaryImage);
xy=structBoundaries{1};
x = xy(:, 2);
y = xy(:, 1);
subplot(2, 3, 1);
hold on;
plot(x, y, 'LineWidth', 2);
burnedImage = grayImage;
burnedImage(binaryImage) = 255;
subplot(2, 3, 3);
imshow(burnedImage);
caption = sprintf('New image with\nmask burned into image');
title(caption, 'FontSize', fontSize);
blackMaskedImage = grayImage;
blackMaskedImage(~binaryImage) = 0;
subplot(2, 3, 4);
imshow(blackMaskedImage);
title('Masked Outside Region', 'FontSize', fontSize);
meanGL = mean(blackMaskedImage(binaryImage));
message = sprintf('Mean value within drawn area = %.3f\nNumber of pixels = %d\nArea in pixels = %.2f', ...
meanGL, numberOfPixels1, numberOfPixels2);
msgbox(message);
insideMasked = grayImage;
insideMasked(binaryImage) = 0;
subplot(2, 3, 5);
imshow(insideMasked);
title('Masked Inside Region', 'FontSize', fontSize);
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]);
subplot(2, 3, 6);
imshow(croppedImage);
title('Cropped Image', 'FontSize', fontSize);
Best Answer