是否有用于复制存储在二维数组中的相邻像素值的算法?

Is there an algorithm for copying neighboring pixel values stored in a 2D-Array?

我有一个二维灰度像素值数组,看起来像

255 250 250 250 235 251 255 201
255 250 250 250 235 251 255 151
255 250 250 250 235 251 255 151
255 250 250 250 235 251 255 151
255 250 250 250 235 251 255 151

在我在网上和其他帖子中看到的实现中,程序将专门获取 3x3 window 区域中的相邻像素。

例如,

for (row = 1; row <= numRows; ++row)
{
    for (col = 1; col <= numCols; ++col)
    {
        //neighbor pixel values are stored in window including this pixel 
        window[0] = imageArr[row - 1][col - 1];
        window[1] = imageArr[row - 1][col];
        window[2] = imageArr[row - 1][col + 1];
        window[3] = imageArr[row][col - 1];
        window[4] = imageArr[row][col];
        window[5] = imageArr[row][col + 1];
        window[6] = imageArr[row + 1][col - 1];
        window[7] = imageArr[row + 1][col];
        window[8] = imageArr[row + 1][col + 1];
        
        // do something with window
    }
}

我正在尝试实现更动态的 window 大小。 前任。如果用户想在一个4x4区域或者5x5区域

中寻找相邻像素

我本来不打算回答这个问题,但现在我已经在评论中写了很多东西了。

一般建议是通过将 rowcol 视为 window 的左上角而不是中心来简化循环。这使数学变得简单明了(因此对于任何阅读代码的人来说都更加清晰),尤其是对于大小为偶数 window 维度的情况。

假设 window 是正方形(维度 N),这似乎是您的要求,外循环变为:

for (int row = 0; row < numRows - N; ++row)
{
    for (int col = 0; col < numCols - N; ++col)
    {
        // TODO: copy window

        // Your window's "center" if you need it
        int cx = col + N/2;
        int cy = row + N/2;

        // TODO: Do something with window...
    }
}

现在,让我们执行“复制 window”循环。这是一个简单的 NxN 图像副本,其中源位置为 [row + y][col + x]:

// Copy window
for (int y = 0; y < N; ++y)
{
    for (int x = 0; x < N ++x)
    {
        window[y * N + x] = imageArr[row + y][col + x];
    }
}

如果需要,将其扩展为矩形非常简单 windows,这将是您尝试的一个很好的练习。各种优化都是可以的,但我认为以你现在的水平,这超出了范围,我其实不想向初学者推广优化。不如学会写简单明了的代码。