Background and foreground color changes


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;


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,:);
    %RGB pixel is white change
    logo(Row,Column,:) = 255;
    %RGB pixel is coloured change to black% 
    logo(Row,Column,:) = 0;


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

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top