Shape recognition from user input and obtain XYZ coordinates

I would like to identify the shape i need from the attached image according to the user input. After the shape has been recognised I want to be able to obtain the XYZ coordinates of the shape.
I thought it would be a simple use of the bwboundaries function or regionprops() but I can't seem to do so.
The attached images contains the shapes in white, so not including the black rectangle box that contains them.

Answers (1)

I thought it would be a simple use of the bwboundaries function or regionprops() but I can't seem to do so.
Assuming the shapes are all going to be circles and convex polygons, then one way would be to use pgonCorners (which must be Downloaded).
load Image; yourImage=BW;
yourImage=bwareaopen(yourImage,50);
S=regionprops(yourImage,'Centroid','ConvexImage','Circularity'); N=numel(S);
names={'','','Triangle','Quadrilateral','Pentagon','Hexagon','Unknown'};
for i=1:N
if S(i).Circularity>0.9, S(i).shape='Circle'; continue; end
ctr=getfield(regionprops(S(i).ConvexImage,'Centroid'),'Centroid'); %centroid in bounding box
k=3;
while 1
corners= pgonCorners(S(i).ConvexImage,k);
s = size( uniquetol( corners ,10,'ByRows',true,'DataScale',1) ,1);
if s==k-1 || s>=numel(names),
break;
end
S(i).corners=fliplr(corners)-ctr+S(i).Centroid;
k=k+1;
end
S(i).shape=names{s};
end
imshow(yourImage)
hold on
for i=1:N
drawpoint('Position',S(i).Centroid,'Label', S(i).shape,'LabelTextColor','y');
if ~isempty(S(i).corners)
scatter(S(i).corners(:,1), S(i).corners(:,2),'MarkerFaceColor','r','MarkerEdgeColor','y')
end
end
hold off

4 Comments

Thank you for your response but is their anyway to differentiate between the square and rectangle using pgoncorners? I want the code to really only work on those 3 shapes from the image I attached, namely square, rectangle and circle.
The output structure S contains the vertex coordinates in S(i).corners. You can analyze them to see if they have the requesite geometric properties of squares and rectangles (e.g. approximately 90 degree angles, equal length sides, etc...).
I cant seem to run the code on my image. I believe it has something to do with the image format. Is it possibel to use this code on an image that uses the .tif or .png format besides the .mat?
I can't know how you are reading in your .tif or .png., or what type of Matlab variable that results in. You must make sure that the image ends up being converted into a matrix of logicals:
load Image
whos BW
Name Size Bytes Class Attributes BW 417x563 234771 logical

Sign in to comment.

Asked:

on 14 Jun 2021

Edited:

on 15 Jun 2021

Community Treasure Hunt

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

Start Hunting!