cs50 第 4 周滤镜不太舒服模糊功能不起作用

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

我已经将total_red、total_blue等设置为float,但我不知道为什么它仍然不适用于我的模糊功能。有人可以向我解释一下出了什么问题吗?

void blur(int height, int width, RGBTRIPLE image[height][width])
{
    // Create a copy of image
    RGBTRIPLE copy[height][width];
    float total_red = 0, total_blue = 0, total_green = 0, count = 0;

    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
        {
            for (int k = i - 1; k < i + 2; k++)
            {
                for (int z = j - 1; z < j + 2; z++)
                {
                    if (k >= 0 && z >= 0 && k < height && z < width)
                    {
                        total_red += image[k][z].rgbtRed;
                        total_blue += image[k][z].rgbtBlue;
                        total_green += image[k][z].rgbtGreen;
                        count++;
                    }
                }
            }
            copy[i][j].rgbtRed = round(total_red/count);
            copy[i][j].rgbtBlue = round(total_blue/count);
            copy[i][j].rgbtGreen = round(total_green/count);
        }
    }

    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
        {
            image[i][j] = copy[i][j];
        }
    }
}
c cs50
1个回答
0
投票

将用于计算平均颜色的变量移至循环中,这样您只需对当前像素周围的像素进行平均即可。您正在对自函数开始以来处理的所有像素进行平均。

void blur(int height, int width, RGBTRIPLE image[height][width])
{
    // Create a copy of image
    RGBTRIPLE copy[height][width];

    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
        {
            float total_red = 0, total_blue = 0, total_green = 0, count = 0;
            for (int k = i - 1; k < i + 2; k++)
            {
                for (int z = j - 1; z < j + 2; z++)
                {
                    if (k >= 0 && z >= 0 && k < height && z < width)
                    {
                        total_red += image[k][z].rgbtRed;
                        total_blue += image[k][z].rgbtBlue;
                        total_green += image[k][z].rgbtGreen;
                        count++;
                    }
                }
            }
            copy[i][j].rgbtRed = round(total_red/count);
            copy[i][j].rgbtBlue = round(total_blue/count);
            copy[i][j].rgbtGreen = round(total_green/count);
        }
    }

    memcpy(image, copy, sizeof copy);
}

您还可以使用

memcpy()
一次性复制整个数组,而不是使用另一组循环。

© www.soinside.com 2019 - 2024. All rights reserved.