matlab - 优化代码——欧氏距离Sift的计算

标签 matlab sift

首先我很清楚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 语法的经验很差。

最佳答案

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

所以内循环可能变成:

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

关于matlab - 优化代码——欧氏距离Sift的计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13925584/

相关文章:

matlab - swift 是否有等效的 "eval"函数,就像在 Matlab 中一样?

MATLAB 格式化矩阵

matlab - 一般数据集的数据增强技术?

matlab - 在 Matlab 中生成随机矩阵

OpenCV - 从预裁剪的补丁中提取 SIFT/SURF 描述符

c - 在 Matlab 中使用 calllib 从 C 头文件获取常量和枚举值

c++ - SIFT detectAndCompute 抛出 ipp 异常

c++ - 具有 k = 2 的 knnMatch 返回 0 最近邻,即使图像经过训练

c++ - 进行 knnMatch 后的 .distance 是什么?

Python。 K近邻TypeError : samples data type = 17 is not supported