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

3 次查看(过去 30 天)
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

回答(2 个)

Simon Chan
Simon Chan 2022-10-5
use function bwateafilt

Ergin Sezgin
Ergin Sezgin 2022-10-5
编辑:Ergin Sezgin 2022-10-5
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

类别

Help CenterFile Exchange 中查找有关 Convert Image Type 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by