gpt4 book ai didi

algorithm - 如何在二值图像中找到连通分量?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:39:20 25 4
gpt4 key购买 nike

我正在寻找一种算法来找到我的二进制图像中的所有连通分量。

如果我们把图像想象成一个矩阵,它看起来像:

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

我想找到所有接触的(对角线也是)。在此示例中,只有一个组件 - 但图像中可能有数百个独特的组件。

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

我看过 two pass labelling维基百科上的算法,但我不相信它会返回实际组件 - 它只是标记不同的组件。 (或者这是同一个?)

如果可能,这应该能够针对视频流实时运行。

最佳答案

下面是一个简单的代码(C++),使用简单的dfs来标记不同的组件,你可以试试看。

例如,如果您的标准输入是

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

那么输出应该是

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

相同的数字表示该单元格属于同一组件。

我假设所有 8 个方向都属于同一个组件,如果您只想要 4 个方向,改变 dx[] 和 dy[]

此外,我假设输入最多为 200*200,并且我做了一些事情来避免处理那些烦人的数组出站问题,您可以检查一下:)

#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;
}

关于algorithm - 如何在二值图像中找到连通分量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22051069/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com