使用Matlab的分析工具!
profile on % Starts the profiler
% Run some code now.
profile viewer % Shows you how often each function was called, and
% where most time was spent. Try to start with the slowest part.
profile off % Resets the Profiler, so you can measure again.
預分配
預分配和輸出,因爲你知道的大小這樣它的速度要快得多。 (Matlab的告訴你,這已經!)
GreenROI = zeros(length(p_g_x), NumberImages); % And the same for RedROI.
使用卷積
閱讀有關Matlab的conv2
代碼。
for s=1:NumberImages
im=imread(fn(s,1).name);
im=im-medfilt2(im,[15,15]);
% Pre-compute the sums first. This will only be faster for large p_g_x
roi_image = conv2(im, ones(5,5));
for i=1:length(p_g_x)
GreenROI(i,s)=roi_image(round(p_g_y(i)), round(p_g_x(i))); % You might have to offset the indices by 2, because of the convolution. Check that results are the same.
RedROI(i,s)=roi_image(round(p_r_y(i)), round(p_r_x(i)));
end
end
Matlab的IZE代碼
現在,您已經使用卷積拿到過5×5的窗口總和的圖像(或者你可以使用過夏嘉曦@的accumarray
,同樣的事情),你可以通過不重複遍歷中的每個元素,可以進一步加快速度,但可以立即使用它作爲矢量。
我把這留給讀者作爲練習。 (作爲提示,將p_g_x
和p_g_y
轉換爲使用sub2ind
的索引)。
更新
我們的答案,包括礦山,表明過早的優化是一個多麼糟糕的事情。不知道,我認爲你的循環會佔用大部分時間,但是當你測量它時(謝謝!)事實證明,這不是問題。瓶頸是medfilt2
中值過濾器,這需要90%的時間。所以你應該首先解決這個問題。(請注意,在我的電腦上,您的原始代碼足夠我的口味,但它仍然是大部分時間佔用的中值濾波器。)
看看中值濾波器操作的作用可能會幫助我們弄清楚如何使其更快。這是一張圖片。在左邊看到原始圖像。中間是中值濾波器,右邊是結果。
對我來說,結果看起來非常類似於邊緣檢測結果。 (在數學上,這並不奇怪。)
我建議你開始試驗各種邊緣檢測。看看Canny和Sobel。或者只是使用conv2(image, kernel_x)
,其中kernel_x = [1, 2, 1; 0, 0, 0; -1, -2, -1]
與kernel_y
相同,但轉置。您可以在這裏找到各種邊緣檢測選項:edge(im, option)
。我嘗試了{'sobel', 'canny', 'roberts', 'prewitt'}
的所有選項。除Canny之外,它們都與中位數過濾方法大致相同。 Canny的速度慢了4倍,其餘的(包括原來的)都是7.x秒。所有這些都沒有GPU。 imgradient
是9秒。
因此,從這我會說,你不能得到任何更快。如果你有一個GPU,它可以和Matlab協同工作,你可以加快速度。加載你的圖像爲gpuArray
s。在medfilt2 documentation上有一個例子。你仍然可以做小幅加速,但它們只能達到10%的速度提升,所以幾乎不可能。
您正在總結5x5以上的區域,而不是4x4 ... – Unapiedra 2014-09-04 08:40:06
區域是否重疊? – Shai 2014-09-04 08:42:28
請用你在'p_g_x'和'p_g_y'中使用的值編輯你的問題。如果這太大,請添加一個相同的較小樣本。 – Unapiedra 2014-09-04 08:43:21