MATLAB: How to further clean up a binary image

binarycolor thresholder

Trying to further clean up a binary image, and I've attached the image to this question. I've done a color thresholding based on the Color Thresholder app and clicked "Show Binary":
function [BW,maskedRGBImage] = createMask(RGB)
%createMask Threshold RGB image using auto-generated code from colorThresholder app.
% [BW,MASKEDRGBIMAGE] = createMask(RGB) thresholds image RGB using
% auto-generated code from the colorThresholder app. The colorspace and
% range for each channel of the colorspace were set within the app. The
% segmentation mask is returned in BW, and a composite of the mask and
% original RGB images is returned in maskedRGBImage.
% Auto-generated by colorThresholder app on 02-Feb-2021
%------------------------------------------------------
% Convert RGB image to chosen color space
I = RGB;
% Define thresholds for channel 1 based on histogram settings
channel1Min = 0.000;
channel1Max = 255.000;
% Define thresholds for channel 2 based on histogram settings
channel2Min = 0.000;
channel2Max = 13.000;
% Define thresholds for channel 3 based on histogram settings
channel3Min = 0.000;
channel3Max = 255.000;
% Create mask based on chosen histogram thresholds
sliderBW = (I(:,:,1) >= channel1Min ) & (I(:,:,1) <= channel1Max) & ...
(I(:,:,2) >= channel2Min ) & (I(:,:,2) <= channel2Max) & ...
(I(:,:,3) >= channel3Min ) & (I(:,:,3) <= channel3Max);
BW = sliderBW;
% Initialize output masked image based on input image.
maskedRGBImage = RGB;
% Set background pixels where BW is false to zero.
maskedRGBImage(repmat(~BW,[1 1 3])) = 0;
end
This gets me closer, but is there a way I can refine this so that the area around the round/circle elements are black, but leaving the round/circle elements as they are?

Best Answer

You probably don't need the color thresholder. You can probably just do
grayImage = rgbImage(:, :, 2);
binaryImage = grayImage > someValue;
binaryImage = binaryImage & ~bwareafilt(binaryImage, 1) % Erase biggest blob which surrounds all the circular dark areas.
Related Question