MATLAB Answers

How to extract a particular colour from an RGB image?

29 views (last 30 days)
Dear all,
I want to extract a particular colour from an RGB image. If that specific colour is present in an image, I wish to replace it with a zero pixel intensity. In the figure below, the arrow points out the light red colour; here, I want to extract this particular light red colour from the image. If it is present in the image, I want to replace it with a zero intensity level with that particular colour.
How to make a logic to extract a particular colour from an image?

Accepted Answer

Walter Roberson
Walter Roberson on 5 Jun 2021
Edited: Walter Roberson on 5 Jun 2021
Not perfect, but it will give you a starting point.
filename = 'https://www.mathworks.com/matlabcentral/answers/uploaded_files/641315/f00167.png';
rgb = imread(filename);
HSV = rgb2hsv(rgb);
mask1 = HSV(:,:,1) < 0.2;
mask2 = HSV(:,:,2) > 0.3 & HSV(:,:,2) < 0.7;
mask3 = HSV(:,:,3) > 0.2 & HSV(:,:,3) < 0.6;
mask = mask1 & mask2 & mask3;
BW = bwareafilt(mask,[30 inf]);
filtered_RGB = rgb .* uint8(BW);
imshow(filtered_RGB)
  8 Comments

Sign in to comment.

More Answers (1)

Sulaymon Eshkabilov
Sulaymon Eshkabilov on 4 Jun 2021
(1) Image read: imread('traffic.png')
(2) Select and Find out the pixel value ranges of a red color, e.g.:
I = imread('traffic.png');
PXY = impixel(I); % Once done selecting enough number of pixel points, hit ENTER from keyboard
R = (PXY(:,1)); % G = (PXY(:,2)); B = (PXY(:,3)); % If interested in Green Or Blue
Rm=min(R); % Gm=min(G); Bm=min(B);
(3) Use logical indexing, e.g.:
RED = I(:,:,1);
GREEN = I(:,:,2);
BLUE = I(:,:,3);
RED(RED>=Rm)=0; % For RED color layer
GREEN(RED>=Rm)=0; % For GREEN color layer
BLUE(RED>=Rm)=0; % For BLUE color layer
NEW_Im(:,:,1) =RED;
NEW_Im(:,:,2) =GREEN;
NEW_Im(:,:,3) =BLUE;
imshow(NEW_Im), shg

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by