How can I select a region of an image and save it in a new file using the Image Processing Toolbox?

6 views (last 30 days)

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 27 Jun 2009
This change has been incorporated into the documentation in Release 14 Service Pack 3 (R14SP3). For previous releases, read below for any additional information:
The following is an example of extracting a region from a graphic file and saving it to a new file using the Image Processing Toolbox :
% Read image from graphics file.
im= imread('trees.tif');
% Display image
imshow(im);
% Use GETRECT to select a rectangle region by using the mouse
sp=getrect;
% Get the x and y co-ordinates
sp(1) = max(floor(sp(1)), 1); %xmin
sp(2) = max(floor(sp(2)), 1);%ymin
sp(3)= min(ceil(sp(1) + sp(3))); %xmax
sp(4)=min(ceil(sp(2) +sp(4))); %ymax
% Index into the original image to create the new image
MM=im(sp(2):sp(4), sp(1): sp(3),:);
image(MM)
% Write image to graphics file.
imwrite(MM,'trees2.tif')
Note that the above code requires the Image Processing Toolbox (which provides trres.tif and the IMSHOW function). If you do not have the Image Processing Toolbox, you may display images with the IMAGE or IMAGESC functions, use GINPUT or RBBOX to obtain image coordinates form the user, and should modify some properties of the image or figure to display it properly, as the following example shows:
% Read image from graphics file.
im = imread(street2.jpg');
% Display image with true aspect ratio
image(im); axis image
% Use ginput to select corner points of a rectangular
% region by pointing and clicking the mouse twice
p = ginput(2);
% Get the x and y corner coordinates as integers
sp(1) = min(floor(p(1)), floor(p(2))); %xmin
sp(2) = min(floor(p(3)), floor(p(4))); %ymin
sp(3) = max(ceil(p(1)), ceil(p(2))); %xmax
sp(4) = max(ceil(p(3)), ceil(p(4))); %ymax
% Index into the original image to create the new image
MM = im(sp(2):sp(4), sp(1): sp(3),:);
%Display the subsetted image with appropriate axis ratio
figure; image(MM); axis image
% Write image to graphics file.
imwrite(MM,'street2_cropped.tif')

More Answers (0)

Categories

Find more on Images 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!