CS50 pset4反映图像过滤器代码问题

时间:2020-08-15 09:54:28

标签: c filter cs50 reflect

我正在使用cs50 pset4运动滤镜,并且完成了灰度滤镜和棕褐色滤镜,现在我在反射滤镜上。我应该水平反射该图像:

正常

enter image description here

但是我得到的只是这个:

引用

enter image description here

我不知道怎么了。我尝试像视频中那样做。在我的代码中,我尝试将右侧像素放入一个临时变量中,然后将左侧像素放入其位置,然后取出右侧像素并将其放入左侧像素点。这是我的代码(仅反映部分):

// Reflect image horizontally
void reflect(int height, int width, RGBTRIPLE image[height][width])
{
    for (int j = 0; j < height;j++)
    {
    for (int i = 0; i < width/2;i++)
    {
        RGBTRIPLE temp = image[j][i];
       image[j][width - i] = image[i][j];
       temp = image[j][width - i];
       
    }
    }
  
    return;
}

请帮助我理解。当我用谷歌搜索时,我所得到的要么是与众不同,要么是整个练习的答案,而这只是谷歌的复制粘贴。

非常感谢, 代码丢失:)

2 个答案:

答案 0 :(得分:2)

您在保存图像之前覆盖了图像[j] [宽度-i]
并且您有一个案例换了i,j。

我建议交换保存,覆盖和还原的顺序。

void reflect(int height, int width, RGBTRIPLE image[height][width])
{
    for (int y = 0; y < height; y++)
    {
        for (int x = 0; x  < width/2; x++)
        {
            RGBTRIPLE temp = image[y][width -1 - x]; //save what gets overwritten

            // then overwrite
            image[y][width -1 - x] = image[y][x]; // note the wrong i,j which was here before
            
            // then overwrite the other with what was saved
            image[y][x] = temp;
        }
    }
  
    return;
}

问题是您拥有的[i] [j]。应该是[j] [i]。 使用名称x,y可以更容易地发现这种问题。

谢谢MikeCat,指出了我犯的一个错误。

答案 1 :(得分:2)

RGBTRIPLE temp = image[j][i];
image[j][width - i] = image[i][j];
temp = image[j][width - i];

是错误的,因为

  • 未保存的像素将被覆盖,而不是覆盖已保存的像素。
  • 您不想在这里使用image[i][j]而不是image[j][i]
  • width - i应该是width - i - 1。例如,当i = 0时,width - i将是width,并且超出范围。
  • 您两次重写temp,而不是将新值分配给两个像素。

应该是:

RGBTRIPLE temp = image[j][i];
image[j][i] = image[j][width - i - 1];
image[j][width - i - 1] = temp;