Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove colour background of an image in MATLAB

Picture of a Spanner with Green Background

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)
like image 611
Image Check Avatar asked Dec 24 '22 11:12

Image Check


2 Answers

Solution

There are two main issues with your solution:

  1. post-processing morphological operations are required, since some of the background pixels are not green (some of them are black).

  2. 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

enter image description here

like image 93
ibezito Avatar answered Dec 26 '22 00:12

ibezito


You don't seem to understand what you are doing. With comments:

% Select only green indexes
newH = hsv(:,:,1) > 0.25 & hsv(:,:,1) < 0.41;

% Change brigthness of the whole image
newV = (0.1) * vChannel; 

What your code does is, gets the logical index of all green pixels, and reduces brigthness of the whole image. Then, you use the logical indexes as color value, thus, if you do newV = (1) * vChannel; and plot, you will realize that all your green is now red (red: HSV=1).

What you want is select the green, and reduce the brightness (or whatever you want to do) of specifically the green.

for that, do:

% Select only green indexes
green_index = hsv(:,:,1) > 0.25 & hsv(:,:,1) < 0.41;
% change the brigtness of those specific pixels
newV=vChannel;
newV(green_index)=0.1*newV(green_index);

newHSVImage = cat(3, hChannel, sChannel, newV);

enter image description here

You may need to tune the range of your green detection in H.

like image 34
Ander Biguri Avatar answered Dec 26 '22 00:12

Ander Biguri