Search code examples
matlabimage-processingbackground-colorforeground

Background and foreground color changes


enter image description here

Hello i need to make background color black and foreground color white. As u can see i did this with transfering image to 2 dimension. I want to make this color changes in 3 dimension, so we are nor allowed to transfer it bw. Is there any way to do this ?

logo=imread('logo.png');

subplot(2,2,1); imshow(logo);

b=rgb2gray(logo);

subplot(2,2,2); imshow(b);

c=im2bw(b,0.92)

subplot(2,2,3); imshow(c);

c = 1-c;

subplot(2,2,4); imshow(c);


Solution

  • Preface:

    To set the pixel to white or black each layer of the pixel needs to be set to an intensity value of 0 (black) or 255 (white).

    White Pixel → rgb(255,255,255)
    Black Pixel → rgb(0,0,0)

    RGB-Image Layer Conventions

    The colon can be used to obtain all the indices in the 3rd dimension (grab all the layers). To grab one RGB-pixel in the top-left corner of the image:

    RGB_Pixel = Image(1,1,:); 
    

    Method 1:

    If you wish to retain the three colour channels you can use matrix indexing to change the white background to black. Matrix indexing can also be used to change anywhere that isn't white to white. This method may, unfortunately, break down if you have a coloured component with a 255 intensity component. This doesn't seem to be the case for your image though. You can use method 2 for a more safe approach.

    logo = imread('logo.png');
    [Image_Height,Image_Width,Depth]= size(logo);
    
    new_logo = zeros(Image_Height,Image_Width,Depth);
    
    new_logo(logo == 255) = 0;
    new_logo(logo ~= 255) = 255;
    
    imshow(new_logo);
    

    Method 2:

    Checks each pixel (RGB-triplet) using a set of for-loops that scan through the entire image. If the RGB-intensities of the pixel are rgb(255,255,255) then the pixels are set to 0 (black). If the RGB-intensities of the pixel are anything else the pixels are set to 255 (white). The ~ismember() function is used to check if the RGB-pixel has an intensity that is not 255 (not-white).

    logo = imread('logo.png');
    
    %Grabbing the size of the image%
    [Image_Height,Image_Width,~]= size(logo);
    
    
    for Row = 1: Image_Height
        for Column = 1: Image_Width
        
        %Grabbing RGB pixel%
        RGB_Pixel = logo(Row,Column,:);
        
        if(~ismember(255,RGB_Pixel))
        %RGB pixel is white change
        logo(Row,Column,:) = 255;
        else
        %RGB pixel is coloured change to black% 
        logo(Row,Column,:) = 0;
        end
        
        end
    end
    
    imshow(logo);
    

    Using the repmat() function is also a great solution that the above comment suggested. Which possibly may be the quickest method since you already have the code that generates one layer from the greyscale image.

    Ran using MATLAB R2019b