clc;
close all;
clear;
workspace;
format long g;
format compact;
fontSize = 20;
sourceImage = imread('peppers.png');
subplot(2, 2, 1);
imshow(sourceImage);
title('Original Image', 'FontSize', 20);
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0 0 1 1]);
set(gcf, 'Toolbar', 'none', 'Menu', 'none');
set(gcf, 'Name', 'Demo by ImageAnalyst', 'NumberTitle', 'Off')
uiwait(msgbox('Draw a polygon. Double click to accept/finish it'));
hPoly = impoly;
polyPoints = hPoly.getPosition
mask = hPoly.createMask;
subplot(2, 2, 2);
imshow(mask);
title('Mask', 'FontSize', 20);
croppedImage = sourceImage;
croppedImage(~repmat(mask, 1, 1, 3)) = 0;
x1 = round(min(polyPoints(:, 1)))
x2 = round(max(polyPoints(:, 1)))
y1 = round(min(polyPoints(:, 2)))
y2 = round(max(polyPoints(:, 2)))
croppedImage = croppedImage(y1:y2, x1:x2, :);
subplot(2, 2, 3);
imshow(croppedImage);
title('Cropped Image', 'FontSize', 20);
Best Answer