# PSET4 Filter: Blur help

While trying to create an algorithm to come up with the average of the color for all nine pixels (if using 9) I realized I would need a way to see how many surrounding pixels are used in the calculation instead of dividing everything by nine. I was thinking I should create and int variable that I could increment for every pixel used so I can just divide by the incremented variable but I am not sure how to go about doing that at the moment. Any good suggestions? Here is my code:

``````void blur(int height, int width, RGBTRIPLE image[height][width])
{
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
float red = image[i][j].rgbtRed;
float green = image[i][j].rgbtGreen;
float blue = image[i][j].rgbtBlue;
float blurRed = round((image[i - 1][j - 1].red) + (image[i - 1][j].red) + (image[i - 1][j + 1].red) + (image[i][j - 1].red) + (image[i][j].red) + (image[i][j + 1].red) + (image[i + 1][j - 1].red) + (image[i + 1][j].red) + (image[i + 1][j + 1].red) /
}
}
return;
}
``````

P.S. I know that my average algorithm can probably be done in a simpler way but this was the best I could think of to acheive the desired pixel location. Also, does your code have to compile before you can test out each filter or can you test out the filter as long as it is complete?

New Code:

``````// sums values of the pixel and 8 neighboring ones, skips iteration if it goes outside the pic
for (int k = -1; k < 2; k++)
{
if (j + k < 0 || j + k > height - 1)
{
continue;
}

for (int h = -1; h < 2; h++)
{
if (i + h < 0 || i + h > width - 1)
{
continue;
}

sumBlue += image[j + k][i + h].rgbtBlue;
sumGreen += image[j + k][i + h].rgbtGreen;
sumRed += image[j + k][i + h].rgbtRed;
counter++;
}
}
``````

First you have to think that when taking the values from the surroundings pixels, some of them will be already changed so the result will be diferent than with the original ones. Think in how you could solve that. On the other hand, when going around each pixel you have to check for each single one that you're not reaching out of limits of the arrays i.e. `image[i - 1][j - 1]`. If it's in fact inside the limits you could then add the value for the average. To keep track of how many elements you added you could use a simple 'int' variable that you would reset every iteration of your 'i j' loops once you'd use to do your math. To go through the pixels around if you don´t feel comfortable using more loops you could simply add 9 lines, one for every pixel, checking if they are out of limits and using them (or not) to average them. If you want to give it a try I suggest a couple of 'for' loops with 3 runs each. One for the horizontal pixels and one for the vertical ones.