How to crop an image inside a boundary ?
14 views (last 30 days)
Show older comments
Warid Islam on 17 Jul 2019
I have an image from which I want to crop a certain portion of it. I drew the boundary at first. Below is the code:
img = imread('Intensity1.jpg');
% getting a segment
position = wait(h);
figure,imshow(region); title('Segmented Region');
% use bwperim rather than bwboundaries to get an Image of boundary.
boundImg = uint8(bwperim(rgb2gray(region),4));
boundImg(boundImg ~=0) = max(img(:));
figure, imshow(img + boundImg)
% save image without loosing information..
imwrite(img + boundImg, 'writeImg.jpg');
read = imread('writeImg.jpg');
isequal(read, img + boundImg)
The image is below:
I want to crop the portion of the image specified by the boundary above. I tried the following line of code but there is no change in the result.
Any suggestions would be very much appreciated. Thank you.
Divya Gaddipati on 24 Jul 2019
After getting the mask of the selected region from the above line in your code, you can use regionprops to obtain a rectangular box around the mask and then use imcrop to crop the image.
stats = regionprops(region, 'BoundingBox');
crop_region = stats.BoundingBox; % contains [top_left_x top_left_y width height]
cropped_img = imcrop(img, crop_region);
For more information on how to use regionprops and imcrop, refer to the following links:
Divya Gaddipati on 26 Jul 2019
I assume you are using the wait command to obtain the positions of the selected boundary from.
The drawfreehand command returns an object which contains the positions of the boundary you selected. Hence, instead of using wait command, you can directly access the "Position" parameter of your drawfreehand object (i.e, h).
position = h.Position;
Try the above line in place of "position = wait(h)".
For more information, refer to the "Output Arguments" section in the drawfreehand documentation.
More Answers (1)
Aytaç Tok on 12 Mar 2021
How can I get the object by auto cropping from a rgb picture. For example, there is a banana on the table and the background is black. I want to crop this picture and just take the banana and I want no background pixel at all. how can I do that
Find more on Region and Image Properties 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!