How can I cluster data points according to their adjacency in a matrix?

6 ビュー (過去 30 日間)
Joe Lau
Joe Lau 2019 年 11 月 7 日
編集済み: Image Analyst 2019 年 11 月 8 日
Hi guys, is there a way which I could separate out the different clusters of 1 (based on adjacency) in a 2D matrix into separate matrices? The input and desired output are as below. Thank you!
input = [0 0 0 0 0 0 0 0;
0 0 0 0 1 1 1 0;
0 0 0 0 1 1 0 0;
0 0 0 0 0 1 0 0;
0 0 1 1 0 0 0 0;
0 1 1 1 1 0 0 0;
0 0 0 0 0 1 0 0] ;
output(:, : , 1) = [0 0 0 0 0 0 0 0;
0 0 0 0 1 1 1 0;
0 0 0 0 1 1 0 0;
0 0 0 0 0 1 0 0;
0 0 0 0 0 0 0 0;
0 0 0 0 0 0 0 0;
0 0 0 0 0 0 0 0] ;
output(:, : , 2) = [0 0 0 0 0 0 0 0;
0 0 0 0 0 0 0 0;
0 0 0 0 0 0 0 0;
0 0 0 0 0 0 0 0;
0 0 1 1 0 0 0 0;
0 1 1 1 1 0 0 0;
0 0 0 0 0 1 0 0] ;

回答 (1 件)

Image Analyst
Image Analyst 2019 年 11 月 7 日
編集済み: Image Analyst 2019 年 11 月 8 日
Don't use "input" as the name of your variable - it's the name of a built-in function.
To answer your question, use bwlabel() if you have the Image Processing Toolbox:
>> yourMatrix = [0 0 0 0 0 0 0 0;
0 0 0 0 1 1 1 0;
0 0 0 0 1 1 0 0;
0 0 0 0 0 1 0 0;
0 0 1 1 0 0 0 0;
0 1 1 1 1 0 0 0;
0 0 0 0 0 1 0 0] ;
>> labeledMatrix = bwlabel(yourMatrix)
labeledMatrix =
0 0 0 0 0 0 0 0
0 0 0 0 2 2 2 0
0 0 0 0 2 2 0 0
0 0 0 0 0 2 0 0
0 0 1 1 0 0 0 0
0 1 1 1 1 0 0 0
0 0 0 0 0 1 0 0
Now pick out region 2, if that's what you want, using ismember().
>> region2 = ismember(labeledMatrix, 2)
region2 =
7×8 logical array
0 0 0 0 0 0 0 0
0 0 0 0 1 1 1 0
0 0 0 0 1 1 0 0
0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
If you want them in your 3-D output array, you could do this (untested):
[labeledMatrix, numRegions] = bwlabel(yourMatrix);
[rows, columns] = size(yourMatrix);
output = zeros(rows, columns, numRegions)
for k = 1 : numregions
output(:, :, k) = ismember(labeledMatrix, k)
end

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by