I've been doing the "filter-less" problem for CS50 and noticed that, this code:
void grayscale(int height, int width, RGBTRIPLE image[height][width])
{
for (int i = 0; i < height; i )
{
for (int j = 0; j < width; j )
{
image[i][j].rgbtBlue = (image[i][j].rgbtBlue image[i][j].rgbtRed image[i][j].rgbtGreen) / 3;
image[i][j].rgbtRed = image[i][j].rgbtBlue;
image[i][j].rgbtGreen = image[i][j].rgbtBlue;
}
}
return;
}
and this one,
// Convert image to grayscale
void grayscale(int height, int width, RGBTRIPLE image[height][width])
{
for (int i = 0; i < height; i )
{
for (int j = 0; j < width; j )
{
image[i][j].rgbtBlue = (image[i][j].rgbtBlue image[i][j].rgbtRed image[i][j].rgbtGreen);
// Notice this line
image[i][j].rgbtBlue /= 3;
image[i][j].rgbtRed = image[i][j].rgbtBlue;
image[i][j].rgbtGreen = image[i][j].rgbtBlue;
}
}
return;
}
Have entirely different outputs, and the former gives better results. Can someone explain the reason behind that? Why is the difference when the arithmetic operation is done in separate lines? Do correct me if I am doing something wrong here.
The program is supposed to take an input image in BMP format, apply filters (In this case Greyscale) and create an output, the function takes the image's height height
and width width
and the RGB values of the said image in the array image
.
This is from CS50's Introduction to computer science course Week 4 by the way.
[EDIT]
typedef uint8_t BYTE;
typedef struct
{
BYTE rgbtBlue;
BYTE rgbtGreen;
BYTE rgbtRed;
} __attribute__((__packed__))
RGBTRIPLE;
More information regarding the question is here:
https://cs50.harvard.edu/x/2022/psets/4/filter/less/
CodePudding user response:
image[i][j].rgbtBlue image[i][j].rgbtRed image[i][j].rgbtGreen
is larger than uint8_t
can cope with. And
image[i][j].rgbtBlue = (image[i][j].rgbtBlue image[i][j].rgbtRed image[i][j].rgbtGreen) / 3;
assigns, for example, 417/3
(or 139
, operations here are done with int
) to the member
image[i][j].rgbtBlue = (image[i][j].rgbtBlue image[i][j].rgbtRed image[i][j].rgbtGreen); image[i][j].rgbtBlue /= 3;
first assigns 417 % 256
(or 161
) to the member, then divides that by 3