0

I was making a grayscale filter for an image that is passed in as a struct and is image[height][width]. All the values seem to be working but for some reason, the function doesn't round properly. For example if the RGB values are 27 28 28, the avg should be 28 but instead, it is 27 so it copies as 27 27 27. Why?

// 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;
}
  • 4
    Are `RGBTTRIPLE.rgbtRed`, etc. integer types? If so, your declaration of `avg` will take the result of integer division. Change your `3` to `3.0`. – JohnFilleau Mar 02 '20 at 01:07

1 Answers1

2

assume your image is int or char type:

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

above code will be compiled as

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

and in C/C++ the int divide will often 'truncation toward zero', so the temp will be 27.

you can use typecasting for the divided number.

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

check this answer:

What is the behavior of integer division?

Pino Huang
  • 21
  • 2