# Caught In The Convolution Matrix

• 11-25-2007
SMurf
Caught In The Convolution Matrix
Hello,

Although this isn't strictly to do with game programming per se (although it may now be possible to do this in real-time, I haven't checked ;)), I was wondering if someone could help with a spot of image processing that I'm trying to do.

I'm currently trying to implement a simple edge detection algorithm using the following convolution matrix:-
Code:

```-1 -1 -1 -1  8 -1 -1 -1 -1```
This is a fairly standard operator used for the detection of edges within an image, and it works great (I thought it was a lot harder than it turned out!), comparing the results with Paint Shop Pro's efforts show them to be nearly identical.

Nearly, because unfortunately I can't work out how best to handle the left, top, right and bottom edges of the rectangle that is the image itself. The problem is, for example, when processing the pixel at the top-left corner of the bitmap (0, 0), part of the matrix is acting outside of the image and so has no effect. To illustrate using a mask:-
Code:

```X is the position of pixel (0, 0) -1 -1 -1      0 0 0 -1  8 -1 into 0 X 1 -1 -1 -1      0 1 1```
Now, what I'm currently doing is testing if the calculated pixel to read is outside the range of the image. If it is, then a count is incremented and nothing is added to the output sample. At the end of the matrix operation, if there were any pixels clipped then the output sample is:-
Code:

`sample = (int)(sample * ((double)numclipped / 9));`
However, this doesn't compare favourably to what PSP does. The outer edge is much brighter on mine, suggesting that I'm not doing it right. Any ideas?
• 11-25-2007
Sang-drax
I would handle edges and corners the following way:
*In the interior of the image, the middle of the matrix is 8.
*Along an edge, the middle element of the matrix is 5.
*At a corner, the middle element is 3.
Then use 0 for 'non-existent' elements outside the image.
• 11-25-2007
SMurf
Thanks Sang-Drax, after including your suggestion the output now looks better and is the same "shape" as the output Paint Shop Pro provides, although the actual values along the edge are more distinct in the PSP version. It must be using a similar algorithm, doing it slightly differently on the edges. :confused:
• 11-25-2007
Sang-drax
Well, you could also replicate nonexistent values with the nearest existing value.

But think about it: edge detection along an edge? It doesn't make sense to care about the value there. I suggest that you only do edge detection along the x-direction at the top and bottom and only along the y-direction at the left and right edge of the image.

I.e.
0 1 0
0 -2 0
0 1 0
along the left and right border.