# How to draw single bounding box by combining all bounding boxes

13 views (last 30 days)
Stephen john on 25 Aug 2022
Commented: Walter Roberson on 25 Aug 2022
Hello everyone, I hope you are doing well. I have the image in which i want to draw bounding box on the object.
I have write the following code, which convert the image in binary form and draw the bounding box around white object.
But i want to draw a single bounding box. How can i draw or combine all bounding boxes in MATLAB and plot it on original Image.
im1=im2bw(Image);
invertedI = ~im1
[labeledImage, numRegions] = bwlabel(invertedI);
props = regionprops(labeledImage,'all' );
allLengths = [props.Area];
% NumberofPulses=allLengths;
centroids = vertcat(props.Centroid);
figure;
hold on;
for k = 1 : numRegions
y1 = round(centroids(k, 2));
y2 = y1;
xt = props(k).Centroid(1);
yt = props(k).Centroid(2);
BB = props(k).BoundingBox;
rectangle('Position', [BB(1),BB(2),BB(3),BB(4)],'EdgeColor','b','LineWidth',1) ;
caption = sprintf('Class 1') ;
hold off
title(caption, 'FontSize',10);
end

KSSV on 25 Aug 2022
im1=im2bw(Image);
invertedI = ~im1 ;
[labeledImage, numRegions] = bwlabel(invertedI);
props = regionprops(labeledImage,'all' );
allLengths = [props.Area];
% NumberofPulses=allLengths;
centroids = vertcat(props.Centroid);
X = zeros(numRegions,4) ;
Y = zeros(numRegions,4) ;
figure;
hold on;
for k = 1 : numRegions
y1 = round(centroids(k, 2));
y2 = y1;
xt = props(k).Centroid(1);
yt = props(k).Centroid(2);
BB = props(k).BoundingBox;
rectangle('Position', [BB(1),BB(2),BB(3),BB(4)],'EdgeColor','b','LineWidth',1) ;
X(k,:) = [BB(1) BB(1)+BB(3) BB(1)+BB(3) BB(1)] ;
Y(k,:) = [BB(2) BB(2) BB(2)+BB(4) BB(2)+BB(4)] ;
caption = sprintf('Class 1') ;
hold off
title(caption, 'FontSize',10);
end
x0 = min(X(:)) ; x1 = max(X(:)) ;
y0 = min(Y(:)) ; y1 = max(Y(:)) ;
L = abs(x1-x0) ;
B = abs(y1-y0) ;
rectangle('Position', [x0 y0 L B],'EdgeColor','r','LineWidth',1) ;
Walter Roberson on 25 Aug 2022
text(x0, y0, 'class1')

### Categories

Find more on Image Arithmetic in Help Center and File Exchange

R2022a

### Community Treasure Hunt

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

Start Hunting!

Translated by