【问题标题】:How can I reduce runtime in my image matching code in MATLAB?如何在 MATLAB 中减少图像匹配代码的运行时间?
【发布时间】:2020-07-18 00:10:26
【问题描述】:

我正在尝试使用简单的图像匹配算法来稳定 MATLAB 中的视频文件。基本上,我正在拍摄视频第一帧的窗口,然后用第 n 帧减去它。我想得到一个从第 n 帧位置到第一帧的 x 和 y 位移向量数组。视频采用 1501x971 灰度格式,包含 391 帧。

下面是我的代码。我已经让代码运行了 15 分钟以上并且仍在运行。我一直在寻找答案并实施了我看到人们建议的 int8 和预分配矩阵解决方案,但它仍然运行时间太长。任何帮助将不胜感激。

% Define image region (window)
xmin = 35;
xmax = 1465;
ymin = 35;
ymax = 940;

% Matching algorithm
error = uint16(10^8); % set error to a larger number than expecting in the loop
deltax = 0;
deltay = 0;
deltaxArray = zeros(1,N,'int8');    % prealloacting arrays
deltayArray = zeros(1,N,'int8');    % using int8 to optimize code
deltaxArray(1) = 0;
deltayArray(1) = 0;

for n = 2:N % N = number of frames
    for deltay = -34:31         % Iterating over all possible displacements
        for deltax = -34:36
            current_error = uint16(sum(abs(f(1, ymin+deltay:ymax+deltay , xmin+deltax:xmax+deltax ) - f(n, ymin:ymax, xmin:xmax)),'all'));        % f is the video array
            if current_error < error        % searching for the smallest error in the nth frame
                error = current_error;      % set error if current error is smaller
                deltaxArray(n) = deltax;    % save x displacement coordinate
                deltayArray(n) = deltay;    % save y displacement coordinate
            end
        end
    end
    error = uint16(10^8);   % reset error for next iteration
end

【问题讨论】:

  • 我不是 matlab 视频处理方面的专家。但是你有三层 for 循环,在里面看起来至少还有两层 :sum,理论上你正在使用 O(n^5) 算法。这通常意味着它非常非常慢......看看你是否可以降低迭代水平

标签: matlab image-processing optimization nested-loops image-stabilization


【解决方案1】:

使用分析器。

profile on;
your_script_name;
profile viewer;

这告诉您哪些代码行消耗了大部分运行时。

输出看起来像这样 https://www.mathworks.com/help/matlab/matlab_prog/profiling-for-improving-performance.html

但是通过阅读您的代码,您应该考虑通过在矩阵/向量级别上操作而不是使用 for 循环在元素级别上操作来对代码进行矢量化。请参阅这篇文章中的教程

Faster way to looping pixel by pixel to calculate entropy in an image

【讨论】:

  • 不幸的是,我认为我无法矢量化我的 for 循环,因为我使用循环变量来填充循环内的数组。也许有一种方法可以使用不同的优化算法,但我很难减少这段代码的运行时间。
猜你喜欢
  • 2016-07-24
  • 1970-01-01
  • 1970-01-01
  • 2017-07-14
  • 2021-12-02
  • 1970-01-01
  • 1970-01-01
  • 2015-06-02
相关资源
最近更新 更多