Search code examples
imagematlabcrop

MATLAB - How can I crop some part of an image from .fig file and save it as .mat?


I have a .fig file. I put the 32x32 square on the image where I want. I write this code:

h = imrect(gca,[1 1 32 32]);

However I don't crop 32x32 part of the image. How to crop and save as .mat from .fig?


Solution

  • You can use the getPosition property of imrect object. If you are working with a .fig file, you can initially use the getimage function to get the image from the Image handle.

    %% If you are working with a image file.    
    %Sample image.
    %I = imread('cameraman.tif');
    
    %Display image.
    %imshow(I);
    
    %% If you are working with a .fig file. 
    %In the following example, yourfile.fig is cameraman.tif previously saved as a .fig file.
    I = open('yourfile.fig')
    I = getimage(I); 
    
    %Draw rectangle.
    h = imrect(gca,[100 30 40 32]);
    
    %Crop rectangle.
    J=imcrop(I,h.getPosition);
    
    %Show rectangle.
    imshow(J);
    
    %Save as .mat file
    save('mymatfile.mat','J');
    

    Initial image:

    enter image description here

    imrect object added:

    enter image description here

    Cropped element:

    enter image description here