Corp Image using Bounding Box

2 views (last 30 days)
Muhammad
Muhammad on 6 Jul 2023
Commented: Muhammad on 6 Jul 2023
I have image which is attached. I am calculating the bounding box around each object (colored area) and then crop that region.
grayImage = rgb2gray(H);
mask = grayImage > 0;
S = regionprops(mask,'BoundingBox','Area');
[MaxArea,MaxIndex] = max(vertcat(S.Area));
rect = S(MaxIndex).BoundingBox;
but when I draw Image I got this.
I want to select the whole region and then crop shown in the attached image.
H = imresize(imcrop(H,rect),[224 224]);

Answers (1)

Sivsankar
Sivsankar on 6 Jul 2023
Hi Muhammed,
Try this modified piece of code
grayImage = rgb2gray(H);
mask = grayImage > 0;
S = regionprops(mask, 'BoundingBox', 'Area');
[MaxArea, MaxIndex] = max(vertcat(S.Area));
rect = S(MaxIndex).BoundingBox;
% Select the whole region
rect(1:2) = [1 1]; % Set the top-left corner of the bounding box to (1, 1)
rect(3:4) = size(H); % Set the width and height of the bounding box to match the image size
% Crop the selected region and resize it to [224, 224]
croppedImage = imresize(imcrop(H, rect), [224, 224]);
By setting the top-left corner of the bounding box to (1, 1) and the width and height to match the image size, you are essentially selecting the whole region. Then, you can use imcrop to crop the selected region and resize it to a desired size using imresize.
Please note that this code assumes H is the original image you want to crop.
I guess this is how you wanted to crop. Reply if this is not in the way that you wanted
  1 Comment
Muhammad
Muhammad on 6 Jul 2023
@J Thank you for reply. This is not what I want to crop both regions like the example.

Sign in to comment.

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!