You should always use inbuilt functions when possible.
nlfilter
is recommended for sliding window operations. colfilt
is the same but with usually better memory locality, you should use it.
neigh = [3,3];
I_mean = colfilt(I, neigh, 'sliding', @mean);
I_max = colfilt(I, neigh, 'sliding', @max);
I_min = colfilt(I, neigh, 'sliding', @min);
Standard deviation can be calculated using stdfilt
. colfilt(... @std)
requires a datatype conversion for some reason, and is ~4x slower on my machine.
I_std = stdfilt(I);
Returns a standard deviation image made with a 3x3 sliding window.
If by fair comparison you mean comparing speed, note that colfilt
and stdfilt
are quite different.
I_std = colfilt(double(I), neigh, 'sliding', @std);
You can also calculate the mean image via imfilter
. It's an order of magnitude faster, but the border pixel output is a bit different
tic;
meanh = fspecial('average', neigh);
I_mean = imfilter(I, meanh);
toc
Elapsed time is 0.024311 seconds.
vs.
tic;
I_mean2 = colfilt(I, neigh, 'sliding', @mean);
toc
Elapsed time is 0.649545 seconds.
Here's a illustration of the difference (double(I_mean)-double(I_mean2)
). Only the border pixels differ:

The speed difference grows larger and larger the bigger the neighbourhood is.