フィルターのクリア

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 Center および File ExchangeImage Segmentation and Analysis についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by