Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
Identify colors in an RGB image

Subject: Identify colors in an RGB image

From: Daphne

Date: 4 Jun, 2010 10:43:04

Message: 1 of 10


I would like to generate a histogram with the colors present in an RGB image.

Specifically, that image is and addition of two other images: one that I define as the red path and the other is the green. So I end up with, red, green, and shades of yellow from overlaps in the images.
What I would like to eventually know is how much red, how much green, and mostly how much yellow I have, and perhaps also be able to filter the merged image by color.

Does any one have an idea how to do this?
I've tried imhist, but couldn't quite figure out what to do with it.

Thanks in advance,
Daphne

Subject: Identify colors in an RGB image

From: ImageAnalyst

Date: 4 Jun, 2010 11:07:05

Message: 2 of 10

Daphne
You have to extract each color band individually and then histogram
them, like in this demo:

clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
imtool close all; % Close all imtool figures.
clear; % Erase all existing variables.
workspace; % Make sure the workspace panel is showing.
fontSize = 20;

% Read in standard MATLAB color demo image.
rgbImage = imread('peppers.png');
[rows columns numberOfColorBands] = size(rgbImage);
subplot(2, 2, 1);
imshow(rgbImage, []);
title('Original Color Image', 'Fontsize', fontSize);
set(gcf, 'Position', get(0,'Screensize')); % Maximize figure.

% Extract the individual color planes.
redPlane = rgbImage(:, :, 1);
greenPlane = rgbImage(:, :, 2);
bluePlane = rgbImage(:, :, 3);

% Let's get its histograms.
[pixelCountR grayLevelsR] = imhist(redPlane);
subplot(2, 2, 2);
bar(pixelCountR, 'r');
title('Histogram of red plane', 'Fontsize', fontSize);
xlim([0 grayLevelsR(end)]); % Scale x axis manually.

[pixelCountG grayLevelsG] = imhist(greenPlane);
subplot(2, 2, 3);
bar(pixelCountG, 'g');
title('Histogram of green plane', 'Fontsize', fontSize);
xlim([0 grayLevelsG(end)]); % Scale x axis manually.

[pixelCountB grayLevelsB] = imhist(bluePlane);
subplot(2, 2, 4);
bar(pixelCountB, 'b');
title('Histogram of blue plane', 'Fontsize', fontSize);
xlim([0 grayLevelsB(end)]); % Scale x axis manually.

Subject: Identify colors in an RGB image

From: Daphne

Date: 4 Jun, 2010 14:07:04

Message: 3 of 10


Thanks so much IA!
That works great for the three colors RGB.

What do I do if I need the yellow? the overlap regions of the red and the green...
For me the blue is empty, so perhpas there's a way to use that channel for the overlap or for detecting yellow directly?

Daphne


ImageAnalyst <imageanalyst@mailinator.com> wrote in message <1dd992dd-9e52-4473-8a2d-df612a9c31c6@r5g2000yqr.googlegroups.com>...
> Daphne
> You have to extract each color band individually and then histogram
> them, like in this demo:
>
> clc; % Clear the command window.
> close all; % Close all figures (except those of imtool.)
> imtool close all; % Close all imtool figures.
> clear; % Erase all existing variables.
> workspace; % Make sure the workspace panel is showing.
> fontSize = 20;
>
> % Read in standard MATLAB color demo image.
> rgbImage = imread('peppers.png');
> [rows columns numberOfColorBands] = size(rgbImage);
> subplot(2, 2, 1);
> imshow(rgbImage, []);
> title('Original Color Image', 'Fontsize', fontSize);
> set(gcf, 'Position', get(0,'Screensize')); % Maximize figure.
>
> % Extract the individual color planes.
> redPlane = rgbImage(:, :, 1);
> greenPlane = rgbImage(:, :, 2);
> bluePlane = rgbImage(:, :, 3);
>
> % Let's get its histograms.
> [pixelCountR grayLevelsR] = imhist(redPlane);
> subplot(2, 2, 2);
> bar(pixelCountR, 'r');
> title('Histogram of red plane', 'Fontsize', fontSize);
> xlim([0 grayLevelsR(end)]); % Scale x axis manually.
>
> [pixelCountG grayLevelsG] = imhist(greenPlane);
> subplot(2, 2, 3);
> bar(pixelCountG, 'g');
> title('Histogram of green plane', 'Fontsize', fontSize);
> xlim([0 grayLevelsG(end)]); % Scale x axis manually.
>
> [pixelCountB grayLevelsB] = imhist(bluePlane);
> subplot(2, 2, 4);
> bar(pixelCountB, 'b');
> title('Histogram of blue plane', 'Fontsize', fontSize);
> xlim([0 grayLevelsB(end)]); % Scale x axis manually.

Subject: Identify colors in an RGB image

From: Daphne

Date: 4 Jun, 2010 14:23:21

Message: 4 of 10


Actually, maybe I'm adding the images wrong?
If I see yellow, there should be a blue component...

I upload an RGB image and define its (:,:,2:3) = 0 (that's my red channel)
then upload another RGB image and define (:,:,[1,3]) = 0 (green channel)
then I use imadd to combine them (just a vectorial addition, I know), and so I don't get anything in the blue channel, although when I imshow the merge there is yellow.

Ideas?

Daphne

Subject: Identify colors in an RGB image

From: ImageAnalyst

Date: 4 Jun, 2010 14:47:13

Message: 5 of 10

Daphne:
See my color detection demo:
http://www.mathworks.com/matlabcentral/fileexchange/26420-simplecolordetection
You can adapt it to find yellow instead of red.

Now that I'm on my other computer, I found my better demo of color
histogramming:

%-------------------------------------------------------------------------------------------------------------
% Calculates and displays histograms of a color image.
% Each color channel (red, green, blue) is extracted and its histogram
calculated and displayed.
% Written by Image Analyst, Jan. 2010.

clc;
clear;
close all;
workspace;

% Change the current folder to the folder of this m-file.
% (The line of code below is from Brett Shoelson of The Mathworks.)
if(~isdeployed)
cd(fileparts(which(mfilename)));
end

% Set up sizes for the captions and text we will show on the figure.
captionFontSize = 20; % Font size for headers/captions of images.
axisFontSize = 14; % Font size for axes of the histogram plots.

% Set the initial default directory to the one containing the
% standard demo images for the MATLAB Image Processing Toolbox.
folder = 'C:\Program Files\MATLAB\R2010a\toolbox\images\imdemos';
if ~exist(folder, 'dir')
folder = pwd;
end
filePattern = fullfile(folder, '*.*');

% Ask user to browse for the image file.
[baseFileName, folder] = uigetfile(filePattern, 'Specify an image
file');
% Construct the full file name.
fullImageFileName = fullfile(folder, baseFileName);


%------------------------------------
% Read the image into an array.
rgbImage = imread(fullImageFileName);
%------------------------------------


% Check to see if it is color or monochrome.
[rows columns numberOfColorChannels] = size(rgbImage);
if strcmpi(class(rgbImage), 'uint8')
% Flag for 256 gray levels.
eightBit = true;
else
eightBit = false;
end
% If it's monochrome, convert it to color.
if numberOfColorChannels == 1
rgbImage = cat(3, rgbImage, rgbImage, rgbImage);
end

% Display the original RGB image.
subplot(3,4,1);
imshow(rgbImage);
% Maximize figure.
set(gcf, 'Position', get(0, 'ScreenSize'));
% drawnow; % Make it display immediately.
if numberOfColorChannels > 1
title('Original Color Image', 'FontSize', captionFontSize);
else
title('Original Monochrome Image (converted to color)', 'FontSize',
captionFontSize);
end

% Extract out the individual color channels
redChannel = rgbImage(:, :, 1);
greenChannel = rgbImage(:, :, 2);
blueChannel = rgbImage(:, :, 3);

% Display the red channel image.
subplot(3,4,2);
imshow(redChannel);
title('Red Channel Image', 'FontSize', captionFontSize);
% Display the green channel image.
subplot(3,4,3);
imshow(greenChannel);
title('Green Channel Image', 'FontSize', captionFontSize);
% Display the blue channel image.
subplot(3,4,4);
imshow(blueChannel);
title('Blue Channel Image', 'FontSize', captionFontSize);

% Calculate the histogram of the red channel.
hR = subplot(3, 4, 6);
[countsR, grayLevelsR] = imhist(redChannel);
maxGLValueR = find(countsR > 0, 1, 'last');
maxCountR = max(countsR);
% Plot the histogram of the red channel.
bar(countsR, 'r');
grid on;
xlabel('Red Gray Levels', 'FontSize', axisFontSize);
ylabel('Red Pixel Count', 'FontSize', axisFontSize);
title('Histogram of Red Channel', 'FontSize', captionFontSize);

% Calculate the histogram of the green channel.
hG = subplot(3, 4, 7);
[countsG, grayLevelsG] = imhist(greenChannel);
maxGLValueG = find(countsG > 0, 1, 'last');
maxCountG = max(countsG);
% Plot the histogram of the green channel.
bar(countsG, 'g');
grid on;
xlabel('Green Gray Levels', 'FontSize', axisFontSize);
ylabel('Green Pixel Count', 'FontSize', axisFontSize);
title('Histogram of Green Channel', 'FontSize', captionFontSize);

% Calculate the histogram of the blue channel.
hB = subplot(3, 4, 8);
[countsB, grayLevelsB] = imhist(blueChannel);
maxGLValueB = find(countsB > 0, 1, 'last');
maxCountB = max(countsB);
% Plot the histogram of the blue channel.
bar(countsB, 'b');
grid on;
xlabel('Blue Gray Levels', 'FontSize', axisFontSize);
ylabel('Blue Pixel Count', 'FontSize', axisFontSize);
title('Histogram of Blue Channel', 'FontSize', captionFontSize);

% Set all axes to be the same height.
maxCount = max([maxCountR, maxCountG, maxCountB]);
% Set all axes to be the same width.
maxGL = max([maxGLValueR, maxGLValueG, maxGLValueB]);
if eightBit
maxGL = 255;
end
% If there's a big spike at the last bin, it can be hard to see
because
% of the box around the axes, so make the box a few bins wider.
% This will make it easier to see spikes in the last bin.
maxGL = maxGL + 8;
axis([hR hG hB], [0 maxGL 0 maxCount]);

% Plot all
subplot(3, 1, 3);
plot(grayLevelsR, countsR, 'r', 'LineWidth', 2);
grid on;
xlabel('Gray Level', 'FontSize', axisFontSize);
ylabel('Pixel Count', 'FontSize', axisFontSize);
hold on;
plot(grayLevelsG, countsG, 'g', 'LineWidth', 2);
plot(grayLevelsB, countsB, 'b', 'LineWidth', 2);
title('Histograms of All Channels', 'FontSize', captionFontSize);
maxGrayLevel = max([maxGLValueR, maxGLValueG, maxGLValueB]);
% Trim x-axis to just the max gray level on the bright end.
if eightBit
xlim([0 255]);
else
xlim([0 maxGrayLevel]);
end

Subject: Identify colors in an RGB image

From: Daphne

Date: 5 Jun, 2010 15:44:04

Message: 6 of 10


Thanks so much!
Your demo and the histogram codes were exactly what I needed.
Tinkered with the images a bit and found the threshold range for yellow.

Thanks again!
Daphne

Subject: Identify colors in an RGB image

From: Kenny Nam

Date: 4 Aug, 2010 06:34:12

Message: 7 of 10

"Daphne" <daphnew_too_nospam@yahoo.com> wrote in message <hudrc3$2oi$1@fred.mathworks.com>...
>
> Thanks so much!
> Your demo and the histogram codes were exactly what I needed.
> Tinkered with the images a bit and found the threshold range for yellow.
>
> Thanks again!
> Daphne

Daphne,i also doing the yellow color detection,do u filter the background of the picture before you get the range for yellow?Can share your idea to me?

Subject: Identify colors in an RGB image

From: Daphne

Date: 4 Aug, 2010 14:12:02

Message: 8 of 10

Hi Kenny,

Any filtration or brightness/contrast is typically set by the user when taking the image and we count on the quality of the staining. We filter objects for brightness and size.

I upload two images into the red and the green, use imadd to get the merged image and then define the color mask to get only the yellow (got the yellow limits or its RGB definition from a spectrum plot). Then I filter a bit more by size of blob, not to get background stains of single pixels etc.

Hope this helps,
Daphne


"Kenny Nam" <kennynam517@hotmail.com> wrote in message <i3b1l3$3a4$1@fred.mathworks.com>...
> "Daphne" <daphnew_too_nospam@yahoo.com> wrote in message <hudrc3$2oi$1@fred.mathworks.com>...
> >
> > Thanks so much!
> > Your demo and the histogram codes were exactly what I needed.
> > Tinkered with the images a bit and found the threshold range for yellow.
> >
> > Thanks again!
> > Daphne
>
> Daphne,i also doing the yellow color detection,do u filter the background of the picture before you get the range for yellow?Can share your idea to me?

Subject: Identify colors in an RGB image

From: Kenny Nam

Date: 9 Aug, 2010 16:01:21

Message: 9 of 10

"Daphne" <daphnew_too_nospam@yahoo.com> wrote in message <i3bsfi$fu1$1@fred.mathworks.com>...
> Hi Kenny,
>
> Any filtration or brightness/contrast is typically set by the user when taking the image and we count on the quality of the staining. We filter objects for brightness and size.
>
> I upload two images into the red and the green, use imadd to get the merged image and then define the color mask to get only the yellow (got the yellow limits or its RGB definition from a spectrum plot). Then I filter a bit more by size of blob, not to get background stains of single pixels etc.
>
> Hope this helps,
> Daphne
>
>
> "Kenny Nam" <kennynam517@hotmail.com> wrote in message <i3b1l3$3a4$1@fred.mathworks.com>...
> > "Daphne" <daphnew_too_nospam@yahoo.com> wrote in message <hudrc3$2oi$1@fred.mathworks.com>...
> > >
> > > Thanks so much!
> > > Your demo and the histogram codes were exactly what I needed.
> > > Tinkered with the images a bit and found the threshold range for yellow.
> > >
> > > Thanks again!
> > > Daphne
> >


Nam Kenny
> > Daphne,i also doing the yellow color detection,do u filter the background of the picture before you get the range for yellow?Can share your idea to me?





Daphne,
I have try to adjust the threshold for the demo of simple color detection,but it not work,it still show the histogram in RGB.Do u mind to show me your coding in detect or filter the yellow?Need your help/guide badly.Thanks

Subject: Identify colors in an RGB image

From: Daphne

Date: 15 Aug, 2010 16:59:04

Message: 10 of 10


I am not sure what it is that you need.
The code that was suggested shows the different colors.
If you want to filter out only the yellow you can try the code below. It includes our yellow filter applied on an RGB image (3 layers). It should leave only what we considered yellow in a merged image. You can change the values to include more greenish or brownish shades.

Hope this helps,
Daphne


% defining a mask for shades of yellow
yellow1 = merged_image(:,:,1)>=190 & merged_image(:,:,2)>=round(0.24*merged_image(:,:,1)+50) ;
yellow2 = merged_image(:,:,1)<190 & merged_image(:,:,1)>=100 & ...
    merged_image(:,:,2)<=round( 1.65 * merged_image(:,:,1) - 85 ) & ...
    merged_image(:,:,2)>=round( 0.24 * merged_image(:,:,1) + 50 ) ;

%yellow1 and yellow2 will never have 1 in the same position,
%thus combine them:
yellowObjectsMask = abs(yellow1-yellow2);
% You can only multiply integers if they are of the same type.
% (yellowObjectsMask is a logical array.)
% We need to convert the type of yellowObjectsMask to the same data type as redBand.
strDataType = class(merged_image(:,:,1));
yellowObjectsMask = eval([strDataType '(yellowObjectsMask)']);

% Use the yellow object mask to mask out the red-only portions of the rgb image.
maskedImageR = yellowObjectsMask .* merged_image(:,:,1);
maskedImageG = yellowObjectsMask .* merged_image(:,:,2);
maskedImageB = yellowObjectsMask .* merged_image(:,:,3);
maskedRGBImage = cat(3, maskedImageR, maskedImageG, maskedImageB);

Tags for this Thread

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us