CS50 pset4中的模糊功能不能完全正常工作。

问题描述 投票:0回答:1

我花了两天时间试图纠正我的模糊给定图像的功能,但尽管进行了大量的校对,现在它只在角落的情况下正确工作。对于其他情况,它在RGB值上产生了2-20+的差异。

这个任务是哈佛大学CS50课程的一部分(更多信息请参见pset4)。https:/cs50.harvard.edux2020psets4filterless。).

我看了网上能找到的所有东西,也试过用那些小技巧,比如用浮点数除以新的RGB值,直接把结果复制回原图,调整if条件,但这都无济于事,我还是不知道哪里出了问题。非常希望得到帮助,谢谢!

 // Blur image
 void blur(int height, int width, RGBTRIPLE image[height][width])
 {
    float new_red, new_blue, new_green;
    new_red = new_blue = new_green = 0;

    int count = 0;

    // Copy the image
    RGBTRIPLE temp[height][width];

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

    // Loop through height
    for (int i = 0; i < height; i++)
    {
        // Loop through width
        for (int j = 0; j < width; j++)
        {
            // Loop through rows around a pixel
            for (int k = -1; k <= 1; k++)
            {
                // Loop through columns around a pixel
                for (int m = -1; m <= 1; m++)
                {
                    if (i + k >= 0 && i + k < height && j + m >= 0 && j + m < width)
                    {
                        count++;
                        new_red += temp[i + k][j + m].rgbtRed;
                        new_blue += temp[i + k][j + m].rgbtBlue;
                        new_green += temp[i + k][j + m].rgbtGreen;
                    }
                }
            }

            temp[i][j].rgbtBlue = round(new_blue / count);
            temp[i][j].rgbtRed = round(new_red / count);
            temp[i][j].rgbtGreen = round(new_green / count);
        }

    }

    // Copy the blurred image to original file
    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
        {
            image[i][j] = temp[i][j];
        }
    }

    return;
}
c blur cs50
1个回答
2
投票

我假设你想为每个像素重置count、new_blue、new_red和new_green。在你的代码中,当你处理图像时,这些值会继续增长。

// Loop through height
for (int i = 0; i < height; i++)
{
    // Loop through width
    for (int j = 0; j < width; j++)
    {
        count = new_blue = new_red = new_green = 0;

在调试时,你可以通过打印出每个像素的变量值来发现这个问题,然后再进行分割和赋值。你可能已经注意到,计数值太高了。

我相信另一个问题是你在临时图像中模糊了像素的位置。当你模糊一个像素时,你会使用它上面的像素的已经模糊的值。相反,你可能想在最里面的循环中使用原始图像。

                    new_red += image[i + k][j + m].rgbtRed;
                    new_blue += image[i + k][j + m].rgbtBlue;
                    new_green += image[i + k][j + m].rgbtGreen
© www.soinside.com 2019 - 2024. All rights reserved.