CS50 PSet4-模糊滤镜,我正在获得黑色图像作为输出

时间:2020-06-12 00:49:53

标签: c cs50

我正在为pset4,过滤器,cs50的模糊编写代码。但是我的输出图像是黑色的,或者根本无法给出正确的输出。我一直遇到这个问题。

我的模糊功能出了什么问题?

void blur(int height, int width, RGBTRIPLE image[height][width])
{
    RGBTRIPLE temp[height][width];
    int sumRed;
    int sumGreen;
    int sumBlue;
    int counter;

    for (int i = 0; i < width; i++)
    {
        for (int n = 0; n < height; n++)
        {
            //Resetting sums to 0
            sumRed = 0;
            sumGreen = 0;
            sumBlue = 0;
            counter = 0;

            for (int x = -1; x < 2; x++)
            {

                if (x + i < 0 || x + i > width - 1)
                {
                    continue;
                }

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

                    sumRed += temp[y + n][x + i].rgbtRed;
                    sumGreen += temp[y + n][x + i].rgbtGreen;
                    sumBlue += temp[y + n][x + i].rgbtBlue;
                    counter++;

                }

            }

            temp[n][i].rgbtRed = round(sumRed / counter);
            temp[n][i].rgbtGreen = round(sumGreen / counter);
            temp[n][i].rgbtBlue = round(sumBlue / counter);
        }
    }

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

    return;
}

1 个答案:

答案 0 :(得分:3)

您在temp上进行计算并同时更改temp,这是错误的。因为随着temp的变化,将对修改后的像素进行新的像素模糊计算。计算应始终对原始图像进行,然后应将图像分配给临时值。更详细的解释是here

基本上,这段代码

temp[n][i].rgbtRed = round(sumRed / counter);
temp[n][i].rgbtGreen = round(sumGreen / counter);
temp[n][i].rgbtBlue = round(sumBlue / counter);

应该是这个,

image[n][i].rgbtRed = round(sumRed / counter);
image[n][i].rgbtGreen = round(sumGreen / counter);
image[n][i].rgbtBlue = round(sumBlue / counter);

并删除此内容,因为我们已经在计算后立即进行赋值了。

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