jeudi 9 avril 2015

Calculate chi-squared distance between to RGB images in matlab

I am trying to test a photos RGB histogram to find the closest one to it in the training data using the chi-squared distance the chisq function i use returns a difference matrix for each R , G , B histogram how can i get 1 value that says that both images difference is minimum



testimage = imread('C:\Documents and Settings\Owner\Desktop\Test\coast_land108.jpg');
imshow(testimage); %just check

%Get Red , Green , Blue Histo for test image
Rtest = testimage(:,:,1);
Gtest = testimage(:,:,2);
Btest = testimage(:,:,3);

[testRcnt, Rtbin]=imhist(Rtest);
[testGcnt, Gtbin]=imhist(Gtest);
[testBcnt, Btbin]=imhist(Btest);

%normalize histogram
testRcnt=testRcnt/sum(testRcnt);
testGcnt=testGcnt/sum(testGcnt);
testBcnt=testBcnt/sum(testBcnt);




Mindiff = 10000000; %min difference
imageindex = 1; %index of nearest image
for i = 1 : length(trainimagedir) % loop to all images in folder
filename = strcat('C:\Documents and Settings\Owner\Desktop\Train\',trainimagedir(i).name); % Get image name
trainI = imread(filename); % read image
% figure, imshow(trainI); % just check


% Get Red , Green , Blue Histo for train image
Rtrain = trainI(:,:,1);
Gtrain = trainI(:,:,2);
Btrain = trainI(:,:,3);

[trainRcnt, Rbin]=imhist(Rtrain);
[trainGcnt, Gbin]=imhist(Gtrain);
[trainBcnt, Bbin]=imhist(Btrain);


totalSumR = 0;
totalSumB = 0;
totalSumG = 0;

%normalize
trainRcnt=trainRcnt/sum(trainRcnt);
trainGcnt=trainGcnt/sum(trainGcnt);
trainBcnt=trainBcnt/sum(trainBcnt);

d1=pdist2(trainRcnt,testRcnt,'chisq'); %each returns a matrix of differences
d2=pdist2(trainGcnt,testGcnt,'chisq');
d3=pdist2(trainBcnt,testBcnt,'chisq');

d=sum(d1)+sum(d2)+sum(d3); %part i do not know how to do ?????????

diff = sqrt(totalSumR/2+totalSumB/2+totalSumG/2); %trying to get the overall difference


if(Mindiff > diff)
Mindiff = diff;
imageindex = i;





end
end

imageindex
filename = strcat('C:\Documents and Settings\Owner\Desktop\Train\',trainimagedir(imageindex).name); % Get Nearest image name
trainI = imread(filename); % read Nearest image
figure, imshow(trainI); % just check


pdist2 usage



% USAGE
% D = pdist2( X, Y, [metric] )
%
% INPUTS
% X - [m x p] matrix of m p-dimensional vectors
% Y - [n x p] matrix of n p-dimensional vectors
% metric - ['sqeuclidean'], 'chisq', 'cosine', 'emd', 'euclidean', 'L1'
%
% OUTPUTS
% D - [m x n] distance matrix


implementation of the distchisquared used from pdist2 implementation



%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function D = distChiSq( X, Y )

%%% supposedly it's possible to implement this without a loop!
m = size(X,1); n = size(Y,1);
mOnes = ones(1,m); D = zeros(m,n);
for i=1:n
yi = Y(i,:); yiRep = yi( mOnes, : );
s = yiRep + X; d = yiRep - X;
D(:,i) = sum( d.^2 ./ (s+eps), 2 );
end
D = D/2;


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Aucun commentaire:

Enregistrer un commentaire