I lately had to implement a number of function that I had to apply to 2D matrices, for example a sliding window averager.
With each of these things I had to take into account that the operation I was doing was not the same if the element I was treating was in the corner or on the edge of the matrix. To continue my example I can't take the average of the surrounding values of the element in (0,0) because it would get me outside of the matrix.
Each time I face this my approach is different : I use imbricated ifs or do loops that doesn't start in the edges then treat them separately but I'm under the impression I'm not doing it the "best way".
I tried to search if there was a widely adopted approach for this problem but couldn't find that's why I'm asking for some input here.
I'm mainly using C, C++, matlab and python so if you have elegant ways of doing that in these languages I'm also interested!
Thank you.
So I think you're talking about convolution filters. I've had to deal with this problem before, and my solution was to create my own class for the 2D Grid that your sliding window is traversing. In that, I overload the lookup method, i.e. in C++
operator[]()
and have it check for an out of bounds value and return some value in its place.Some common solutions are:
(0,y)
takes the value at(0,y)
).Which option you go for depends on your application (which filter you are using). For example, if you are performing edge detection, with a Sobel filter, you probably want to use clamping, so that the edge of the image does not appear as a false edge in the image, however, if you are applying a mean filter, you will want to return the mean of the true values in the window for anything out of range (so that the out of range values don't affect the mean).
SHORT ANSWER There is no one answer, it's highly context specific.