How to crop a masked area (polygon shape) out of an image?
89 views (last 30 days)
Show older comments
Chutiphon Moranon on 29 Mar 2022
Commented: Image Analyst on 30 Mar 2022
Now my code is like below:
I = imread('moon.tif');
Poly_Mask = images.roi.Polygon(gca,'Position',[100 150; 200 250; 300 350; 150 450]);
As you can see, the example image is now masked with a polygon shape. I would like to crop the masked area (polygon shape) out of the image. Could you please suggest me how to do this? Thank you.
grayImage = imread('moon.tif');
[rows, columns, numberOfColorChannels] = size(grayImage)
subplot(2, 1, 1);
x = [100, 200, 300, 150];
y = [150, 250, 350, 450];
% tack on starting point to close it so the plot is not oepn jaw. (Only
% needed if you wan to plot the outline in the overlay.
x = [x, x(1)];
y = [y, y(1)];
plot(x, y, 'r-', 'LineWidth', 2);
mask = poly2mask(x, y, rows, columns);
% Erase outside mask by setting to zero
grayImage(~mask) = 0;
croppedImage = grayImage(min(y):max(y), min(x):max(x));
subplot(2, 1, 2);
You can't make it transparent, and it does not need to be for any reason that I can think of, certainly not for normxcorr2().
You can have any shape you want just by putting in the coordinates of the shape boundaries into poly2mask().
More Answers (1)
Tala on 29 Mar 2022
Edited: Tala on 29 Mar 2022
I cannot see your image. But I used a photo of my dog (because she wont sue me :D) to show the concept:
x=[100 200 300 150];% your ROI x values
y=[150 250 350 450];% your ROI y values
[rows, columns,~] = size(I);
mask = imcomplement(poly2mask(x, y, rows, columns));
mul = immultiply(I,mask);
Find more on Region and Image Properties in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!Start Hunting!