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

好久不见. 提交于 2019-12-04 05:41:01

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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!