How to remove image background color in MATLAB

Wrench image with green background

I want to remove the green pixels in this image and replace it with a white background as a preliminary step in order to make caries detection in this image in order to detect only the wrench. I converted it to 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)
+4
source share
2 answers

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

+7
source

, , , . :

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

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

, . , , newV = (1) * vChannel; , , (: HSV = 1).

( , ) .

, 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);

H.

+3

Source: https://habr.com/ru/post/1692206/


All Articles