0

I've managed to make Filter Grayscale work. It wasn't too complicated, I was just missing to cast each color to float as such;

 void grayscale(int height, int width, RGBTRIPLE image[height][width])
{
    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
        {
            int averageRGB = round((float) image[i][j].rgbtRed + (float) image[i][j].rgbtGreen + (float) image[i][j].rgbtBlue)/3;
            image[i][j].rgbtRed = averageRGB;
            image[i][j].rgbtGreen = averageRGB;
            image[i][j].rgbtBlue = averageRGB;
        }
    }
    return;
}

My question is, why do we need to cast it to float and as an int it doesn't work? Well, it does work but some colors are off (not grayscale).

My understanding is that float is used for precision, but I can't wrap my mind around it and I would like to understand it properly.

Thanks in advance

1

The reason is that if the code is doing division with all integers, it will do integer division, not normal division.

Integer division will truncate the fractional part of the division. So, if the result were something like 3.8, the result would be truncated to 3. This would lead to a lot of errors in an entire image.

Now, you can reduce the extent of casting needed. Since the code is adding 3 integers together before doing the division, they can be directly added. The result will actually be more accurate (because no storage errors related to floats yet.)

Next, if you divide by a number WITH A DECIMAL POINT rather than an integer, it will force casting to floats in the result.

Put all this together and you can do this:

int a = 30, b = 30 c = 29;
int avg = (int) round( (a + b + c) / 3.0 );
2
  • Thanks for your reply Cliff! I do really appreciate you taking the time. – highpointer Feb 6 at 10:55
  • Yo man can you explain it again with examples please !! That solved my problem but i am not surely understand. – LesBenjamim Feb 17 at 11:53

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .