Change Background of Color Image into Grayscale in MATLAB


We can obtain grayscale color by setting RGB values to 128. This means all color channels will have the same intensity values.

The following MATLAB program illustrate the code for changing the background of a color image into grayscale.

Example

%MATLAB program to demonstrate changing color background into grayscale
% Read the input colored image
img1 = imread('https://www.tutorialspoint.com/assets/questions/media/14304-1687425236.jpg'); 
% Display the input color image
subplot(1, 2, 1); imshow(img1); title('Original Image');
% Create a binary mask of the background
BGMask = img1(:, :, 1) == img1(1, 1, 1) & ...
                 img1(:, :, 2) == img1(1, 1, 2) & ...
                 img1(:, :, 3) == img1(1, 1, 3);
% Place the background pixels to black in the color image
img2 = img1;
img2(repmat(BGMask, [1, 1, 3])) = 0;
% Display the black background image
subplot(1, 2, 2); imshow(img2); title('Black BG Image');
    

Output

Note - Use an image with a solid background to get the desired result.

Conclusion

In the above MATLAB program, we read the input colored image by using the “imread” function and show the original image by using the “imshow” function. Then, we create a binary mask of the background of the image, in this case we have assumed that the background is a solid color and we take the sample background from the top-left corner of the image. After that we set the background pixels to grayscale in the color image by setting the RGB value to 128. Finally, we display the image with grayscale background “img2” by using the “imshow” function.

Updated on: 18-Jul-2023

55 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements