我正在尝试用 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]
,对于 N
和 P
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.
这是因为您在计算 mm
和 nn
时翻转了掩码索引。只需删除这些行并使用 m
和 n
来索引掩码:
if (ii >= 0 && ii < WIDTH1 && jj >= 0 && jj < WIDTH2)
P[i][j] += N[ii][jj] * M[m][n];
关于C - 二维卷积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41452226/