在matlab中计算RGB图像之间的卡方距离

时间:2015-04-09 15:52:18

标签: image matlab histogram

我正在尝试测试照片RGB直方图以使用卡方距离在训练数据中找到最接近的直方图我使用的chisq函数返回每个R,G,B直方图的差异矩阵我怎么能得到1表示两个图像差异最小的值

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
%  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

从pdist2实现中使用的distchisquared的实现

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
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;


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

0 个答案:

没有答案