How to draw bounding boxes around objects?
62 views (last 30 days)
Show older comments
Hello..
I'm trying to get a bounding box around the objects in an image:
[bwlabel,num]=bwlabel(Ibin);
num;
s=regionprops(FeatureMap,'BoundingBox');
imshow(FeatureMap),title('Image with bounding box')
hold on
for i=1:length(s)
currbb=s(i).BoundingBox;
rectangle('position',[currbb(1),currbb(2),currbb(3),currbb(4)],'EdgeColor','g')
end
hold off
but the result is one rectangle like this:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1005635/image.png)
can someone help...
2 Comments
Matt J
on 20 May 2022
Well, attach Ibin in a .mat file (not any other image file type) and we can examine it.
Answers (1)
prabhat kumar sharma
on 19 Feb 2024
Hi Ali,
I understand that you are trying to identify and draw bounding boxes around connected components in a binary image. You've mentioned using bwlabel and regionprops, but there seems to be a discrepancy in how they are being used in conjunction with the variable FeatureMap.
To clarify, bwlabel is a MATLAB function that labels connected components in a binary image, and regionprops computes properties of these labeled regions, including their bounding boxes. It's important to use the labeled image output from bwlabel as the input to regionprops.
Here's the steps with the corrected code to help you with your task:
- Read your RGB image into MATLAB.
- Convert the RGB image to grayscale.
- Threshold the grayscale image to create a binary image.
- Use bwlabel to label the connected components in the binary image.
- Use regionprops to get the bounding boxes of the labeled regions.
- Display the binary image and draw the bounding boxes.
% Read the RGB image
rgbImage = imread('C:\Users\prabhats\Downloads\MATLAB CODES\image.png'); % Replace with your image path
% Convert the RGB image to grayscale
grayImage = rgb2gray(rgbImage);
% Choose a threshold value
thresholdValue = 128; % This is an example value; adjust it as needed
% Convert the grayscale image to a binary image using the threshold
Ibin = imbinarize(grayImage, thresholdValue/255);
[labeledImage, num] = bwlabel(Ibin);
s = regionprops(labeledImage, 'BoundingBox');
imshow(Ibin), title('Image with bounding box'); % Display the binary image
hold on;
% Loop through each region and draw the bounding box
for i = 1:length(s)
currbb = s(i).BoundingBox;
rectangle('Position', [currbb(1), currbb(2), currbb(3), currbb(4)], 'EdgeColor', 'g');
end
hold off;
Output Image:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1621158/image.png)
I hope it helps to resolve your issue!
1 Comment
Image Analyst
on 19 Feb 2024
It's not important to pass in the labeled image to regionprops. If you do you'll get a warning. It's fine to just pass in the binary image directly into regionprops.
s=regionprops(Ibin,'BoundingBox');
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!