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
댓글 수: 0
답변 (2개)
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
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Convert Image Type에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!