在 MATLAB 中以某种方式对数字进行分组

Group numbers in a certain way in MATLAB

我在没有使用 Matlab 中的计算机视觉工具箱的情况下找到图像中的连通分量。

在给定图像的第一次扫描中,我给每个像素都贴上了标签。我还创建了一个 table,它为我提供了相互连接的组件列表。 table 看起来像这样:

1   5
1   5
2   4
3   5
8   5
2   6

这table意味着所有标签为1和5的像素是相连的,2和4是相连的,3和5是相连的等等。另外,由于1和5相连,3和5也相连,这意味着1和3也相连。

我想找到一种方法将所有这些组件组合在一起。有什么办法吗?? 或者以某种方式使每个连接的像素都获得一个与具有最小值的标签等效的标签,即如果连接了 4、7 和 12 个像素,则所有具有标签 4、7 和 12 的像素都应获得值为 4.[=11 的标签=]

您似乎想要计算图形的连通分量。这可以在 MATLAB 中相当容易地完成,无需任何额外的工具箱。

e = [1   5; ...
     1   5; ...
     2   4; ...
     3   5; ...
     8   5; ...
     2   6];
% MATLAB doesn't support repeated edges so remove them
e = unique(sort(e,2),'rows');
% create a graph
G = graph(e(:,1),e(:,2));
% plot the graph (optional)
plot(G);
% find connected components
bins = conncomp(G);
% get the indicies of nodes in each cluster
cluster = arrayfun(@(v)find(bins==v),1:max(bins),'UniformOutput',false);

结果

>> cluster{1}
ans = 1     3     5     8
>> cluster{2}
ans = 2     4     6
>> cluster{3}
ans = 7