2016-05-14 78 views
0

我一直在尝试在1维阵列上实现卷积算法,但需要将其表示为2D NxM矩阵。试图执行一个类似的方法后:图像卷积和边界

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]; 
      } 
     } 
    } 
} 

来源:http://www.songho.ca/dsp/convolution/convolution.html#convolution_2d

而鉴于给出的两个矩阵是:

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 

的问题是谁开发的编码器就设置边界外的所有值都是0.那么,我可以使用什么方法来检查某个元素何时位于数组边缘,然后推出这些值,以便使用内核值进行计算。基本上代表矩阵为:

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 
+0

另外我也困惑的线: 如果(ⅱ> = 0 &&二 = 0 && jj user3696819

回答

1

这里是更新的代码

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]; 

      } 
     } 
    } 
}