function sim = histogramSimilarity(im1,im2)

if length(size(im1))==3 % if image is RGB, transform it to gray
    im1 = im1(:,:,1)*0.3 + im1(:,:,2)*0.6 + im1(:,:,3)*0.1;
end
if length(size(im2))==3 % if image is RGB, transform it to gray
    im2 = im2(:,:,1)*0.3 + im2(:,:,2)*0.6 + im2(:,:,3)*0.1;
end

h1 = imhist(im1,256);
h1 = h1/sum(h1); % normalize the histogram (so that sum=1)
h2 = imhist(im2,256);
h2 = h2/sum(h2); % normalize the histogram (so that sum=1)

% smoothing of histogram, with sliding window of size 11

k = 10;
h1sm = zeros(k+length(h1),1);
h2sm = h1sm;
smmask = h1sm;

for i=0:k
    h1sm([1:256]+i) = h1sm([1:256]+i) + h1;
    h2sm([1:256]+i) = h2sm([1:256]+i) + h2;
    smmask([1:256]+i) = smmask([1:256]+i) + ones(256,1);
end

h1sm = h1sm./smmask;
h2sm = h2sm./smmask;

h1sm = h1sm([1:256]+k/2);
h2sm = h2sm([1:256]+k/2);

% end of smoothing

% calculate similarity of smoothed histograms
sim = norm(h1sm-h2sm);
