Reputation: 25
I've been attempting at implementing the convolution algorithm onto a 1 dimensional array but needs to be represented as a 2D NxM matrix. After attempting to implement a method similar to this:
int kCenterX = kCol / 2;
int kCenterY = kRow / 2;
for(int i=0; i < mRow; ++i) { // rows
for(int j=0; j < mCol; ++j) { // columns
for(int m=0; m < kRow; ++m) { // kernel rows
int mm = kRow - 1 - m; // row index of flipped kernel
for(int n=0; n < kCol; ++n) { // kernel columns
int nn = kCol - 1 - n; // column index of flipped kernel
// index of input signal, used for checking boundary
int ii = i + (m - kCenterY);
int jj = j + (n - kCenterX);
// ignore input samples which are out of bound
if( ii >= 0 && ii < mRow && jj >= 0 && jj < mCol )
o[i][j] += input[ii][jj] * kern[mm][n];
}
}
}
}
source: http://www.songho.ca/dsp/convolution/convolution.html#convolution_2d
And given that the two matrices given are:
input = {1,2,3,4,5,6,7,8,9,10,11,12,15,16};
// 1 2 3 4
// 5 6 7 8
// 9 10 11 12
// 13 14 15 16
sharpen_kernel = {0,-1,0,-1,5,-1,0,-1,0};
// 0 -1 0
// -1 5 -1
// 0 -1 0
The issue is the coder who developed it set that all values outside the edges are 0. So what method could I use to check when an element is on the edge of an array and then push out those values so they would get calculated with the kernel values. Essentially to represent the matrix as:
1 1 2 3 4 4
1 *1 2 3 4* 4
5 *5 6 7 8* 8
9 *9 10 11 12* 12
13 *13 14 15 16* 16
13 13 14 15 16 16
Upvotes: 0
Views: 3822
Reputation: 2132
Here is the updated code
int kCenterX = kCol / 2;
int kCenterY = kRow / 2;
for(int i=0; i < mRow; ++i) { // rows
for(int j=0; j < mCol; ++j) { // columns
for(int m=0; m < kRow; ++m) { // kernel rows
int mm = kRow - 1 - m; // row index of flipped kernel
for(int n=0; n < kCol; ++n) { // kernel columns
int nn = kCol - 1 - n; // column index of flipped kernel
// index of input signal, used for checking boundary
int ii = i + (m - kCenterY);
int jj = j + (n - kCenterX);
if(ii < 0)
ii=ii+1;
if(jj < 0)
jj=jj+1;
if(ii >= mRow)
ii=ii-1;
if(jj >= mCol)
jj=jj-1;
if( ii >= 0 && ii < mRow && jj >= 0 && jj < mCol )
o[i][j] += input[ii][jj] * kern[mm][n];
}
}
}
}
Upvotes: 1