Change background of color image into grayscale in MATLAB
In this article, we will discuss how to change the background of a colour image into grayscale using MATLAB. We are focused on the RGB colour model. An RGB colour image is taken. The entire image is converted into grayscale except for the object highlighted in the image. We kept the colour of the flower yellow and converted the rest of the background into Grayscale.
This is the manually written function. It converts the colour image into grayscale first of all. A new colour image is created and all three channels (RGB) are assigned the values of the grayscale image(obtained in the first step). The idea is to keep the colour of the interesting portion of the image and keep the rest of the pixels as grayscale. We have noticed that for the central flower part, the Red intensity values are greater than equal to 110; the Green intensity values are greater than equal to 70 and the Blue intensity values are less than 90.
Upon completing the traversing and modifying the newly created image. We return the new image.
- Reading images: First, the input image is read and stored in a variable named K. Images are read into the MATLAB Environment using imread() function which takes filename with applicable extension as the argument. The given below syntax read JPEG image into the image array.
- Image is passed to utility function for modification.
- Showing images: Original and modified images are displayed. Images are shown into the MATLAB environment using the imtool() function. imtool opens a new Image Tool in an empty state. We can use the File menu options Open or Import from Workspace to choose an image for display.
- Utility function sets all 3 channel pixel intensities for the central flower part.
- Utility function sets all 3 channels pixel intensities the same for the rest of the background equal to a grayscale image.
Now, we have taken an example to change the background colour of an image.
(img(i,j,1)>=110 && img(i,j,2)>=70 && img(i,j,3)<90)
Figure: Original Colour image
Figure: Gray Background image