【问题标题】:Optimizing code - calculation of Euclidean distance Sift优化代码——计算欧几里得距离 Sift
【发布时间】:2012-12-05 05:21:26
【问题描述】:

首先我很了解 Sift 中特征匹配背后的理论,我的问题是技术问题

所以我尝试计算第一个图像的向量和第二个图像的所有向量之间的欧几里得距离,然后如果最大的两个值之间的比率大于某个阈值,则匹配

这是我的代码

distRatio = 0.5;   
for i = 1:size(des1,1)
    eucl = zeros(size(des2,1));
    for j=1:size(des2,1)
           eucl(j) = sqrt(sum((des1(i,:)-des2(j,:)).^2));
    end;

    [vals,indx] = sort(eucl);        
    if (vals(1) < distRatio * vals(2))
      match(i) = indx(1);
    else
      match(i) = 0;
    end
end;

问题是它很慢,我知道原因,因为嵌套循环,它很慢,有没有办法优化它?抱歉,我对 Matlab 语法的体验很差。

【问题讨论】:

    标签: matlab sift


    【解决方案1】:

    在计算欧几里得距离时,您经常可以使用的一个巧妙技巧是修改您的算法以使用 squared 欧几里得距离 - 这消除了不必要的昂贵平方根函数,例如,如果您只想找到一组中的最大或最小距离。

    所以内部循环可能变成:

    distSquared(j) = sum((des1(i, :) - des2(j, :)).^2);
    

    在你的情况下,要改变的棘手的事情是行

    if (vals(1) < distRatio * vals(2))
    

    相当于

    if (vals(1)^2 < (distRatio * vals(2))^2)
    

    或者

    if (vals(1)^2 < (distRatio^2) * (vals(2)^2))
    

    如果您从 distSquared 而不是 eucl 获取值,那么您可以使用

    if (valSquared(1) < (distRatio^2) * valSquared(2))
    

    最后,您可以像这样重写减法来取出内部循环:

    countRowsDes2 = size(des2, 1); % this line outside the loop
    
    %... now inside the loop
        des1expand = repmat(des1(i, :), countRowsDes2, 1); % copy this row
    
        distSquared = sum((des1expand - des2).^2, 2);      % sum horizontally
    

    我使用repmat 复制行des1(i, :),并使用第二个维度参数使sum 在水平维度上工作。

    把它们放在一起

    distRatio = 0.5;
    distRatioSq = distRatio^2; % distance ratio squared
    countRowsDes1 = size(des1, 1); % number of rows in des1
    countRowsDes2 = size(des2, 1); % number of rows in des2
    
    match = zeros(countRowsDes1, 1); % pre-initialize with zeros
    
    for i = i:size(des1, 1)
        des1expand = repmat(des1(i, :), countRowsDes2, 1); % copy row i of des1
        distSquared = sum((des1expand - des2).^2, 2);      % sum horizontally
    
        [valsSquared, index] = sort(distSquared);
    
        if (valsSquared(1) < distRatioSq * valsSquared(2))
            match(i) = index(1);
        % else zero by initialization
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-07
      • 2020-11-29
      • 2021-01-31
      • 2018-02-14
      • 2015-09-23
      • 1970-01-01
      相关资源
      最近更新 更多