% Use nlfilter2 for neighborhood processing. % nlfilter2 is not compatible with nlfilter. The function in nlfilter % works on an mxn block and must return a scalar. The function in nlfilter2 % works on an (mxn)x(MxN) matrix and must return a 1x(MxN) vector where M % and N are the number of rows and columns in the image. nlfilter calls its % function MxN times (once for each pixel). nlfilter2 calls its function % just once. nlfilter2 uses a lot more memory (it makes mxn copies of the % original image) but is much faster. Depending on the type of processing % anywhere from 10 to 1000 times faster.% % a_img = imread('testimg.png'); a_img = uint8(255*rand(250, 250)); [M N] = size(a_img); figure(1); imshow(a_img); b_img = im2double(a_img); % Use nlfilter for median processing nmedian1 = @(A) median(A(:)); tic d1_img = nlfilter(b_img, [3 3], nmedian1); e1 = toc; % Use nlfilter2 for median processing % You don't need to define nmedian2. You can just pass '@median' as the % function argument to nlfilter2. I defined it to make sure that I was % comparing apples to apples. nmedian2 = @(A) median(A); tic d2_img = nlfilter2(b_img, [3 3], nmedian2); e2 = toc; figure(2) printf('Sum of abs differences = %f\n', sum(sum(abs(d1_img-d2_img)))); printf('nlfilter2 is %f times faster than nlfilter1\n',e1/e2); imshow(d2_img);