Creating Binary Image from Polygon Label in MATLAB

Hello,
I'm relatively new to MATLAB and I'm working on a project where I need to create a binary image from a PNG image. I've used the Image Labeler app to add a polygon label to the region of interest in my image, similar to what's shown in the attached image.
Now, I'm looking for guidance on the next steps to create a binary label. Specifically, I want the selected polygon area to be in white, while the rest of the image should be black. After creating this binary label, I'd like to export it as a PNG file.
I've searched extensively for a solution but haven't been able to figure it out yet. Can someone please provide me with step-by-step instructions or sample code on how to achieve this in MATLAB?
Any assistance would be greatly appreciated. Thank you!

 採用された回答

Image Analyst
Image Analyst 2023 年 10 月 30 日

1 投票

You have to click the Export button and then export to the workspace to a variable, like groundTruth. Then you can get the (x,y) coordinates from groundTruth.Labeldata.yourRegionm then use poly2mask and imwrite.
x = groundTruth.LabelData.yourRegion(:, 1);
y = groundTruth.LabelData.yourRegion(:, 2);
mask = poly2mask(x, y, rows, columns);
imwrite(mask, 'Mask.png');
I don't think there is a way to export it directly without writing some code like I did.

2 件のコメント

Ahmad
Ahmad 2023 年 10 月 31 日
thank you!
Image Analyst
Image Analyst 2023 年 10 月 31 日
Thanks for accepting. You can email them and make the suggestion that the labeled image be able to be exported to a disk file.

サインインしてコメントする。

その他の回答 (1 件)

Sulaymon Eshkabilov
Sulaymon Eshkabilov 2023 年 10 月 30 日

0 投票

Here is how it can be done:
I0 = imread('HVOF.png');
I = rgb2gray(I0);
% Polygon coordinates
XY=[50 150; 200 250; 300 350; 150 350; 100 350;50 150;]; % Close the loop polygon
X = XY(:,1)';% Coordinates of the polygon along x axis
Y = XY(:,2)';% Coordinates of the polygon along y axis
[rows, columns, numberOfColorChannels] = size(I);
figure
imshow(I, []);
axis 'on';
title('ALPS (Original picture)')
hold on;
plot(X, Y, 'rd-', 'LineWidth', 2);
mask = poly2mask(X,Y, rows, columns);
% Beyond of the MASK (polygon) = black (0)
Inew = I;
Inew(~mask) = 0;
figure('name', 'Comparison')
subplot(221)
imshow(I), title ('Original'), axis on
subplot(222)
imshow(Inew), title('Changed')
figure ('Name', 'Changed Image')
imshow(Inew), title('Changed')
axis('on', 'image')

1 件のコメント

Ahmad
Ahmad 2023 年 10 月 30 日
Thank you for responding. I want to make polygons through the image labeler and not using the code. Can you tell me how it can be done?

サインインしてコメントする。

製品

リリース

R2023b

質問済み:

2023 年 10 月 30 日

コメント済み:

2023 年 10 月 31 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by