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

12 ビュー (過去 30 日間)
Md 2022 年 10 月 4 日
編集済み: Ergin Sezgin 2022 年 10 月 5 日
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.
for i = 1:30
RGB = snapshot(cam);
% 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);
% 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);
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');
hold off

回答 (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

Community Treasure Hunt

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

Start Hunting!

Translated by