Clear Filters
Clear Filters

Fix bounding box in a image and save it

10 views (last 30 days)
Josep Llobet
Josep Llobet on 16 Mar 2022
Answered: Saffan on 28 Jun 2023
Hi there,
I am trying to fix a Bounding Box permanently in a image because to save it.
I used as usual hold on for graphic the bounding box, but I want to fix it in a image for then save it.
As example:
% Obtain image
krillin = imread("https://es.mathworks.com/responsive_image/150/150/0/0/0/cache/matlabcentral/profiles/22817879_1627284404454.jpg");
% Process it
krillin_grey = im2gray(krillin);
krillin_grey_imadj = imadjust(krillin_grey);
krillin_BW = imbinarize(krillin_grey_imadj);
krillin_BW_2 = imclearborder(~krillin_BW);
% Boca
krillin_BW_2_largest_fin = bwpropfilt(krillin_BW_2, "Area", 1, "largest");
% Obtain the Bounding box
BB_krillboca=regionprops(krillin_BW_2_largest_fin,'BoundingBox'); %<--- rellevant
% Show in the image
imshow(krillin)
hold on
rectangle('Position', BB_krillboca.BoundingBox+[-1 -1 +1 +1], 'EdgeColor','b', 'LineWidth', 1)
hold off
And I want to save just the bounding box in a zeros image:
zeros_krillin = zeros(size(krillin_BW_2_largest_fin));
imshow(zeros_krillin)
hold on
rectangle('Position', BB_krillboca.BoundingBox+[-1 -1 +1 +1], 'EdgeColor','b', 'LineWidth', 1)
hold off
I tried exportgraphics but the size is not the same when it is saved.
Thank you so much

Answers (1)

Saffan
Saffan on 28 Jun 2023
I understand that you want to save an image along with the bounding box without changing its size. This can be accomplished in the following way:
  • Get the figure using “getframe” function.
  • Convert it to an image using “frame2im” function.
  • Save it using “imwrite” function in the desired format.
Below is an example code snippet that demonstrates how to achieve this:
% Capture the figure with the drawn rectangle
f = getframe(gca);
% Convert it to an image
bounding_box_image = frame2im(f);
% Save the image with the bounding box
imwrite(bounding_box_image, 'bounding_box_image.png');
Refer to these links for more information:

Categories

Find more on Read, Write, and Modify Image in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!