# How to classify shapes of this image as square, rectangle, triangle and circle?

조회 수: 62 (최근 30일)
ROMIL 2014년 2월 19일
댓글: Image Analyst 2021년 10월 6일
Please provide me the matlab code to identify shapes on this image and classify them as square, rectangle, circle and triangle.
##### 댓글 수: 5이전 댓글 3개 표시이전 댓글 3개 숨기기
phaneendra ch 2015년 12월 11일
Ur code is working very excellent.
Image Analyst 2015년 12월 12일
Not sure whose code you're talking about, but glad you finally got it working. If you have any questions in the future, post your image and code in a new question.

댓글을 달려면 로그인하십시오.

### 채택된 답변

Matt Kindig 2014년 2월 21일
편집: Matt Kindig 2014년 2월 21일
Another approach is to calculate the best-fit bounding rectangle of each object, such that the bounding rectangle can be oriented at an arbitrary angle. I took the following approach:
1) Identify the boundary (i.e. perimeter) of each object, using bwboundaries()
2) Calculate the smallest rectangular bounding box that contains this perimeter. To do this, I used the minboundrect function available at http://www.mathworks.com/matlabcentral/fileexchange/34767-a-suite-of-minimal-bounding-objects/content/MinBoundSuite/minboundrect.m.
3) I calculated the width, height, and area of each bounding rectangle. The aspect ratio (ratio between the width and height) can be used to determine whether it is a square (aspect ratio ~= 1.0) or rectangle.
4) For a rectangle or square, the filled area of the object (from regionprops()) should be almost the same as the area of its bounding rectangle, whereas for a triangle it should be substantially less.
5) For the circularity condition, I used the ratio between perimeter and area like Image Analyst suggested.
Enjoy!
%convert to 2D black and white with colors inverted
BW = im(:,:,1) < 10;
%get outlines of each object
[B,L,N] = bwboundaries(BW);
%get stats
stats= regionprops(L, 'Centroid', 'Area', 'Perimeter');
Centroid = cat(1, stats.Centroid);
Perimeter = cat(1,stats.Perimeter);
Area = cat(1,stats.Area);
CircleMetric = (Perimeter.^2)./(4*pi*Area); %circularity metric
SquareMetric = NaN(N,1);
TriangleMetric = NaN(N,1);
%for each boundary, fit to bounding box, and calculate some parameters
for k=1:N,
boundary = B{k};
[rx,ry,boxArea] = minboundrect( boundary(:,2), boundary(:,1)); %x and y are flipped in images
%get width and height of bounding box
width = sqrt( sum( (rx(2)-rx(1)).^2 + (ry(2)-ry(1)).^2));
height = sqrt( sum( (rx(2)-rx(3)).^2+ (ry(2)-ry(3)).^2));
aspectRatio = width/height;
if aspectRatio > 1,
aspectRatio = height/width; %make aspect ratio less than unity
end
SquareMetric(k) = aspectRatio; %aspect ratio of box sides
TriangleMetric(k) = Area(k)/boxArea; %filled area vs box area
end
%define some thresholds for each metric
%do in order of circle, triangle, square, rectangle to avoid assigning the
%same shape to multiple objects
isCircle = (CircleMetric < 1.1);
isTriangle = ~isCircle & (TriangleMetric < 0.6);
isSquare = ~isCircle & ~isTriangle & (SquareMetric > 0.9);
isRectangle= ~isCircle & ~isTriangle & ~isSquare; %rectangle isn't any of these
%assign shape to each object
whichShape = cell(N,1);
whichShape(isCircle) = {'Circle'};
whichShape(isTriangle) = {'Triangle'};
whichShape(isSquare) = {'Square'};
whichShape(isRectangle)= {'Rectangle'};
%now label with results
RGB = label2rgb(L);
imshow(RGB); hold on;
Combined = [CircleMetric, SquareMetric, TriangleMetric];
for k=1:N,
%display metric values and which shape next to object
Txt = sprintf('C=%0.3f S=%0.3f T=%0.3f', Combined(k,:));
text( Centroid(k,1)-20, Centroid(k,2), Txt);
text( Centroid(k,1)-20, Centroid(k,2)+20, whichShape{k});
end
##### 댓글 수: 12이전 댓글 10개 표시이전 댓글 10개 숨기기
Beenish Ishtiaq 2021년 8월 5일
error in minboundrect

댓글을 달려면 로그인하십시오.

### 추가 답변 (10개)

Image Analyst 2014년 2월 19일
편집: Image Analyst 2016년 3월 19일
Look at the perimeter squared to area ratio. Use regionprops as shown in my Image Segmentation Tutorial: http://www.mathworks.com/matlabcentral/fileexchange/?term=authorid%3A31862
[EDIT]
See attached demo.
##### 댓글 수: 21이전 댓글 19개 표시이전 댓글 19개 숨기기
aliya 2021년 10월 6일
hye sir, i use your shape_recognition_demo.m. code. but i want to use my own image, i already use your method which replace the
% Now create a demo image.
[binaryImage, numSidesCircularity] = CreateDemoImage();
with imread() but i got an error 'unrecognized function or variable 'binaryImage' , how to solve this? thankyou in advanced!
Image Analyst 2021년 10월 6일
@aliya I just downloaded it and it works fine. You modified it somehow but didn't attach your code so I can't fix it.
I'm attaching the lastest version I have of the demo (not sure if it's changed over the last 7 years, but probably).

댓글을 달려면 로그인하십시오.

phaneendra ch 2015년 11월 22일
While executing the above code I am getting an error in the code I.e.,(undefined function or variable 'minbounderect'). As I am new to MATLAB plz solve this prblm.tq in advance sir
##### 댓글 수: 2없음 표시없음 숨기기
Image Analyst 2015년 11월 22일
I'm attaching John D'Errico's function, minboundrect().
kaz 2016년 4월 25일
i am so noob with matlab. sir how to add this function to the codes at the top. which i am getting the same error minboundrect. ty

댓글을 달려면 로그인하십시오.

Venkatesh A 2015년 12월 12일
Mr.matt kindig, I am working with your "various shapes detecting" code which is in this page. The code u have written is working very well for the above black and white image(the image which you chosen to write code). But I am using some other images( 'shapes.jpg' which is now I am submitting) which might have some holes in the inside of the image and I am getting error( error is the matrix cannot be generated). How to fill the small holes in that image. Can I draw subplots for your code for various shapes that are present in the image?
##### 댓글 수: 1이전 댓글 -1개 표시이전 댓글 -1개 숨기기
Image Analyst 2015년 12월 12일
Venkatesh A, you forgot to give the link to your question where you attached your code and image.
If you do that, we can go to your question and tell you how to use imfill(binaryImage, 'holes') to fill holes in your image.

댓글을 달려면 로그인하십시오.

Venkatesh A 2015년 12월 14일
Sorry sir. here is the image
##### 댓글 수: 2없음 표시없음 숨기기
Jan 2016년 2월 18일
No, there is no image.
B.k Sumedha 2016년 3월 19일
There is no image attached.

댓글을 달려면 로그인하십시오.

AKHIL RAJAGOPAL 2016년 4월 23일
I am getting an error at isTriangle = ~isCircle & (TriangleMetric < 0.6); as: Error using & Matrix dimensions must agree.
##### 댓글 수: 10이전 댓글 8개 표시이전 댓글 8개 숨기기
Image Analyst 2016년 4월 25일
See attached spatial calibration demo.
kaz 2016년 4월 25일
thank you so much

댓글을 달려면 로그인하십시오.

noor jahan m 2016년 12월 8일
i am a beginner in matlab. I tried the code for rectangle detection. I cud also find the function minboundrect . but i got error in convex hull of this function. Can u please help further? thank u
##### 댓글 수: 0이전 댓글 -2개 표시이전 댓글 -2개 숨기기

댓글을 달려면 로그인하십시오.

Rahul Chauhan 2017년 10월 23일
Ty very much sir for the code but I'm getting error as "undefined function or variable 'minboundract'" So plz help me sir getting this error correct asap.... Again Ty in advance sir
##### 댓글 수: 4이전 댓글 2개 표시이전 댓글 2개 숨기기
Image Analyst 2017년 10월 24일
Again, it's minboundrect(), not minboundract().
Supply your image and code in a new question (not as an Answer here in ROMIL's discussion thread - he probably doesn't care anymore since he posted this three and a half years ago.)
Rahul Chauhan 2017년 10월 25일
again sir i corrected the function but the code is not working here i am attaching the code and image file know help me.... here is the code :(1)file attached as test.m
(2)minboundrect.m
here is the image: abc.jpg
ty in advance sir for helping me.....

댓글을 달려면 로그인하십시오.

Pavel Vilbik 2017년 12월 11일
How to find the qr code( this plastic card) in this photo, as it has a begining job, I need a coordinate and axis, and that I would be marked with a ractangle.
##### 댓글 수: 1이전 댓글 -1개 표시이전 댓글 -1개 숨기기
Image Analyst 2017년 12월 11일
You should start your own question on this. In that question I'll tell you how to find the blobs, perhaps based on color saturation, and then to take the histogram of each blob looking for a fairly bimodal histogram. The standard deviation of the histogram of the all black and all white objects will be much less than a checkerboard object. If you still can't figure it out, I might post code over in that new question you're going to post.

댓글을 달려면 로그인하십시오.

Michelle de Bock 2018년 12월 28일
Hi Sir,
Is it also possible to classify the direction of the triangle. e.g. left pointing triangle or right pointing triangle? Also classifying the thrid/fourth object in the picture? This is not really a rectangle, but how to separate this from a real rectangle?
Kind regards,
Michelle
##### 댓글 수: 1이전 댓글 -1개 표시이전 댓글 -1개 숨기기
Image Analyst 2018년 12월 28일
Yes, I'm sure you could. Just modify my attached shape recognition demo. Once you have the blob, find its bounding box and centroid with regionprops. Then if the centroid is to the left of the centerline of the bounding box, it's pointing to the left. If it's below, it's pointing up.
For the other object, you'll also have to look for how many vertices it has and then perhaps scale a template to its size and see if enough pixels match to be considered that object. You could also do the template matching method with the triangles if you want. No, I don't have code for that but, being smart engineer, I'm sure you will find it easy to do.

댓글을 달려면 로그인하십시오.

Ahaana Khurana 2020년 2월 4일
ROMIL can you pls provide the code for SHAPE DETECTION on ahaanakhurana@gmail.com.
##### 댓글 수: 3이전 댓글 1개 표시이전 댓글 1개 숨기기
Dina Abd El-twab 2020년 2월 24일
편집: Dina Abd El-twab 2020년 2월 24일
pp=alexnet;
ppl=pp.Layers;
pp=pp.Layers(1:19);
ppp=[pp
fullyConnectedLayer(2)
softmaxLayer()
classificationLayer()]
options = trainingOptions('sgdm',...
'InitialLearnRate',1e-3,...
'MaxEpochs',10,...
'CheckpointPath',tempdir);
train1 = trainFasterRCNNObjectDetector(gTruth,ppp,options, ...
'NegativeOverlapRange',[0 0.1], ...
'PositiveOverlapRange',[0.5 1], ...
'SmallestImageDimension',300);
a = imresize(a,[227 227]);
[bbox,score,label] = detect(train1,a);
detect= insertShape(a,'rectangle',bbox);
figure
imshow(detect)
@Image Analyst
Image Analyst
Dina Abd El-twab 2020년 2월 24일
I applied this code to draw a rectangle on the region of interest that i want after taining using faster RCNN .I want to convert the drawn rectangle to be circle in the next step , could you help me please ?
@Image Analyst
Image Analyst

댓글을 달려면 로그인하십시오.

### 카테고리

Help CenterFile Exchange에서 Recognition, Object Detection, and Semantic Segmentation에 대해 자세히 알아보기

### Community Treasure Hunt

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

Start Hunting!

Translated by