# Thread: Counting Pixels In A Blob

1. ## Counting Pixels In A Blob

The purpose of the program is to take a position and count how many "pixels" are in the "blob". If there is no "pixel" aka the value is 0, the blob number is 0. If there is a pixel, the blob_check function recursively checks the surrounding cells for "pixels" aka values of 1. My program compiles but doesn't accurately count the number of pixels in the blob. If I ask it to count the number of pixels in the blob for (0,0) it gives a 4 instead of a 5. Please help!

Code:
```#include <stdlib.h>
#include <stdio.h>

#define N 5

int blob_check(int pic[N][N], int x, int y)
{
if (pic[x][y] == 0)
return 0;
else
{
pic[x][y] = 0;

int sum = 1;

//check
if (x>0)
{
sum += blob_check(pic, x-1, y);
if (y<N-1)
sum += blob_check(pic, x-1, y+1);
}
else if (y<N-1)
{
sum += blob_check(pic, x, y+1);
if (x<N-1)
sum += blob_check(pic, x+1, y+1);
}
else if (x<N-1)
{
sum += blob_check(pic, x+1, y);
if (y>0)
sum += blob_check(pic, x+1, y-1);
}
else if (y>0)
{
sum += blob_check(pic, x, y-1);
if (x>0)
sum += blob_check(pic, x-1, y-1);
}

return sum;
}
}

int main()
{
int x,y,i,j;
int row=0;
char line[80];
int table[N][N] = { {1,1,0,0,0},
{0,1,1,0,0},
{0,0,1,0,1},
{1,0,0,0,1},
{0,1,0,1,1}};

printf("\t0\t1\t2\t3\t4\t");
printf("\n   -----------------------------------------");
for(i=0;i<5;i++)
{
printf("\n   |\n%d  |\t", i);
for(j=0;j<5;j++)
{
printf("%d\t", table[i][j]);
}
}

printf("\n\nEnter x-y coordinates of cell  => ");
scanf("%d %d", &y, &x);

printf("Pixel quantity in blob: %i\n", blob_check(table, x, y));

system("pause");
return 0;
}```

2. A simple printf on entry to blob_check would tell you the order or elements being checked. Are you only supposed to be checking adjacent cells?

3. We have to check the 8 cells surrounding the given one, vertically, horizontally and diagonally.

4. Then you are checking too many.

5. what do you mean?

6. Add a printf statement to your blob_check function, printing out the coordinates being checked, and you'll see what I mean.

7. ahhh i see... but why would it be checking those? if it returns a 0, shouldn't it end the recursion?

8. It's doing exactly what you coded it to do. Check your logic - work it out on paper with the output of your printf and see why. Then, fix it once you understand what is happening.

9. This is essentially a variant on the flood fill algorithm.

Popular pages Recent additions