Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find the connected components in a binary image?

I am looking for an algorithm to find all connected components in my binary image.

If we think of the image like a matrix, it looks like:

[ 0 0 0 0 ...
  0 0 0 0 ...
  0 1 1 1 ...
  0 1 0 1 ...
  0 1 0 0 ...
  ...
]

I would like to find the all the ones that are touching (diagonally, as well). In this example, there is only one component - but there may be hundreds of unique components in an image.

Image => ALGORITHM => [ [(x,y)], ... ] 
                      # list of lists of coordinates (each shape is a list)

I have looked at the two pass labelling algorithm on Wikipedia, but I don't believe it returns me the actual components - it just labels the distinct components. (Or is this one and the same?)

If possible, this should be able to run in real-time against a video stream.

like image 466
sdasdadas Avatar asked Feb 26 '14 19:02

sdasdadas


1 Answers

Below are a simple code (C++) using simple dfs to mark different component, you may try it out.

For example, if your stdin input is

4 5
0 0 0 0 1
0 1 1 0 1
0 0 1 0 0
1 0 0 0 1

Then the output should be

Graph:
0 0 0 0 1 
0 1 1 0 1 
0 0 1 0 0 
1 0 0 0 1 

Output:
0 0 0 0 1 
0 2 2 0 1 
0 0 2 0 0 
3 0 0 0 4

The same number represent that cell belongs to the same component.

I am assuming all 8-directions belongs to the same component, if you only want 4-directions, change dx[] and dy[]

Also I am assuming the input is at most 200*200, and I did something to avoid handling those annoying array outbound issues, you may check it out :)

#include<cstdio>
#include<cstdlib>
#include<cstring>

int g[202][202] = {0};
int w[202][202] = {0};

int dx[8] = {-1,0,1,1,1,0,-1,-1};
int dy[8] = {1,1,1,0,-1,-1,-1,0};

void dfs(int x,int y,int c){
    w[x][y] = c;
    for(int i=0; i<8;i++){
        int nx = x+dx[i], ny = y+dy[i];
        if(g[nx][ny] && !w[nx][ny]) dfs(nx,ny,c);
    }
}

int main(){
    int row, col, set = 1;
    scanf("%d%d", &row, &col);

    for(int i=1; i<=row; i++) for(int j=1; j<=col; j++) scanf("%d", &g[i][j]);

    for(int i=1; i<=row;i++)
        for(int j=1; j<=col; j++)
            if(g[i][j] && !w[i][j])
                dfs(i,j,set++);

    printf("Graph:\n");
    for(int i=1; i<=row;i++){
        for(int j=1; j<=col;j++)
            printf("%d ", g[i][j]);
        puts("");
    }
    puts("");
    printf("Output:\n");
    for(int i=1; i<=row;i++){
        for(int j=1; j<=col;j++)
            printf("%d ", w[i][j]);
        puts("");
    }

    return 0;
}
like image 119
shole Avatar answered Nov 19 '22 00:11

shole