CS50 模糊滤镜 - 图像颠倒

时间:2021-04-11 16:07:18

标签: c cs50

我正在处理 CS50 滤镜挑战,特别是模糊挑战。

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

你知道问题出在哪里吗?

converted picture original picture

这是我的代码:

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;
    }
}

}

1 个答案:

答案 0 :(得分:1)

您似乎在这里交换了宽度和高度:

            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 向下增加的注释可能是可取的。

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