C - 二维卷积

C - 2D Convolution

我正在尝试用 C 语言进行矩阵卷积。

我已经尝试了一些但无法正确完成。

N[WIDTH1][WIDTH2]是输入矩阵,M[MASK_WIDTH1][MASK_WIDTH2]是核矩阵,P[][]是输出矩阵。

第一次尝试:

void convolution_2D(int N[][WIDTH2], int M[][MASK_WIDTH2], int P[][WIDTH2]) {

// find center position of kernel (half of kernel size)
int kCenterX = MASK_WIDTH2 / 2;
int kCenterY = MASK_WIDTH1 / 2;

for (int i = 0; i < WIDTH1; ++i)              // rows
{
    for (int j = 0; j < WIDTH2; ++j)          // columns
    {
        for (int m = 0; m < MASK_WIDTH1; ++m)     // kernel rows
        {
            int mm = MASK_WIDTH1 - 1 - m;      // row index

            for (int n = 0; n < MASK_WIDTH2; ++n) // kernel columns
            {
                int nn = MASK_WIDTH2 - 1 - n;  // column index

                // 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 < WIDTH1 && jj >= 0 && jj < WIDTH2)
                    P[i][j] += N[ii][jj] * M[mm][nn];
            }
        }
    }
}

问题是边界值不对,因为我选错了M矩阵的值。例如,对于 P[0][0],结果应该是,对于 NP 5x5 和 M 3x3:

P[0][0] = N[0][0]*M[1][1] + N[0][1]*M[1][2] + N[1][0]*M[2][1] + N[1][1]*M[2][2];

右下角是我需要的内核值;相反,该代码选择了左上部分,我无法编写代码来检查正确的值。

The values of the kernel that I need are the lower right part; instead, that code picks the upper left part and I can't write the code to check the right values.

这是因为您在计算 mmnn 时翻转了遮罩索引。只需删除这些行并使用 mn 索引掩码:

if (ii >= 0 && ii < WIDTH1 && jj >= 0 && jj < WIDTH2)
    P[i][j] += N[ii][jj] * M[m][n];