简体   繁体   English

如何减少 MATLAB 中图像匹配代码的运行时间?

[英]How can I reduce runtime in my image matching code in MATLAB?

I am trying to stabilize a video file in MATLAB using a simple image matching algorithm.我正在尝试使用简单的图像匹配算法来稳定 MATLAB 中的视频文件。 Basically, I am taking a window of the first frame of the video and subtracting it with the nth frame.基本上,我将视频第一帧的 window 与第 n 帧相减。 I want to end up with an array of x and y displacement vectors from the position of the nth frame to the first frame.我想得到一个从第 n 帧的 position 到第一帧的 x 和 y 位移向量数组。 The video is in a 1501x971 grayscale format with 391 frames.视频采用 1501x971 灰度格式,391 帧。

Below is my code.下面是我的代码。 I have let the code run for 15+ minutes and still running.我已经让代码运行了 15 分钟以上并且仍在运行。 I have been searching for answers and implemented the int8 and preallocating matrix solutions that I've seen people suggesting but it still runs too long.我一直在寻找答案并实施了我看到人们建议的 int8 和预分配矩阵解决方案,但它仍然运行时间太长。 Any help would be appreciated.任何帮助,将不胜感激。

% 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

Use a profiler.使用分析器。

profile on;
your_script_name;
profile viewer;

this tells you which lines of your code consumed most of the runtime.这会告诉您哪些代码行消耗了大部分运行时。

the output looks like this https://www.mathworks.com/help/matlab/matlab_prog/profiling-for-improving-performance.html output看起来像这样

but from reading your code, you should consider vectorizing your code by operating on matrix/vector level instead of operating on element-level using for-loops.但是通过阅读您的代码,您应该考虑通过在矩阵/向量级别上操作而不是使用 for 循环在元素级别上操作来对代码进行矢量化。 see tutorials in this post请参阅这篇文章中的教程

Faster way to looping pixel by pixel to calculate entropy in an image 逐像素循环以计算图像熵的更快方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM