Nikhil
Nikhil

Reputation: 1309

Matlab code to compare two histograms

I want to compare two image histograms. They are as follows:

h1 --> double valued 1 dimension vector .4096 in length.

h2 --> double valued 1 dimension vector .4096 in length.

I am using this matlab function here:

http://clickdamage.com/sourcecode/code/compareHists.m

It is as follows:

% s = compareHists(h1,h2)
%       returns a histogram similarity in the range 0..1
%
% Compares 2 normalised histograms using the Bhattacharyya coefficient.
% Assumes that sum(h1) == sum(h2) == 1
%
function s = compareHists(h1,h2)

s = sum(sum(sum(sqrt(h1).*sqrt(h2))));

My question is :

Is there a need for multiple sums?

Even if there is only one sum in the above equation, it would suffice..right?

like this: sum(sqrt(h1).*sqrt(h2)) --> ?

Can some one please explain the code above? Also, tell me if I use a single sum will it be all right?

I tried both ways and got the same answer for two image histograms. I did this with only two histograms not more and hence want to be sure.

Thanks!

Upvotes: 1

Views: 9083

Answers (4)

Luis Mendo
Luis Mendo

Reputation: 112659

In general, sum does the sum along one dimension only. If you want to sum along multiple dimensions you either

  • use sum several times; or
  • use linear indexing to reduce to a single dimension and then use sum once: sum(sqrt(h1(:)).*sqrt(h2(:))).

In your case, if there's only one dimension, yes, a single sum would suffice.

Upvotes: 3

user2987507
user2987507

Reputation: 11

I don't see any points in 3 sums too, but if you have not a vector with histogram but a matrix you will need 2 sums like this sum(sum(sqrt(h1).*sqrt(h2))) to compare them. First one will calculate the sum of the rows, the second - the sum of the columns.

Upvotes: 1

heriantolim
heriantolim

Reputation: 457

You are right. Only one sum is needed. However, if either h1 or h2 is a multidimensional matrix, then you may want to sum as many as the dimensions. For example:

A=magic(4); % a 4 by 4 matrix of magic numbers.
sum(A) % returns [34,34,34,34], i.e. the sum of elements in each column.
sum(sum(A)) % returns 136, i.e. the sum of all elements in A.

Upvotes: 2

Shai
Shai

Reputation: 114786

I believe the code you downloaded originaly was written to handle multiple histograms stacked as columns of a matrix. This is (IMHO) the reason for the multiple sums.

In your case you can leave it with only one sum.

You can do even better - without any sum

Hover here to see the answer

s = sqrt(h1(:)')*sqrt(h2(:)); The trick is to use vector multiplication!

Upvotes: 2

Related Questions