0

So I have a bunch of code thats been taking about a minute to run, traced it to the adaptive thresholding, one line in particular. Any suggestions as to how to speed this up or any explanation as to why this is unavoidable?..the "mIM=medfilt2(IM,[ws ws]);" is where everything slows down.

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);
Ratbert
  • 5,463
  • 2
  • 18
  • 37
user3470496
  • 141
  • 7
  • 33
  • Did you try `gpuArray` to perform the actions on your GPU? Your functions seems to be compatible to gpuArrays, use something like `gpuArray(imread(...))` when your read the image – Daniel Apr 02 '15 at 20:35
  • Median filtering is a non-linear operation, it is normal that it takes a long time. I'm not surprised, especially if the image is large or if `ws` is large. – Ratbert Apr 02 '15 at 20:43

1 Answers1

2

Median filtering is a non-linear operation, so it can take a long time to perform. For large values of ws, you should prefer ordfilt2 to medfilt2: it is both faster and more flexible !

Here is a sample code that does the same median filtering with both functions:

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

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

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

and the timing on my machine:

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

Best,

Ratbert
  • 5,463
  • 2
  • 18
  • 37