How to detect rectangle in an image then crop it out?

조회 수: 33 (최근 30일)
WanYu
WanYu 2020년 2월 20일
댓글: Akira Agata 2020년 3월 5일
Hi All,
I wish to detect the rectangle as shown below in the image. After that, I want to crop out what's only inside the rectangle part.
Anyone can teach me how?
First, I changed this coloured image into grayscale image then to binary image. Then, I tried using 'regionprops' with 'BoundingBox' to detect the presence of rectangle. However, the cropped image is not exactly the rectangle size.
PS. I do refer from someone else code.
% Find boundary box
props = regionprops(binaryImage, 'BoundingBox');
boundingBox = props.BoundingBox;
width = boundingBox(3);
height = boundingBox(4);
% Crop off the top, shaded portion of column headers,
% which are known to be a fixed 29% of the height of the box.
newHeight = height * (1 - 0.29)
% Make a new bounding box.
xLeft = boundingBox(1);
yTop = boundingBox(2);
boundingBox2 = [xLeft, yTop + 0.29 * height, width, newHeight];
% Crop the image
newGrayScaleImage = imcrop(grayImage, boundingBox2);
subplot(2, 3, 6);
imshow(newGrayScaleImage);
axis('on', 'image');
impixelinfo;
title('New Gray Scale Image', 'FontSize', fontSize);
Result:

채택된 답변

Akira Agata
Akira Agata 2020년 2월 25일
How about the following?
% Load the image and convert it to gray scale
I = imread('image.jpeg');
Igray = rgb2gray(I);
% Detect black line
BW = Igray < 10;
% Detect rectangle region (inside the line)
BW = imclearborder(~BW);
BW = bwareafilt(BW,1);
% Calculate bounding box
s = regionprops(BW,'BoundingBox');
% Crop the image
Icropped = imcrop(I,s.BoundingBox);
% Show the result
figure
imshow(Icropped)
  댓글 수: 5
WanYu
WanYu 2020년 3월 5일
Hi,
Can you please explain to me, why the repmat is using (1,1,3)?
Akira Agata
Akira Agata 2020년 3월 5일
This is because the array I is N x M x 3 (RGB) matrix. To apply immultiply to I, the N x M binary array BW should be expanded to N x M x 3. So I have applied repmat using [1,1,3].

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Image Processing Toolbox에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by