Auto Crop the image

40 次查看(过去 30 天)
Swapnil Rane
Swapnil Rane 2018-4-26
编辑: DGM 2023-1-11
How can I automatically crop these types of images, to get just the rectangle part?

采纳的回答

NISARGA G K
NISARGA G K 2018-4-30
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 个评论
Imran Riaz
Imran Riaz 2023-1-11
Error using rectangle
Value must be a 4 element vector
DGM
DGM 2023-1-11
编辑:DGM 2023-1-11
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);

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Image Segmentation and Analysis 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by