0

I want to remove/change the background color of an image in Matlab.

Anyone know how to do this?

Here is an example image, I want to remove the green background color.


(source: frip.in)

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
kim
  • 73
  • 2
  • 7
  • do you know what color the background is? – Shai Nov 20 '14 at 06:25
  • No, I don't know. As there are different cases, some of them maybe green background color and some maybe others. Is there a way to do this? – kim Nov 20 '14 at 06:46
  • BTW, the background color maybe slightly different between different areas. Like the image shown above, some area are lighter green. – kim Nov 20 '14 at 06:48

1 Answers1

4

Simplest answer would be,

c = [70 100 70];
thresh = 50;
A = imread('image.jpg');
B = zeros(size(A));
Ar = A(:,:,1);
Ag = A(:,:,2);
Ab = A(:,:,3);
Br = B(:,:,1);
Bg = B(:,:,2);
Bb = B(:,:,3);
logmap = (Ar > (c(1) - thresh)).*(Ar < (c(1) + thresh)).*...
         (Ag > (c(2) - thresh)).*(Ag < (c(2) + thresh)).*...
         (Ab > (c(3) - thresh)).*(Ab < (c(3) + thresh));
Ar(logmap == 1) = Br(logmap == 1);
Ag(logmap == 1) = Bg(logmap == 1); 
Ab(logmap == 1) = Bb(logmap == 1);
A = cat(3 ,Ar,Ag,Ab);
imshow(A);

enter image description here

You should change c (background color) and thresh (threshold for c) and find the best that fits your background.

You can define B as your new background image. Fr example adding Bb(:,:) = 255;will give you a blue background.

enter image description here

You can even define B as an image.

In order to detect background you could find the color that is most used in the image, but that is not necessarily background I think.

Rashid
  • 4,326
  • 2
  • 29
  • 54
  • Thanks for your answer. What is C and thresh? Based on what rules to change these two value for other images? Thank you very much! – kim Nov 20 '14 at 07:44
  • 1
    c is the definition of the green color (define on [R G B] with a value from 0 to 255). Thresh is your threshold which define the separation between what in green and what is not. – R.Falque Nov 20 '14 at 07:51
  • I see. Thank you very much! Is there a way to change the color if we don't know what is the background color beforehand as there will be many images with different background color? Or just remove the background color? – kim Nov 21 '14 at 03:06
  • @Kim you can find the default background of an image by analyzing the histogram of you three RGB layers. – R.Falque Nov 21 '14 at 06:51
  • @R.Bergamote. one example code about finding the default background color of an image? Thanks – kim Nov 21 '14 at 09:12
  • @R.Bergamote do you know how to find the default background color? Thanks! – kim Jan 30 '15 at 08:37