detect the largest red object, its centroid and put bounding box around it

3 views (last 30 days)
This code detects red objects, their centroid and put bouding box around them, instead of doing this, I want it to detect the largest red object only, get its centroid and put bounding box around it. It shouldn't identify any red object if it's not the largest in the image.
cam=webcam
for i = 1:30
RGB = snapshot(cam);
size(RGB)
% defining redness of image
r = RGB(:, :,1); g = RGB(:, : ,2); b = RGB(:, :, 3);
% create a binary image (heuristic)
red = (r > 2*g) & (r > 2*b) & (r > 30);
imshow(red)
% group all red object within 5 pixels of each other as one object
se = strel('disk',5);
red = imclose(red,se);
% delete all objects smaller than 35 pixels in area
red = bwareaopen(red,35);
% getting the centroid & creating bounding box
stats = regionprops(bwlabel(red),'BoundingBox','centroid');
S = vertcat(stats.Centroid);
figure
imshow(RGB); % show original image
hold on
for object = 1:length(stats)
bb = stats(object).BoundingBox;
bc = stats(object).Centroid;
rectangle('Position', bb, 'EdgeColor', 'r', 'LineWidth', 2) % draw bounding box
plot(bc(1), bc(2), '-m+')
% mark centroid (x, y) with '+'
a=text(bc(1)+15,bc(2), strcat('X: ', num2str(round(bc(1))), ' Y: ', num2str(round(bc(2)))));
set(a, 'FontName', 'Arial', 'FontWeight', 'bold', 'FontSize', 12, 'Color', 'yellow');
end
hold off
end

Answers (2)

Simon Chan
Simon Chan on 5 Oct 2022
use function bwateafilt

Ergin Sezgin
Ergin Sezgin on 5 Oct 2022
Edited: Ergin Sezgin on 5 Oct 2022
You can use regionprops function as the following to get area value of each individual region and then sort the table and get the first row which has the largest area in the set.
rpOutput = regionprops('table',BW,'Area','BoundingBox','Centroid')
rpOutput = sortrows(rpOutput,'Area','descend')
largestObject = rpOutput(1,:);
Good luck

Categories

Find more on Convert Image Type in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!