Search code examples
imagematlabimage-processingcrop

Cropping an image with imcrop() in matlab


I'm having trouble in cropping an image in MATLAB. The code is as follows:

n = 128;
% M0 = rescale(imcrop(x_gray,n));
[xx, xy] = size(x_gray);
M0 = rescale(imcrop(x_gray, 1, 1, n, n));

The size of x_gray is 384x512:

>> size(x_gray)
ans =
   384   512

imcrop() gives the following error:

Attempted to access spatial_rect(4); index out
of bounds because numel(spatial_rect)=1.

Error in imcrop (line 128)
pixelHeight = spatial_rect(4) *
pixelsPerVerticalUnit;

Why is the index out of bounds? The syntax of imcrop is:

B = imcrop(A,[xmin ymin width height]);

Solution

  • I get the same error as you, because the syntax you use is incorrect. Place the coordinates of your rectangle (i.e. 1,1,n,n) inside square brackets and it should work:

    M0 = rescale(imcrop(x_gray, [1 1 n n]));