Search code examples
cfiltercs50grayscale

Need some initial direction with cs50 Filter Grayscale


I am trying to tackle the problem of the filter grayscale and I am struggling before I start.

For grayscale, the formula we have been given is to average the values of RGB and then use that value as the new RGB values for each pixel. How do I update the values in the pixels after I've averaged them?

I was thinking I could create a boolean of Replace and set it to false and then set it to true after it's replaced, but now I think I'm overlooking something much simpler.

And how do I treat the image as an array when I dont know how many rows there are other than 'height -1' rows.

The assignment video describes an example pixel format as:

image[2][3].rgtbBlue
image[2][3].rgbtGreen
image[2][3].rgbtRed

So does that mean that

((BYTE.rgbtBlue + BYTE.rgbtGreen + BYTE.rgbtRed) /3)

won't work to get the average values?

Would this work?

for (int i = 0; i < height -1; i ++)
{
   for (int j =0; j < height; j++)
    {
        image[i][j].rgbtBlue = round(((BYTE.rgbtBlue+ BYTE.rgbtGreen + BYTE.rgbtRed) /3));
        image[i][j].rgbtGreen = round(((BYTE.rgbtBlue+ BYTE.rgbtGreen + BYTE.rgbtRed) /3));
        image[i][j].rgbtRed = round(((BYTE.rgbtBlue+ BYTE.rgbtGreen + BYTE.rgbtRed) /3));
     }
}

Solution

  • void grayscale(int height, int width, RGBTRIPLE image[height][width])
    {
    // Locate the pixel
        for (int i = 0; i < width; i++)
        {
            for (int j = 0; j < height; j++)
            {
    // Find the average pixel color
                float avgpixel = round((image[j][i].rgbtBlue + image[j][i].rgbtGreen + image[j][i].rgbtRed) / 3.00);
    // Replace the grayscale pixel to all colors
                image[j][i].rgbtBlue = avgpixel;
                image[j][i].rgbtGreen = avgpixel;
                image[j][i].rgbtRed = avgpixel;
            }
        }
        return;
    }