Reputation: 3
I am working on the CS50 filter challenge and specifically the blur challenge.
It compiles nicely, but when I create the image the image is turned 90 degrees and at the bottom of the image is an image error.
Do you know what the problem is?
This is my code:
void blur(int height, int width, RGBTRIPLE image[height][width])
{
float sum_blue;
float sum_green;
float sum_red;
float counter;
RGBTRIPLE temp[height][width];
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
sum_blue = 0;
sum_green = 0;
sum_red = 0;
counter = 0;
for (int h= -1; h < 2; h++)
{
if (j + h < 0 || j + h > width - 1)
{
continue;
}
for (int v = -1; v < 2; v++)
{
if (i + v < 0 || i + v > height - 1)
{
continue;
}
sum_red += image[j + h][i + v].rgbtRed;
sum_blue += image[j + h][i + v].rgbtBlue;
sum_green += image[j + h][i + v].rgbtGreen;
counter++;
}
}
//summarize all values and save the pixels in a temporary image to transfer it later
temp[i][j].rgbtRed = round(sum_red / counter);
temp[i][j].rgbtBlue = round(sum_blue / counter);
temp[i][j].rgbtGreen = round(sum_green / counter);
}
}
// transfer temporary to real image
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
image[i][j].rgbtRed = temp[i][j].rgbtRed;
image[i][j].rgbtBlue = temp[i][j].rgbtBlue;
image[i][j].rgbtGreen = temp[i][j].rgbtGreen;
}
}
}
Upvotes: 0
Views: 145
Reputation: 93566
You appear to have swapped width and height here:
sum_red += image[j + h][i + v].rgbtRed;
sum_blue += image[j + h][i + v].rgbtBlue;
sum_green += image[j + h][i + v].rgbtGreen;
I would expect:
sum_red += image[i + v][j + h].rgbtRed;
sum_blue += image[i + v][j + h].rgbtBlue;
sum_green += image[i + v][j + h].rgbtGreen;
since the image array is [height][width]
and i
is the vertical iterator and j
the horizontal. Possibly only i
and j
are swapped, and i + h
and j + v
are intended.
Possibly the variables are swapped elsewhere in the algorithm. Better variable naming might help - so the names indicate what they represent. Even x
and y
would be clearer since that is a convention for cartesian coordinates - though a comment indicating top-left origin and y increasing down might be advisable.
By getting the indexes in the wrong order you have rotated and mirrored it and processed data from the wrong part of the image or not in the image at all.
Upvotes: 1