Corner and edge detection for operations on the elements of matrices

103 views Asked by At

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.

2

There are 2 answers

0
amnn On

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:

  • Return to some constant (like the min or max possible value in the grid).
  • Tile the grid (i.e. your grid is just one window into an infinite field of the same grid).
  • Clamp the grid (E.g. so that everything left of (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.

0
chill On

For the cost of a bit of extra memory, you can "surround" the matrix with zeros (or ones, or whatever is appropriate for your algorithm) like this:

000000
0abcd0
0efhg0
000000

and run the loops like:

  for (size_t i = 1; i < N - 1; ++i)
    for (size_t j = 1; j < M - 1; ++j)
       ...

Where N-1 and M-1 were your original matrix dimensions.