Effacer les filtres
Effacer les filtres

Auto Crop the image

40 vues (au cours des 30 derniers jours)
Swapnil Rane
Swapnil Rane le 26 Avr 2018
Modifié(e) : DGM le 11 Jan 2023
How can I automatically crop these types of images, to get just the rectangle part?

Réponse acceptée

NISARGA G K
NISARGA G K le 30 Avr 2018
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, []);
  2 commentaires
Imran Riaz
Imran Riaz le 11 Jan 2023
Error using rectangle
Value must be a 4 element vector
DGM
DGM le 11 Jan 2023
Modifié(e) : DGM le 11 Jan 2023
You're feeding the script (specifically regionprops()) an RGB image. Don't do that. It will segment an RGB image as if it were a 3D volumetric image.
If your goal is to autocrop borders from color images, it would be necessary to have a description of what defines the crop area in your images specifically, and changes would need to be made to make the above script work.
% Read the image
rawImage = imread('op3.png');
% use some means to reduce the image to a 2D binary mask
% how this is done depends on what defines the background
if size(rawImage,3) == 3
grayImage = rgb2gray(rawImage);
elseif size(rawImage,3) == 1
grayImage = rawImage;
else
error('not a supported image')
end
mask = grayImage > 0;
% segment the image, find the largest object
S = regionprops(mask,'BoundingBox','Area');
[MaxArea,MaxIndex] = max(vertcat(S.Area));
rect = S(MaxIndex).BoundingBox;
% Display the image; highlight the largest object
imshow(grayImage); hold on
rectangle('Position',rect,'LineWidth',2,'EdgeColor','y')
hold off
% Extract a cropped image from the original.
croppedImage = imcrop(rawImage,rect);
% Display the cropped image.
imshow(croppedImage);

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Image Segmentation and Analysis dans Help Center et File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by