When doing advanced stuff such as image processing, it is very wasteful to re-invent a wheel. This time this is about a very common operation as a sliding window operation. Imagine that we have an image I and a small region MxN (called ROI – Region of Interest) that we want to slide over the I image. What for? We may do many things:
- image enhancement;
- collecting statistics as average, standard deviation etc
- etc
In my case I wanted to collect a simple statistics as sum of pixel values under this ROI. Instead of writing my custom function doing loop inside loop, I devoted some time to search over net. I felt that all the necessary tools are already there in my machine and waiting that I start using them. That was the case – a single function “nlfilter” [REF] from Image Processing toolbox in MATLAB will do all the magic.
Few steps are necessary:
- Define a function that will return a scalar for every ROI:
fun = @(x) sum( x(:) ); <— notice that output of this function should be a scalar! - Define the size of the sliding ROI:
w = [m n]; <— m – height, n – width - Compute the output image (can take some time):
B = nlfilter( I, w, fun ); - <Do some stuff with the matrix B>
Notice that input of the algorithm is an image (matrix of values) and output is an image (matrix of values). This is up to you to make sense of the value in input/output and the workings of the function!
Finally, depending on your needs, this function can be suboptimal. For example, if you want to do convolution or other filtering in signal processing, use conv2 instead!
As you noticed, the Image Processing toolbox [WWW] is necessary to get this operation done. If somebody has pointers to a freely available MEX implementation, please let me know.