MATLAB: Auto Crop the image

cropimage

How can I automatically crop these types of images, to get just the rectangle part?

Best Answer

I understand that you would like to crop the rectangular object from the image automatically. I hope the following code would help you do the same
% Read the image
grayImage = imread(filename);
% Display the image.
imshow(grayImage);
S = regionprops(grayImage,'BoundingBox','Area');
[MaxArea,MaxIndex] = max(vertcat(S.Area));
imshow(grayImage,'InitialMagnification',20)
%// Highlight the required object
hold on
rectangle('Position',S(MaxIndex).BoundingBox,'LineWidth',2,'EdgeColor','y')
Length = S(MaxIndex).BoundingBox(3);
Height = S(MaxIndex).BoundingBox(4);
% Cropping the image
% Get all rows and columns where the image is nonzero
[nonZeroRows,nonZeroColumns] = find(grayImage);
% Get the cropping parameters
topRow = min(nonZeroRows(:));
bottomRow = max(nonZeroRows(:));
leftColumn = min(nonZeroColumns(:));
rightColumn = max(nonZeroColumns(:));
% Extract a cropped image from the original.
croppedImage = grayImage(topRow:bottomRow, leftColumn:rightColumn);
% Display the original gray scale image.
figure
imshow(croppedImage, []);