0

我必須計算兩個不同圖像分佈的Kullback-Leibler(KL)距離。假設我有兩個尺寸爲5694x1和231x1的圖像。現在,我想計算這些圖像中兩個分佈的KL距離。我嘗試在matlab中做,但它沒有運行。你能幫我嗎?問題是兩個分佈的矩陣不是相同的大小。您可以在imagetestKullback-Leibler之間的距離2圖像分佈matlab

%%Main function to calculate KL 
function d=KLdist(firstImg,secondImg) 
    h1 = histogram(firstImg, max(firstImg(:))+1, 0, max(firstImg(:))); 
    h2 = histogram(secondImg, max(secondImg(:))+1, 0, max(secondImg(:))); 
    h1(find(h1==0))=1; 
    h2(find(h2==0))=1; 
    temp = sum(h1.*log(h1./h2)); 
    temp(isinf(temp)) = 0; % this resloves where h1(i) == 0 
    d1 = sum(temp); 
    temp = sum(h2.*log(h2./h1)); % other direction of compare since it's not symetric 
    temp(isinf(temp)) = 0; 
    d2 = sum(temp); 
    d = d1 + d2 
end 

%%Function to calculate histogram distribution 
function [h,bins] = histogram(I, n, min, max) 
I = I(:); 
range = max - min; 
drdb = range/double(n); % dr/db - change in range per bin 
h = zeros(n,1); 
bins = zeros(n,1); 
for i=1:n 
    % note: while the instructions say "within integer round off" I'm leaving 
    %  this as float bin edges, to handle the potential float input 
    %  ie - say the input was a probability image. 
    low = min + (i-1)*drdb; 
    high = min + i*drdb; 
    h(i) = sum((I>=low) .* (I<high)); 
    bins(i) = low; 
end 
h(n) = h(n) + sum((I>=(n*drdb)) .* (I<=max)); % include anything we may have missed in the last bin. 
h = h ./ sum(h); % "relative frequency" 
end 

回答

0

下載圖像測試你就不能計算在不同大小的向量KL發散。您必須調整直方圖的大小才能在兩種情況下獲得相同的大小。

因此,在調用函數直方圖時,爲所有輸入設置恆定數量的分檔。

+0

如果我用h1 =直方圖(firstImg,255 + 1,0255)編輯,怎麼樣?而不是h1 =直方圖(firstImg,max(firstImg(:))+ 1,0,max(firstImg(:))); – user3336190

+0

@ user3336190是的,它應該工作。 – Bentoy13

+0

#Bentoy13:但我不確定它是否正確 – user3336190