首页 > 解决方案 > cs50 pset4 反映图片滤镜代码问题

问题描述

我正在研究 cs50 pset4 练习滤镜,我完成了灰度滤镜和棕褐色滤镜,现在我在使用反射滤镜。我应该水平地反映这个图像:

普通的

在此处输入图像描述

但我得到的只是:

反映

在此处输入图像描述

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

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

请帮我理解。当我用谷歌搜索它时,我得到的要么是不同的东西,要么是整个练习的答案,这只是从谷歌复制粘贴。

非常感谢,迷失在代码中:)

标签: cfiltercs50image-manipulation

解决方案


您在保存之前覆盖 image[j][width - 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,指出我犯的一个错误。


推荐阅读