MATLAB: How can imfill a objects when they are in the edges of main image

imfill object

hi,
I have Two rectangles 200X300 and 300X100 in the edges as shown below. I need to imfill in side the objects edge shape only. I have try use the regular imfill but doesn't work with me. Could you please help me??p.jpg

Best Answer

Close the contours then fill. Assuming the lines reach the edge lines:
% Make top line white:
col1 = find(binaryImage(1, :), 1, 'first')
col2 = find(binaryImage(1, :), 1, 'last')
binaryImage(1, col1:col2) = true;
% Make bottom line white:
col1 = find(binaryImage(end, :), 1, 'first')
col2 = find(binaryImage(end, :), 1, 'last')
binaryImage(end, col1:col2) = true;
% Make right line white:
row1 = find(binaryImage(:, end), 1, 'first')
row2 = find(binaryImage(:, end), 1, 'last')
binaryImage(row1:row2, end) = true;
binaryImage = imfill(binaryImage, 'holes');
If the lines don't reach the edges, then you'd need to use bwmorph() to find endpoints, then use bwlabel() to identify separate/distinct blobs, then construct a line between the two end points of each blob using polyfit(). Then write those lines into the image, then finally call imfill(). This is a more complicated algorithm but certainly doable in a few lines of code.
Post your original image (not a screenshot) if you still have trouble.