CS50 模糊滤镜 - 图像上下颠倒

CS50 Blur Filter - Image is turned upside down

我正在应对 CS50 滤镜挑战,特别是模糊挑战。

它编译得很好,但是当我创建图像时,图像旋转了 90 度,图像底部是图像错误。

你知道问题出在哪里吗?

这是我的代码:

void blur(int height, int width, RGBTRIPLE image[height][width])

{
    float sum_blue;
    float sum_green;
    float sum_red;
    float counter;

    RGBTRIPLE temp[height][width];

    for (int i = 0; i < height; i++)
    {

        for (int j = 0; j < width; j++)
        {
            sum_blue = 0;
            sum_green = 0;
            sum_red = 0;
            counter = 0;
       
        for (int h= -1; h < 2; h++)
        {
            if (j + h < 0 || j + h > width - 1)
            {
                continue;
            }

        for (int v = -1; v < 2; v++)
            {
                if (i + v < 0 || i + v > height - 1)
                {
                    continue;
                }

                sum_red += image[j + h][i + v].rgbtRed;
                sum_blue += image[j + h][i + v].rgbtBlue;
                sum_green += image[j + h][i + v].rgbtGreen;
                counter++;
            }
        }


        //summarize all values and save the pixels in a temporary image to transfer it later
        temp[i][j].rgbtRed = round(sum_red / counter);
        temp[i][j].rgbtBlue = round(sum_blue / counter);
        temp[i][j].rgbtGreen = round(sum_green / counter);

    }
}

// transfer temporary to real image

for (int i = 0; i < height; i++)
{
    for (int j = 0; j < width; j++)
    {
        image[i][j].rgbtRed = temp[i][j].rgbtRed;
        image[i][j].rgbtBlue = temp[i][j].rgbtBlue;
        image[i][j].rgbtGreen = temp[i][j].rgbtGreen;
    }
}

}

您似乎在此处调换了宽度和高度:

            sum_red += image[j + h][i + v].rgbtRed;
            sum_blue += image[j + h][i + v].rgbtBlue;
            sum_green += image[j + h][i + v].rgbtGreen;

我预计:

            sum_red += image[i + v][j + h].rgbtRed;
            sum_blue += image[i + v][j + h].rgbtBlue;
            sum_green += image[i + v][j + h].rgbtGreen;

因为图像数组是 [height][width]i 是垂直迭代器,j 是水平迭代器。可能只有 ij 被交换了,i + hj + v 是有意的。

可能变量在算法的其他地方被交换了。更好的变量命名可能会有所帮助 - 因此名称表明它们代表什么。即使是 xy 也会更清楚,因为这是笛卡尔坐标的约定——尽管注释指示左上原点和 y 向下增加可能是可取的。

通过以错误的顺序获取索引,您已经旋转和镜像它并处理了图像错误部分的数据或根本不在图像中。