Reputation: 71
I want to find the histogram of two images and find the similarity using Euclidean distance. I'm trying to use the imhist
command but it is giving the following error:
Error using ==> iptcheckinput
Function IMHIST expected its first input, I or X, to be two-dimensional.
my code is as follows:
% read two images
Im1 = imread('1.jpg');
Im2 = imread('2.jpg');
% convert images to type double (range from from 0 to 1 instead of from 0 to 255)
Im1 = im2double(Im1);
Im2 = im2double(Im2);
% Calculate the Normalized Histogram of Image 1 and Image 2
hn1 = imhist(Im1)./numel(Im1);
hn2 = imhist(Im2)./numel(Im2);
% Calculate the histogram error
f = sum((hn1 - hn2).^2);
f; %display the result to console
Upvotes: 7
Views: 21779
Reputation: 156
Indeed, histograms are meant to represent the repartition of tonal values for one single channel. Color images are often 3-channels images (Red, Green, Blue in most cases).
Ghaul's method should work quite correctly. If you want to be more precise, you can extract each channel and compute its histogram:
Red1 = Im1(:, :, 1);
Green1 = Im1(:, :, 2);
Blue1 = Im1(:, :, 3);
HnBlue1 = imhist(Blue1)./numel(Blue1);
You are now able to define an evaluation fonction based on the 3 euclidean distances (1 for each channel):
FBlue = sum((HnBlue1 - HnBlue2).^2);
FRed= sum((HnRed1 - HnRed2).^2);
...
F = Alpha*FBlue + Beta*FRed + Gamma*FGreen //as an example
You can therefore put the emphasis on one color or the other in your distance definition. That could be useful if the image you want to test has a specific color.
This is an alternative to Ghaul's method, but its equivalent would be to set Alpha, Beta and Gamma as "0.2989 * R + 0.5870 * G + 0.1140 * B", as Andrey stated.
Upvotes: 7
Reputation: 3330
I'm guessing that your images are color images, i.e. have three channels. To reduce them to one channel gray scale images do
Im1 = rgb2gray(Im1);
Im2 = rgb2gray(Im2);
hn1 = imhist(Im1)./numel(Im1);
hn2 = imhist(Im2)./numel(Im2);
etc..
Alternatively, if you want to work on all the color channels you can stretch your images into vectors before doing imhist, i.e., just do
hn1 = imhist(Im1(:))./numel(Im1);
hn2 = imhist(Im2(:))./numel(Im2);
Upvotes: 5