C - 二维卷积

标签 c matrix 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];

关于C - 二维卷积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41452226/

相关文章:

c - 获取段错误

在 C 中使用 MPI 进行代码并行化

Java将数组切割成不均匀矩阵的最快方法

python - scipy.signal.fftconvolve-更多详细信息?

algorithm - 卷积的有效方法,如求和评估

康威的生命游戏缓冲区下溢

c - ifconfig->which 的结果是我要提供给 TCP/IP 套接字的 IP 地址

java - 使用 Matrix4f 围绕多个轴进行框旋转

matlab - 逐行setdiff而不在matlab中使用循环

algorithm - 如何用卷积解决精确模式匹配