How to remove the white background blobs touching the border of the image?

11 views (last 30 days)
After processing the image, I need to remove the white background which surrounds the black area in the binary image.
I would like to keep the dimensions of the image, so how can I change the white background, that is touching the edge of the image, to black?

Accepted Answer

Image Analyst
Image Analyst on 18 May 2022
mask = imclearborder(mask);

More Answers (1)

DGM on 18 May 2022
Edited: DGM on 18 May 2022
I don't know why you have a big white border on your image, or why your binarized image is uint8 RGB -- or why the apparent pixels in the image are larger than the image pixels (i.e. it appears upscaled). Did you save the image by saving the figure? If so, don't do that. Save the image with imwrite(). If you saved the image from a figure, it's geometry will be lost. It won't have the same resolution anymore, and if there's padding added, there's no way to know how much padding there is unless the padding is a different color than the image periphery.
Alternatively, maybe it appears upscaled because it's just been dilated with a 3x3 strel. I can't know.
Either way, the task is still unclear. You have this image
A = imread('');
A = rgb2gray(A)>128; % why is this RGB?
You can try to remove the white pixels connected to the image border:
% remove all border-connected objects
B = imclearborder(A);
Or you can try to remove only full edge vectors to retain some edge detail
% remove only full edge vectors
C = A;
fullrows = all(C,2);
fullcols = all(C,1);
C(:,fullcols) = 0;
C(fullrows,:) = 0;
But again, the cause for the white border is not clear, so it's not clear how much of it should be removed.
Image Analyst
Image Analyst on 19 May 2022
If you have the situation like the second image @DGM showed, where there is an artificial "edge" that is well within the borders of the image, you can use find() to find the upper left and lower right corners of the white regions and then crop the image so that now the white edges are on the edge of the cropped image. Then you can use imclearborder.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!