Auto Crop the image
38 次查看(过去 30 天)
显示 更早的评论
How can I automatically crop these types of images, to get just the rectangle part?
0 个评论
采纳的回答
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 个评论
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 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!