Loading
Loading

Reputation: 19

Filter program in C does not work on more complex images

I need to write a program which makes a grayscale filter. It works only partially and I am having the following error messages:

:) grayscale correctly filters single pixel with whole number average
:( grayscale correctly filters single pixel without whole number average
    expected "28 28 28\n", not "27 27 27\n"
:) grayscale leaves alone pixels that are already gray
:) grayscale correctly filters simple 3x3 image
:( grayscale correctly filters more complex 3x3 image
    expected "20 20 20\n50 5...", not "20 20 20\n50 5..."
:( grayscale correctly filters 4x4 image
    expected "20 20 20\n50 5...", not "20 20 20\n50 5..."

The code is below:

void grayscale(int height, int width, RGBTRIPLE image[height][width])
{
    for(int i = 0; i < height; i++) //Loop thought each row of 2D array
    {
        for(int j = 0; j < width; j++)//Loop through each pixel of each row
        {

            int red = image[i][j].rgbtRed;
            int blue = image[i][j].rgbtBlue;
            int green = image[i][j].rgbtGreen;
            int avr = round((red + blue + green) / 3);
            image[i][j].rgbtBlue = image[i][j].rgbtGreen = image[i][j].rgbtRed = avr;

        }
    }
    return;
}

Upvotes: 1

Views: 128

Answers (1)

chux
chux

Reputation: 154228

round() ineffective as the quotient of two ints is as int. Rounding that int has no effect.

//                 ........int........  / int
// int avr = round((red + blue + green) / 3);

// Divide by a `double`
int avr = round((red + blue + green) / 3.0);
// or
int avr = lround((red + blue + green) / 3.0);

// or even better, round with integer math.
int avr = ((red + blue + green)*2 + 3)/6;

Other problems may exist, but this explains "expected "28 28 28\n", not "27 27 27\n".

Upvotes: 1

Related Questions