Saturday, March 19, 2016

How to apply Bounding BOX for selected objects

Connectivity helps in applying bounding box for selected objects.
Calculate  :
i)Area 
ii) Mean 
iii)Centroid 
iv) Perimeter

clear
close all;
I=imread('coins.png');
figure,imshow(I);
B=im2bw(I);
figure,imshow(B);
c=imfill(B,'holes');                            % Fill the holes
figure,imshow(c);
[label,num]=bwlabel(c);
display(num)
object=3;                                       % To apply bounding box for labelled 3
[row,col]=find(label==object); % to find coordinates of the bounding box
sx=min(col)-0.5;
sy=min(row)-0.5;
breadth=max(col)-min(col)+1;
len=max(row)-min(row)+1;
bbox=[sx sy breadth len];
display(bbox);
figure,imshow(I);
hold on;
x=zeros([1 5]);
y=zeros([1 5]);
x(:)=bbox(1);
y(:)=bbox(2);
x(2:3)=bbox(1)+bbox(3);
y(3:4)=bbox(2)+bbox(4);
plot(x,y);
obj_area=numel(row);
display(obj_area);
% Find Centroid
X=mean(col);
Y=mean(row);
Centroid=[X Y];
display(Centroid);
plot(X,Y,'o','color','r');
hold off
%Find perimeter
BW=bwboundaries(label==object);
figure, imshow(I);
hold on
visboundaries(BW);
c=cell2mat(BW(1));
perimeter=0;
for i=1:size(c,1)-1
perimeter=perimeter+sqrt((c(i,1)-c(i+1,1)^2+c(i+1,2)).^2);
end
display(perimeter);

% calculation with regionprops for verification purpose
sdata=regionprops(label,'all'); % click on sdata and check for different parameters

RESULT:

Fig 1

Fig 2

No comments:

Post a Comment