Search code examples
matlabimage-processingimage-effects

How can I change the background color of the image?


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)


Solution

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