2015-04-02 97 views
0

所以我有一堆代碼需要花費大約一分鐘的時間來運行,將它跟蹤到自適應閾值,特別是一行。關於如何加速或解釋爲什麼這是不可避免的任何建議?「mIM = medfilt2(IM,[ws ws]);」是一切放緩的地方。MATLAB自適應閾值超慢

function bw=adaptivethreshold(IM,ws,C,tm) 
%ADAPTIVETHRESHOLD An adaptive thresholding algorithm that seperates the 
%foreground from the background with nonuniform illumination. 
% bw=adaptivethreshold(IM,ws,C) outputs a binary image bw with the local 
% threshold mean-C or median-C to the image IM. 
% ws is the local window size. 
% tm is 0 or 1, a switch between mean and median. tm=0 mean(default); tm=1 median. 
% 
% Contributed by ... 
% at Tsinghua University, Beijing, China. 
% 
% For more information, please see 
% http://homepages.inf.ed.ac.uk/rbf/HIPR2/adpthrsh.htm 

if (nargin<3) 
    error('You must provide the image IM, the window size ws, and C.'); 
elseif (nargin==3) 
    tm=0; 
elseif (tm~=0 && tm~=1) 
    error('tm must be 0 or 1.'); 
end 

IM=mat2gray(IM); 
disp(strcat('100: ',datestr(now))) 
if tm==0 
    mIM=imfilter(IM,fspecial('average',ws),'replicate'); 
else 
    mIM=medfilt2(IM,[ws ws]); 
end 
sIM=mIM-IM-C; 
bw=im2bw(sIM,0); 
bw=imcomplement(bw); 
+0

你嘗試'gpuArray '在GPU上執行操作?您的函數似乎與gpuArrays兼容,當您讀取圖像時使用類似'gpuArray(imread(...))'的方法 – Daniel 2015-04-02 20:35:40

+0

中值濾波是一種非線性操作,這是很正常的,需要很長時間。我並不感到驚訝,特別是如果圖像很大或者「ws」很大。 – Ratbert 2015-04-02 20:43:47

回答

2

中值濾波是一種非線性操作,因此可能需要很長時間才能執行。對於ws的較大值,您應該更喜歡ordfilt2medfilt2:它既快又靈活!

這裏是一個示例代碼,做同樣的正中有兩種功能過濾:

Img = imread('elephant.jpg'); 
ws = 100; 

tic 
Res = medfilt2(Img, [ws ws]); 
toc 

tic 
Res = ordfilt2(Img, round(ws^2/2), true(ws)); 
toc 

和我的機器上的時間:

Elapsed time is 0.190697 seconds. 
Elapsed time is 0.095528 seconds. 

最佳,