sda*_*das 6 language-agnostic algorithm image-recognition computer-vision
我正在寻找一种算法来查找二进制图像中的所有连接组件.
如果我们将图像看作矩阵,它看起来像:
[ 0 0 0 0 ...
0 0 0 0 ...
0 1 1 1 ...
0 1 0 1 ...
0 1 0 0 ...
...
]
Run Code Online (Sandbox Code Playgroud)
我想找到所有触摸的对角线(对角线).在此示例中,只有一个组件 - 但图像中可能有数百个独特组件.
Image => ALGORITHM => [ [(x,y)], ... ]
# list of lists of coordinates (each shape is a list)
Run Code Online (Sandbox Code Playgroud)
我已经看过维基百科上的两个通过标记算法,但我不相信它会给我带来实际的组件 - 它只是标记了不同的组件.(或者这个和那个一样吗?)
如果可能,这应该能够针对视频流实时运行.
sho*_*ole 11
下面是一个简单的代码(C++),使用简单的dfs来标记不同的组件,你可以尝试一下.
例如,如果您的stdin输入是
4 5
0 0 0 0 1
0 1 1 0 1
0 0 1 0 0
1 0 0 0 1
Run Code Online (Sandbox Code Playgroud)
那么输出应该是
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
Run Code Online (Sandbox Code Playgroud)
相同的数字表示该单元属于同一组件.
我假设所有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;
}
Run Code Online (Sandbox Code Playgroud)