MATLAB: Extract the INNER white region of an image with black and white intersection.

8 or 4-connectedimage analysisimage processingImage Processing Toolboximage segmentationMATLAB

Hello,
I would like to get the inner part of the white region in the image below, the region I want is the red rectangluar part (INNER part of the white region). I do not want the outter part of the white region.
However, with my code below, I can only get the out part of the white region, is there anyone can help me?
Thanks a lot.
%%%%%My code
I = imread(filename);
Igray = rgb2gray(I);
BW2 = Igray < 50;
% Detect rectangle region (inside the line)
BW2 = imclearborder(~BW2);
BW2 = bwareafilt(BW2,1);
% Calculate bounding box
props2= regionprops(BW2,'BoundingBox');
boundingBox2 = props2.BoundingBox;
figure
imshow(BW2)

Best Answer

First of all you don't need imclearborder because there is no part of your blob that touches the border. And after bwareafilt() you're probably still getting the original blob because some of the outer blobs are touching your inner blob by having the corners of the pixels touch. The default for bwareafilt() is 8-connected, which considers blobs touching on the diagonal to be the same blob. You should specify the "4-connected" option so that a blob is only connected if it's fully touching on the top, bottom, left, or right (not the diagonal/corner).