what is executed first in c?

Viewed 41

I am trying to write a function that applies a sepia filter to the images,

    void sepia(int height, int width, RGBTRIPLE image[height][width])
    {
         for(int i=0; i<height; i++)
         {
            for(int j=0; j<width; j++)
            {
                int r = image[i][j].rgbtRed;
                int g = image[i][j].rgbtGreen;
                int b = image[i][j].rgbtBlue;

                image[i][j].rgbtRed =  round((0.393 * r) + (0.769 * g) + (0.189 * b));
                image[i][j].rgbtGreen =  round((0.349 * r) + (0.686 * g) + (0.168 * b));
                image[i][j].rgbtBlue = round((0.272 * r) + (0.534 * g) + (0.131 * b));


                if(image[i][j].rgbtRed > 255)
                {
                    image[i][j].rgbtRed = 255;
                }

                if(image[i][j].rgbtGreen > 255)
                {
                    image[i][j].rgbtGreen = 255;
                }

                if(image[i][j].rgbtBlue > 255)
                {
                    image[i][j].rgbtBlue = 255;
                }
            }
        }
    }

when I used this code, it does not raise any error, but the if conditions do not work at all, and the resulting image has many creepy pixels.

but when I used intermediate variables like this code below:

    void sepia(int height, int width, RGBTRIPLE image[height][width])
    {
        for(int i=0; i<height; i++)
        {
            for(int j=0; j<width; j++)
            {
                int r = image[i][j].rgbtRed;
                int g = image[i][j].rgbtGreen;
                int b = image[i][j].rgbtBlue;

                int sr =  round((0.393 * r) + (0.769 * g) + (0.189 * b));
                int sg =  round((0.349 * r) + (0.686 * g) + (0.168 * b));
                int sb = round((0.272 * r) + (0.534 * g) + (0.131 * b));


                if(sr > 255)
                {
                    sr = 255;
                }

                if(sg > 255)
                {
                    sg = 255;
                }

                if(sb > 255)
                {
                   sb = 255;
                }

                image[i][j].rgbtRed = sr;
                image[i][j].rgbtGreen = sg;
                image[i][j].rgbtBlue = sb;
            }
         }
     }

the if statements worked perfectly.

my question is what is wrong in the first code that makes the if statements don't work?

2 Answers

The structure members are eight-bit unsigned integers. When you assign to them, values over 255 are lost. (They are wrapped modulo 256.)

When you assign to the intermediate int variables, they retain the full values.

image[i][j].rgbtRed > 255 is never true as .rgbtRed is 8-bit. Use an int to save the sum.

Related