Filter löschen
Filter löschen

Auto Crop the image

40 Ansichten (letzte 30 Tage)
Swapnil Rane
Swapnil Rane am 26 Apr. 2018
Bearbeitet: DGM am 11 Jan. 2023
How can I automatically crop these types of images, to get just the rectangle part?

Akzeptierte Antwort

NISARGA G K
NISARGA G K am 30 Apr. 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 Kommentare
Imran Riaz
Imran Riaz am 11 Jan. 2023
Error using rectangle
Value must be a 4 element vector
DGM
DGM am 11 Jan. 2023
Bearbeitet: DGM am 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);

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by