mardi 27 octobre 2020

Why do my conditions (IF statements) return false?

I'm trying to solve the blur function in PSET4 filter(less) in the CS50x course. This is the problem:


Blur

There are a number of ways to create the effect of blurring or softening an image. For this problem, we’ll use the “box blur,” which works by taking each pixel and, for each color value, giving it a new value by averaging the color values of neighboring pixels.

Consider the following grid of pixels, where we’ve numbered each pixel.

a grid of pixels (here is an image of a 4x4 grid)

The new value of each pixel would be the average of the values of all of the pixels that are within 1 row and column of the original pixel (forming a 3x3 box). For example, each of the color values for pixel 6 would be obtained by averaging the original color values of pixels 1, 2, 3, 5, 6, 7, 9, 10, and 11 (note that pixel 6 itself is included in the average). Likewise, the color values for pixel 11 would be be obtained by averaging the color values of pixels 6, 7, 8, 10, 11, 12, 14, 15 and 16.

For a pixel along the edge or corner, like pixel 15, we would still look for all pixels within 1 row and column: in this case, pixels 10, 11, 12, 14, 15, and 16.


This is the code I've written so far:

// Blur image
void blur(int height, int width, RGBTRIPLE image[height][width])
{
    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
        {
            int red = image[i][j].rgbtRed;
            float count = 0.0;
            int blurRed = 0;

            for (int k = 0; (k <= i + 1) && (k < height); k++)
            {
                for (int l = 0; (l <= j + 1) && (l < width); l++)
                {
                    int sumRed = image[k][l].rgbtRed;

                    if ((k - 1 >= 0) && (k + 1 < height))
                    //these if statements should ensure that the following action is only carried out IF the k/l indices do not exceed height and width
                    {
                        sumRed += image[k - 1][l].rgbtRed;
                        count++;
                    }

                    if ((l - 1 >= 0) && (l + 1 < width))
                    {
                        sumRed += image[k][l - 1].rgbtRed;
                        count++;
                    }
                    blurRed = roundf(sumRed / count);
                }
            }          
            red = blurRed;
        }
    }
}

Although I'm not all sure that I'm on the right track here with my solution. When I run the code, I get this error message:

helpers.c:139:45: runtime error: division by zero helpers.c:139:32: runtime error: inf is outside the range of representable values of type 'int'

So I'm wondering why my counter always remains at 0.

Looking forward to some help and answers!

Aucun commentaire:

Enregistrer un commentaire