I want to remove the green pixels in this image and replace it with white background as a preliminary step to do canny detection on this picture to detect only the spanner. I converted it into hsv and considered h without green as follows, But didn't work. Please Help.
image = imread('F:\03.jpg');
hsv = rgb2hsv(image);
hChannel = hsv(:, :, 1);
sChannel = hsv(:, :, 2);
vChannel = hsv(:, :, 3);
newH = hsv(:,:,1) > 0.25 & hsv(:,:,1) < 0.41;
newV = (0.1) * vChannel; % I am trying to change brightness
newHSVImage = cat(3, newH, sChannel, newV);
newRGBImage = hsv2rgb(newHSVImage);
imshow(newRGBIMage)
Solution
There are two main issues with your solution:
post-processing morphological operations are required, since some of the background pixels are not green (some of them are black).
it would be easier to add the white background on the rgb space.
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