Open In App

How to Partially Colored Gray Image in MATLAB?

Last Updated : 25 Oct, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Partially colored images are a common way of enhancing the objects within the image. It is sometimes used as a tool to emphasize the presence of certain objects within the scene. And the processing required to create one is negligible, in contrast to the effect it produces. In this article you will learn how to convert an colored image to an partly colored one using MATLAB.

Example 1:

Matlab




% MATLAB program for Partially Colored
% Gray Image in MATLAB
  img = imread('test.jpg');
  R = img(:,:,1); % RED component
  G = img(:,:,2); % GREEN component
  B = img(:,:,3); % BLUE component
 
% RGB to Gray scale Image
  GS = rgb2gray(img);
  R1 = GS;
  G1 = GS;
  B1 = GS;
 
% Importing the mask
  mask = imread('mask.jpg');
  mask_grey = rgb2gray(mask);
  mask_bw = imbinarize(mask_grey);
 
% Find Index
  X = find(mask_bw==0);
  R1(X) = R(X);
  G1(X) = G(X);
  B1(X) = B(X);
 
% Create a RGB matrix
  C = zeros(size(img));
  C(:,:,1) = R1;
  C(:,:,2) = G1;
  C(:,:,3) = B1;
 
  C = uint8(C);
 
  figure,imshow(C);


Output:

For demonstration we would be using the following image:

 

During the process we would also be requiring a mask for the above image, which is:

 

The above mask has been created using photoshop, but could also be made programmatically in case of non-complex objects within the image. In the case of complex objects either feature extraction, contour detection, logical operations, or flood fill are used to create masks as producing them using programming is impractical. 

 

The images’ background changed from pink color to grey. This is because of the mask, which turned all the region in white (or region not black) to grayscale, and kept the region in black unchanged.

Explanation:

Firstly, we imported the test.jpg image. Then changed the color mode of the image from RGB to L (or Grayscale) using rgb2gray function. After which the mask was imported and then converted to grayscale, and then to black and white color mode. This is to ensure that the mask is bilevel as it is required to partition the regions of the image. Then all the regions within the mask containing the intensity 0 is determined and the result is stored in an variable X. This variable is used in all three RGB channels, and color is added to those places. In the end all 3 channels are concatenated into an RGB matrix which is later used to create the final image. The final image thus contains the ROI or the object colored, and the rest of the image in grey.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads