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:
color histogram

Subject: color histogram

From: Rashmi S N

Date: 23 Feb, 2012 07:42:17

Message: 1 of 6

We intend to compute the colour histograms of about 20 colour images and save it in a file. When we have a query image, we want to compute the colour histogram of the query image and later compare it with the values in the file. Could anyone please help us with the appropriate code for saving the colour histogram values in a file?

Once the match is found, we want the corresponding image to be output. So if anyone can give us an idea about how indexing is done in matlab, we will really appreciate it!

Subject: color histogram

From: ImageAnalyst

Date: 23 Feb, 2012 11:10:50

Message: 2 of 6

On Feb 23, 2:42 am, "Rashmi S N" <rashmisnachar.9...@gmail.com> wrote:
> We intend to compute the colour histograms of about 20 colour images and save it in a file. When we have a query image, we want to compute the colour histogram of the query image and later compare it with the values in the file. Could anyone please help us with the appropriate code for saving the colour histogram values in a file?
>
> Once the match is found, we want the corresponding image to be output. So if anyone can give us an idea about how indexing is done in matlab, we will really appreciate it!

------------------------------------------------------------------------------------------------
Copy and paste this demo. To save, you can use save(), fprintf() or
similar.

% IMPORTANT: The newsreader may break long lines into multiple lines.
% Be sure to join any long lines that got split into multiple single
lines.
% These can be found by the red lines on the left side of your
% text editor, which indicate syntax errors, or else just run the
% code and it will stop at the split lines with an error.
%----------------------------------------------------------
% Program to read in all the RGB color images in a folder and
% display the histograms of each color channel.
% By ImageAnalyst, Feb. 2011
%----------------------------------------------------------

function RGB_Histogram_Demo()

% Change the current folder to the folder of this m-file.
if(~isdeployed)
cd(fileparts(which(mfilename)));
end
clc; % Clear command window.
clear; % Delete all variables.
close all; % Close all figure windows except those created by imtool.
imtool close all; % Close all figure windows created by imtool.
workspace; % Make sure the workspace panel is showing.
fontSize = 16;

try
% Read in standard MATLAB color demo images.
% Construct the folder name where the demo images live.
imagesFolder = fullfile(matlabroot, '\toolbox\images\imdemos');
if ~exist(imagesFolder, 'dir')
% That folder didn't exist. Ask user to specify folder.
  message = sprintf('Please browse to your image folder');
button = questdlg(message, 'Specify Folder', 'OK', 'Cancel', 'OK');
drawnow; % Refresh screen to get rid of dialog box remnants.
if strcmpi(button, 'Cancel')
return;
else
imagesFolder = uigetdir();
if imagesFolder == 0
% Exit if uer clicked Cancel.
return;
end
end
end

% Read the directory to get a list of images.
filePattern = [imagesFolder, '\*.jpg'];
jpegFiles = dir(filePattern);
filePattern = [imagesFolder, '\*.tif'];
tifFiles = dir(filePattern);
filePattern = [imagesFolder, '\*.png'];
pngFiles = dir(filePattern);
filePattern = [imagesFolder, '\*.bmp'];
bmpFiles = dir(filePattern);
% Add more extensions if you need to.
imageFiles = [jpegFiles; tifFiles; pngFiles; bmpFiles];

% Bail out if there aren't any images in that folder.
numberOfImagesProcessed = 0;
numberOfImagesToProcess = length(imageFiles);
if numberOfImagesToProcess <= 0
  message = sprintf('I did not find any JPG, TIF, PNG, or BMP images
in the folder\n%s\nClick OK to Exit.', imagesFolder);
uiwait(msgbox(message));
return;
end

% Create a figure for our images.
figure;
set(gcf, 'Position', get(0,'Screensize')); % Maximize figure.
set(gcf,'name','Demo by ImageAnalyst','numbertitle','off')

% Preallocate arrays to hold the mean intensity values of all the
images.
redChannel_Mean = zeros(numberOfImagesToProcess, 1);
greenChannel_Mean = zeros(numberOfImagesToProcess, 1);
blueChannel_Mean = zeros(numberOfImagesToProcess, 1);

% We'll be skipping monochrome and indexed images
% and just looking at true color images.
% Keep track of how many we actually look at.
numberOfImagesToProcess2 = numberOfImagesToProcess;

% Loop though all images, calculating and displaying the histograms.
% and then getting the means of the Red, green, and blue channels.
for k = 1 : numberOfImagesToProcess
% Read in this one file.
baseFileName = imageFiles(k).name;
fullFileName = fullfile(imagesFolder, baseFileName);
rgbImage = imread(fullFileName);

% Check to see that it is a color image (3 dimensions).
% Skip it if it is not true RGB color.
if ndims(rgbImage) < 3
% Skip monochrome or indexed images.
fprintf('Skipped %s. It is a grayscale or indexed image.\n',
baseFileName);
% Decrement the number of images that we'll report that we need to
look at.
numberOfImagesToProcess2 = numberOfImagesToProcess2 - 1;
continue;
end

% If we get to here, it's a true color image.
subplot(3, 3, 1);
imshow(rgbImage, []);
[rows columns numberOfColorBands] = size(rgbImage);

% Create a title for the image.
caption = sprintf('Original Color Image\n%s\n%d rows by %d columns by
%d color channels', ...
baseFileName, rows, columns, numberOfColorBands);
% If there are underlines in the name, title() converts the next
character to a subscript.
% To avoid this, replace underlines by spaces.
caption = strrep(caption, '_', ' ');
title(caption, 'FontSize', fontSize);
drawnow; % Force it to update, otherwise it waits until after the
conversion to double.

% Extract the individual red, green, and blue color channels.
redChannel = rgbImage(:, :, 1);
greenChannel = rgbImage(:, :, 2);
blueChannel = rgbImage(:, :, 3);

% Red image:
subplot(3, 3, 4);
imshow(redChannel, []); % Display the image.
% Compute mean
redChannel_Mean(k) = mean(redChannel(:));
caption = sprintf('Red Image. Mean = %6.2f', redChannel_Mean(k));
title(caption, 'FontSize', fontSize);
% Compute and display the histogram for the Red image.
pixelCountRed = PlotHistogramOfOneColorChannel(redChannel, 7,
'Histogram of Red Image', 'r');

% Green image:
subplot(3, 3, 5);
imshow(greenChannel, []); % Display the image.
% Compute mean
greenChannel_Mean(k) = mean(greenChannel(:));
caption = sprintf('Green Image. Mean = %6.2f',
greenChannel_Mean(k));
title(caption, 'FontSize', fontSize);
% Compute and display the histogram for the Green image.
pixelCountGreen = PlotHistogramOfOneColorChannel(greenChannel, 8,
'Histogram of Green Image', 'g');

% Blue image:
subplot(3, 3, 6);
imshow(blueChannel, []); % Display the image.
numberOfImagesProcessed = numberOfImagesProcessed + 1;
% Compute mean
blueChannel_Mean(k) = mean(blueChannel(:));
caption = sprintf('Blue Image. Mean = %6.2f', blueChannel_Mean(k));
title(caption, 'FontSize', fontSize);
% Compute and display the histogram for the Blue image.
pixelCountBlue = PlotHistogramOfOneColorChannel(blueChannel, 9,
'Histogram of Blue Image', 'b');

% Plot all three histograms on the same plot.
subplot(3, 3, 2:3);
lineWidth = 2;
hold off;
plot(pixelCountRed, 'r', 'LineWidth', lineWidth);
hold on;
grid on;
plot(pixelCountGreen, 'g', 'LineWidth', lineWidth);
plot(pixelCountBlue, 'b', 'LineWidth', lineWidth);
title('All the Color Histograms (Superimposed)', 'FontSize',
fontSize);
% Set the x axis range manually to be 0-255.
xlim([0 255]);

% Prompt user to continue, unless they're at the last image.
if k < numberOfImagesToProcess
promptMessage = sprintf('Currently displaying image #%d of a
possible %d:\n%s\n\nDo you want to\nContinue processing, or\nCancel
processing?',...
numberOfImagesProcessed, numberOfImagesToProcess2, baseFileName);
button = questdlg(promptMessage, 'Continue?', 'Continue', 'Cancel',
'Continue');
if strcmp(button, 'Cancel')
break;
end
end
end

% Crop off any unassigned values:
redChannel_Mean = redChannel_Mean(1:numberOfImagesProcessed);
greenChannel_Mean = greenChannel_Mean(1:numberOfImagesProcessed);
blueChannel_Mean = blueChannel_Mean(1:numberOfImagesProcessed);

% Print to command window
fprintf(1, ' Filename, Red Mean, Green Mean, Blue Mean
\n');
for k = 1 : length(redChannel_Mean)
baseFileName = imageFiles(k).name;
fprintf(1, '%24s %6.2f, %6.2f, %6.2f\n', ...
baseFileName, redChannel_Mean(k), greenChannel_Mean(k),
blueChannel_Mean(k));
end

if numberOfImagesProcessed == 1
caption = sprintf('Done with demo!\n\nProcessed 1 image.\nCheck out
the command window for the results');
else
caption = sprintf('Done with demo!\n\nProcessed %d images.\nCheck out
the command window for the results', numberOfImagesProcessed);
end
msgbox(caption);
catch ME
errorMessage = sprintf('Error in function RGB_Hist_Demo.\n.\n\nError
Message:\n%s', ME.message);
uiwait(warndlg(errorMessage));
end

%----------------------------------------------------------
% Plots a bar chart of the histogram of the color channel.
function pixelCount = PlotHistogramOfOneColorChannel(oneColorChannel,
subplotNumber, caption, color)
try
% Let's get its histogram into 256 bins.
[pixelCount grayLevels] = imhist(oneColorChannel, 256);

subplot(3, 3, subplotNumber);
bar(grayLevels, pixelCount, 'FaceColor', color);
title(caption, 'FontSize', 16);
grid on;
% Set the x axis range manually to be 0-255.
xlim([0 255]);
catch ME
errorMessage = sprintf('Error in function
PlotHistogramOfOneColorChannel.\n.\n\nError Message:\n%s',
ME.message);
uiwait(warndlg(errorMessage));
end
return;

Subject: color histogram

From: keenN

Date: 16 Apr, 2012 10:29:07

Message: 3 of 6

Hello,
I tried this demo. Instead of displaying each R,G and B, I changed them to H,S,I. I also changed the range from [0 255] to [0 100]. It worked, the superimposed histogram was okay; however, the individual histograms didn't show correctly. I could not figure out why. Do I need to add or change anything if I use HSI color space?

ImageAnalyst <imageanalyst@mailinator.com> wrote in message <c8000dfd-eae6-4653-b299-fdfb94c3772a@m24g2000yqb.googlegroups.com>...
> On Feb 23, 2:42 am, "Rashmi S N" <rashmisnachar.9...@gmail.com> wrote:
> > We intend to compute the colour histograms of about 20 colour images and save it in a file. When we have a query image, we want to compute the colour histogram of the query image and later compare it with the values in the file. Could anyone please help us with the appropriate code for saving the colour histogram values in a file?
> >
> > Once the match is found, we want the corresponding image to be output. So if anyone can give us an idea about how indexing is done in matlab, we will really appreciate it!
>
> ------------------------------------------------------------------------------------------------
> Copy and paste this demo. To save, you can use save(), fprintf() or
> similar.
>
> % IMPORTANT: The newsreader may break long lines into multiple lines.
> % Be sure to join any long lines that got split into multiple single
> lines.
> % These can be found by the red lines on the left side of your
> % text editor, which indicate syntax errors, or else just run the
> % code and it will stop at the split lines with an error.
> %----------------------------------------------------------
> % Program to read in all the RGB color images in a folder and
> % display the histograms of each color channel.
> % By ImageAnalyst, Feb. 2011
> %----------------------------------------------------------
>
> function RGB_Histogram_Demo()
>
> % Change the current folder to the folder of this m-file.
> if(~isdeployed)
> cd(fileparts(which(mfilename)));
> end
> clc; % Clear command window.
> clear; % Delete all variables.
> close all; % Close all figure windows except those created by imtool.
> imtool close all; % Close all figure windows created by imtool.
> workspace; % Make sure the workspace panel is showing.
> fontSize = 16;
>
> try
> % Read in standard MATLAB color demo images.
> % Construct the folder name where the demo images live.
> imagesFolder = fullfile(matlabroot, '\toolbox\images\imdemos');
> if ~exist(imagesFolder, 'dir')
> % That folder didn't exist. Ask user to specify folder.
> message = sprintf('Please browse to your image folder');
> button = questdlg(message, 'Specify Folder', 'OK', 'Cancel', 'OK');
> drawnow; % Refresh screen to get rid of dialog box remnants.
> if strcmpi(button, 'Cancel')
> return;
> else
> imagesFolder = uigetdir();
> if imagesFolder == 0
> % Exit if uer clicked Cancel.
> return;
> end
> end
> end
>
> % Read the directory to get a list of images.
> filePattern = [imagesFolder, '\*.jpg'];
> jpegFiles = dir(filePattern);
> filePattern = [imagesFolder, '\*.tif'];
> tifFiles = dir(filePattern);
> filePattern = [imagesFolder, '\*.png'];
> pngFiles = dir(filePattern);
> filePattern = [imagesFolder, '\*.bmp'];
> bmpFiles = dir(filePattern);
> % Add more extensions if you need to.
> imageFiles = [jpegFiles; tifFiles; pngFiles; bmpFiles];
>
> % Bail out if there aren't any images in that folder.
> numberOfImagesProcessed = 0;
> numberOfImagesToProcess = length(imageFiles);
> if numberOfImagesToProcess <= 0
> message = sprintf('I did not find any JPG, TIF, PNG, or BMP images
> in the folder\n%s\nClick OK to Exit.', imagesFolder);
> uiwait(msgbox(message));
> return;
> end
>
> % Create a figure for our images.
> figure;
> set(gcf, 'Position', get(0,'Screensize')); % Maximize figure.
> set(gcf,'name','Demo by ImageAnalyst','numbertitle','off')
>
> % Preallocate arrays to hold the mean intensity values of all the
> images.
> redChannel_Mean = zeros(numberOfImagesToProcess, 1);
> greenChannel_Mean = zeros(numberOfImagesToProcess, 1);
> blueChannel_Mean = zeros(numberOfImagesToProcess, 1);
>
> % We'll be skipping monochrome and indexed images
> % and just looking at true color images.
> % Keep track of how many we actually look at.
> numberOfImagesToProcess2 = numberOfImagesToProcess;
>
> % Loop though all images, calculating and displaying the histograms.
> % and then getting the means of the Red, green, and blue channels.
> for k = 1 : numberOfImagesToProcess
> % Read in this one file.
> baseFileName = imageFiles(k).name;
> fullFileName = fullfile(imagesFolder, baseFileName);
> rgbImage = imread(fullFileName);
>
> % Check to see that it is a color image (3 dimensions).
> % Skip it if it is not true RGB color.
> if ndims(rgbImage) < 3
> % Skip monochrome or indexed images.
> fprintf('Skipped %s. It is a grayscale or indexed image.\n',
> baseFileName);
> % Decrement the number of images that we'll report that we need to
> look at.
> numberOfImagesToProcess2 = numberOfImagesToProcess2 - 1;
> continue;
> end
>
> % If we get to here, it's a true color image.
> subplot(3, 3, 1);
> imshow(rgbImage, []);
> [rows columns numberOfColorBands] = size(rgbImage);
>
> % Create a title for the image.
> caption = sprintf('Original Color Image\n%s\n%d rows by %d columns by
> %d color channels', ...
> baseFileName, rows, columns, numberOfColorBands);
> % If there are underlines in the name, title() converts the next
> character to a subscript.
> % To avoid this, replace underlines by spaces.
> caption = strrep(caption, '_', ' ');
> title(caption, 'FontSize', fontSize);
> drawnow; % Force it to update, otherwise it waits until after the
> conversion to double.
>
> % Extract the individual red, green, and blue color channels.
> redChannel = rgbImage(:, :, 1);
> greenChannel = rgbImage(:, :, 2);
> blueChannel = rgbImage(:, :, 3);
>
> % Red image:
> subplot(3, 3, 4);
> imshow(redChannel, []); % Display the image.
> % Compute mean
> redChannel_Mean(k) = mean(redChannel(:));
> caption = sprintf('Red Image. Mean = %6.2f', redChannel_Mean(k));
> title(caption, 'FontSize', fontSize);
> % Compute and display the histogram for the Red image.
> pixelCountRed = PlotHistogramOfOneColorChannel(redChannel, 7,
> 'Histogram of Red Image', 'r');
>
> % Green image:
> subplot(3, 3, 5);
> imshow(greenChannel, []); % Display the image.
> % Compute mean
> greenChannel_Mean(k) = mean(greenChannel(:));
> caption = sprintf('Green Image. Mean = %6.2f',
> greenChannel_Mean(k));
> title(caption, 'FontSize', fontSize);
> % Compute and display the histogram for the Green image.
> pixelCountGreen = PlotHistogramOfOneColorChannel(greenChannel, 8,
> 'Histogram of Green Image', 'g');
>
> % Blue image:
> subplot(3, 3, 6);
> imshow(blueChannel, []); % Display the image.
> numberOfImagesProcessed = numberOfImagesProcessed + 1;
> % Compute mean
> blueChannel_Mean(k) = mean(blueChannel(:));
> caption = sprintf('Blue Image. Mean = %6.2f', blueChannel_Mean(k));
> title(caption, 'FontSize', fontSize);
> % Compute and display the histogram for the Blue image.
> pixelCountBlue = PlotHistogramOfOneColorChannel(blueChannel, 9,
> 'Histogram of Blue Image', 'b');
>
> % Plot all three histograms on the same plot.
> subplot(3, 3, 2:3);
> lineWidth = 2;
> hold off;
> plot(pixelCountRed, 'r', 'LineWidth', lineWidth);
> hold on;
> grid on;
> plot(pixelCountGreen, 'g', 'LineWidth', lineWidth);
> plot(pixelCountBlue, 'b', 'LineWidth', lineWidth);
> title('All the Color Histograms (Superimposed)', 'FontSize',
> fontSize);
> % Set the x axis range manually to be 0-255.
> xlim([0 255]);
>
> % Prompt user to continue, unless they're at the last image.
> if k < numberOfImagesToProcess
> promptMessage = sprintf('Currently displaying image #%d of a
> possible %d:\n%s\n\nDo you want to\nContinue processing, or\nCancel
> processing?',...
> numberOfImagesProcessed, numberOfImagesToProcess2, baseFileName);
> button = questdlg(promptMessage, 'Continue?', 'Continue', 'Cancel',
> 'Continue');
> if strcmp(button, 'Cancel')
> break;
> end
> end
> end
>
> % Crop off any unassigned values:
> redChannel_Mean = redChannel_Mean(1:numberOfImagesProcessed);
> greenChannel_Mean = greenChannel_Mean(1:numberOfImagesProcessed);
> blueChannel_Mean = blueChannel_Mean(1:numberOfImagesProcessed);
>
> % Print to command window
> fprintf(1, ' Filename, Red Mean, Green Mean, Blue Mean
> \n');
> for k = 1 : length(redChannel_Mean)
> baseFileName = imageFiles(k).name;
> fprintf(1, '%24s %6.2f, %6.2f, %6.2f\n', ...
> baseFileName, redChannel_Mean(k), greenChannel_Mean(k),
> blueChannel_Mean(k));
> end
>
> if numberOfImagesProcessed == 1
> caption = sprintf('Done with demo!\n\nProcessed 1 image.\nCheck out
> the command window for the results');
> else
> caption = sprintf('Done with demo!\n\nProcessed %d images.\nCheck out
> the command window for the results', numberOfImagesProcessed);
> end
> msgbox(caption);
> catch ME
> errorMessage = sprintf('Error in function RGB_Hist_Demo.\n.\n\nError
> Message:\n%s', ME.message);
> uiwait(warndlg(errorMessage));
> end
>
> %----------------------------------------------------------
> % Plots a bar chart of the histogram of the color channel.
> function pixelCount = PlotHistogramOfOneColorChannel(oneColorChannel,
> subplotNumber, caption, color)
> try
> % Let's get its histogram into 256 bins.
> [pixelCount grayLevels] = imhist(oneColorChannel, 256);
>
> subplot(3, 3, subplotNumber);
> bar(grayLevels, pixelCount, 'FaceColor', color);
> title(caption, 'FontSize', 16);
> grid on;
> % Set the x axis range manually to be 0-255.
> xlim([0 255]);
> catch ME
> errorMessage = sprintf('Error in function
> PlotHistogramOfOneColorChannel.\n.\n\nError Message:\n%s',
> ME.message);
> uiwait(warndlg(errorMessage));
> end
> return;

Subject: color histogram

From: ImageAnalyst

Date: 16 Apr, 2012 14:08:02

Message: 4 of 6

On Apr 16, 6:29 am, "keenN " <ikin9...@yahoo.com> wrote:
> Hello,
> I tried this demo. Instead of displaying each R,G and B, I changed them to H,S,I. I also changed the range from [0 255] to [0 100]. It worked, the superimposed histogram was okay; however, the individual histograms didn't show correctly. I could not figure out why. Do I need to add or change anything if I use HSI color space?
---------------------------------------------------------------------
keenN:
It's tricky to use imhist() if you have floating point (single or
double) images, though it can be done (see my code below). You'd
probably be better off using hist() instead. Give that a try.
ImageAnalyst

% IMPORTANT: The newsreader may break long lines into multiple lines.
% Be sure to join any long lines that got split into multiple single
lines.
% These can be found by the red lines on the left side of your
% text editor, which indicate syntax errors, or else just run the
% code and it will stop at the split lines with an error.

% function double_image_histogram()

% Change the current folder to the folder of this m-file.
if(~isdeployed)
cd(fileparts(which(mfilename)));
end
clc; % Clear command window.
clear; % Delete all variables.
close all; % Close all figure windows except those created by imtool.
imtool close all; % Close all figure windows created by imtool.
workspace; % Make sure the workspace panel is showing.
fontSize = 20;

% Read in standard MATLAB gray scale demo image.
grayImage = imread('cameraman.tif');
subplot(2, 2, 1);
imshow(grayImage, []);
title('Original Grayscale Image', 'FontSize', fontSize);
set(gcf, 'Position', get(0,'Screensize')); % Maximize figure.

% Let's get its histogram.
[pixelCount grayLevels] = imhist(grayImage);
subplot(2, 2, 3);
bar(pixelCount);
xlim([0 grayLevels(end)]); % Scale x axis manually.
title('Original Grayscale Histogram', 'FontSize', fontSize);

% Now let's synthesize an image that is a floating point
% image and has values from -12345 to +54321.
originalMinValue = double(min(min(grayImage)))
originalMaxValue = double(max(max(grayImage)))
originalRange = originalMaxValue - originalMinValue;

% Get a double image in the range -127 to +128
desiredMin = -45678;
desiredMax = 54321;
desiredRange = desiredMax - desiredMin;
dblImageS = desiredRange * (double(grayImage) - originalMinValue) /
originalRange + desiredMin;
% So now we have a double image that is our "starting image."
% However can't use imhist on this. We need to scale to 0-1.
minValueS = min(min(dblImageS))
maxValueS = max(max(dblImageS))
rangeS = maxValueS - minValueS;
dblImage = (dblImageS - minValueS) / rangeS;
% Check to verify that range is now 0-1.
minValueNorm = min(min(dblImage))
maxValueNorm = max(max(dblImage))
subplot(2, 2, 2);
imshow(dblImage, []);
title('Double Image', 'FontSize', fontSize);

% Let's get its histogram into 256 bins.
[pixelCountD grayLevelsD] = imhist(dblImage, 256);
% But now grayLevelsD goes from 0 to 1.
% We want it to go from the original range, so we need to scale.
originalDoubleGrayLevels = rangeS * grayLevelsD + minValueS;

subplot(2, 2, 4);
plot(originalDoubleGrayLevels, pixelCountD);
title('Histogram of double image', 'FontSize', fontSize);
% Scale x axis manually.
xlim([originalDoubleGrayLevels(1) originalDoubleGrayLevels(end)]);

Subject: color histogram

From: Dave Robinson

Date: 16 Apr, 2012 15:45:09

Message: 5 of 6

"Rashmi S N" <rashmisnachar.9028@gmail.com> wrote in message <ji4qkp$psq$1@newscl01ah.mathworks.com>...
> We intend to compute the colour histograms of about 20 colour images and save it in a file. When we have a query image, we want to compute the colour histogram of the query image and later compare it with the values in the file. Could anyone please help us with the appropriate code for saving the colour histogram values in a file?
>
> Once the match is found, we want the corresponding image to be output. So if anyone can give us an idea about how indexing is done in matlab, we will really appreciate it!

You need to be careful when using histograms to compare images, in as much as many different distinct images can result in identical histograms - a trivial grayscale example is an image of a chessboard will result in an identical histogram to that of an image whose right side is white and whose left side is black.

The problem becomes even more complicated when dealing with colour histograms, where different colours can really generate some confusion. In splitting up the colour planes and histogramming them seperately, you loose the information regarding whether the regions of colour overlap or not, e.g. do some of fhe red components overlap some of the blue components, and belong to a region of magenta in the scene, or do they belong to self standing regions of red and blue, or maybe a mixture of the two, in which case what number of the red blue belongs to the magenta, and what belongs to the self standing primary colour blobs? Do the other images you are comparing have exactly the same colour balance, if not you might find that the comparisons might match totally inappropriate images.

Maybe this isn't a problem to you. In which case ignore this note, however all I am saying is think deeply before making a histogram image matching algorithm.

Regards

Dave Robinson

Subject: color histogram

From: keenN

Date: 17 Apr, 2012 06:37:08

Message: 6 of 6

Oh yes, I just realized that now about imhist.
Thank you very much ImageAnalyst for pointing it out.
> ---------------------------------------------------------------------
> keenN:
> It's tricky to use imhist() if you have floating point (single or
> double) images, though it can be done (see my code below). You'd
> probably be better off using hist() instead. Give that a try.
> ImageAnalyst
>
> % IMPORTANT: The newsreader may break long lines into multiple lines.
> % Be sure to join any long lines that got split into multiple single
> lines.
> % These can be found by the red lines on the left side of your
> % text editor, which indicate syntax errors, or else just run the
> % code and it will stop at the split lines with an error.
>
> % function double_image_histogram()
>
> % Change the current folder to the folder of this m-file.
> if(~isdeployed)
> cd(fileparts(which(mfilename)));
> end
> clc; % Clear command window.
> clear; % Delete all variables.
> close all; % Close all figure windows except those created by imtool.
> imtool close all; % Close all figure windows created by imtool.
> workspace; % Make sure the workspace panel is showing.
> fontSize = 20;
>
> % Read in standard MATLAB gray scale demo image.
> grayImage = imread('cameraman.tif');
> subplot(2, 2, 1);
> imshow(grayImage, []);
> title('Original Grayscale Image', 'FontSize', fontSize);
> set(gcf, 'Position', get(0,'Screensize')); % Maximize figure.
>
> % Let's get its histogram.
> [pixelCount grayLevels] = imhist(grayImage);
> subplot(2, 2, 3);
> bar(pixelCount);
> xlim([0 grayLevels(end)]); % Scale x axis manually.
> title('Original Grayscale Histogram', 'FontSize', fontSize);
>
> % Now let's synthesize an image that is a floating point
> % image and has values from -12345 to +54321.
> originalMinValue = double(min(min(grayImage)))
> originalMaxValue = double(max(max(grayImage)))
> originalRange = originalMaxValue - originalMinValue;
>
> % Get a double image in the range -127 to +128
> desiredMin = -45678;
> desiredMax = 54321;
> desiredRange = desiredMax - desiredMin;
> dblImageS = desiredRange * (double(grayImage) - originalMinValue) /
> originalRange + desiredMin;
> % So now we have a double image that is our "starting image."
> % However can't use imhist on this. We need to scale to 0-1.
> minValueS = min(min(dblImageS))
> maxValueS = max(max(dblImageS))
> rangeS = maxValueS - minValueS;
> dblImage = (dblImageS - minValueS) / rangeS;
> % Check to verify that range is now 0-1.
> minValueNorm = min(min(dblImage))
> maxValueNorm = max(max(dblImage))
> subplot(2, 2, 2);
> imshow(dblImage, []);
> title('Double Image', 'FontSize', fontSize);
>
> % Let's get its histogram into 256 bins.
> [pixelCountD grayLevelsD] = imhist(dblImage, 256);
> % But now grayLevelsD goes from 0 to 1.
> % We want it to go from the original range, so we need to scale.
> originalDoubleGrayLevels = rangeS * grayLevelsD + minValueS;
>
> subplot(2, 2, 4);
> plot(originalDoubleGrayLevels, pixelCountD);
> title('Histogram of double image', 'FontSize', fontSize);
> % Scale x axis manually.
> xlim([originalDoubleGrayLevels(1) originalDoubleGrayLevels(end)]);
>
>
>
>

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