【问题标题】:Grayscale filter for jpeg image not rounding values properly?jpeg图像的灰度过滤器没有正确舍入值?
【发布时间】:2020-03-02 09:15:43
【问题描述】:

我正在为作为结构传入的图像制作灰度过滤器,并且是图像[高度] [宽度]。所有值似乎都在工作,但由于某种原因,该函数无法正确舍入。例如,如果 RGB 值为 27 28 28,则 avg 应该是 28,但实际上是 27,所以它复制为 27 27 27。为什么?

// Convert image to grayscale
void grayscale(int height, int width, RGBTRIPLE image[height][width])
{

    for (int i = 0; i < height; i++)
    {
        for (int w = 0; w < width; w++)
        {

            float avg = ((image[i][w].rgbtRed + image[i][w].rgbtGreen + image[i][w].rgbtBlue) / 3);

            image[i][w].rgbtRed = round(avg);
            image[i][w].rgbtGreen = round(avg);
            image[i][w].rgbtBlue = round(avg);
        }
    }

    return;
}

【问题讨论】:

  • RGBTTRIPLE.rgbtRed等整数类型吗?如果是这样,您的avg 声明将采用整数除法的结果。将您的 3 更改为 3.0

标签: c++ c filter rounding


【解决方案1】:

假设您的图像是 int 或 char 类型:

float avg = ((image[i][w].rgbtRed + image[i][w].rgbtGreen + image[i][w].rgbtBlue) / 3);

上面的代码将被编译为

int temp = ((image[i][w].rgbtRed + image[i][w].rgbtGreen + image[i][w].rgbtBlue) / 3);
float avg = temp;

在 C/C++ 中,int 除法通常会“向零截断”,因此 temp 为 27。

您可以对除数使用类型转换。

float avg = ((float)(image[i][w].rgbtRed + image[i][w].rgbtGreen + image[i][w].rgbtBlue) / 3);

检查这个答案:

What is the behavior of integer division?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-20
    • 2013-04-30
    • 1970-01-01
    • 2016-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多