Decision
There are two main problems in your solution:
morphological operations must be performed after processing, since some of the background pixels are not green (some of them are black).
it would be easier to add a white background to the rgb space.
the code
I suggest the following solution:
%generates mask of forground
fgMask = ~(hsv(:,:,1) > 0.25 & hsv(:,:,1) < 0.41);
CC = bwconncomp(fgMask);
numOfPixels = cellfun(@numel,CC.PixelIdxList);
[~,indexOfMax] = max(numOfPixels);
fgMask = zeros(size(fgMask));
fgMask(CC.PixelIdxList{indexOfMax}) = 1;
%morphological operations
fgMask = imopen(fgMask,strel('disk',2));
fgMask = imclose(fgMask,strel('disk',5));
%updating image in RGB space
rChannel = image(:, :, 1); rChannel(~fgMask) = 255;
gChannel = image(:, :, 2); gChannel(~fgMask) = 255;
bChannel = image(:, :, 3); bChannel(~fgMask) = 255;
image = cat(3, rChannel, gChannel, bChannel);
%display image
imshow(image)
Result
source
share