how to plot the bounding box detected by regionprops in matlab in matlab

Here's an example code to plot the bounding box detected by regionprops in MATLAB:

main.m
% Read the image
img = imread('example.jpg');

% Convert image to grayscale
img_gray = rgb2gray(img);

% Binarize the image using Otsu's thresholding method
level = graythresh(img_gray);
img_bw = imbinarize(img_gray, level);

% Perform connected component analysis
cc = bwconncomp(img_bw);
stats = regionprops(cc, 'BoundingBox');

% Show the image with bounding boxes drawn
figure, imshow(img)
hold on
for idx = 1 : length(stats)
   bb = stats(idx).BoundingBox;
   rectangle('Position', [bb(1),bb(2),bb(3),bb(4)], 'EdgeColor', 'r', 'LineWidth', 2)
end
552 chars
22 lines

This code will read an example image, convert it to grayscale, binarize it using Otsu's thresholding method, and perform connected component analysis using bwconncomp. regionprops is used to detect bounding boxes for each connected component, which are then plotted on the original image using rectangle.

related categories

gistlibby LogSnag