Matlab点云欧式距离聚类-2021-12-06

最近博主根据matlab2019b的函数,仿写了欧氏距离聚类,其代码如下:

其实代码就是一模一样的,哈哈哈哈,博主偷了点懒。

clear
clc
%% 模拟数据
[X,Y,Z] = sphere(100);
loc1 = [X(:),Y(:),Z(:)];
loc2 = 2*loc1;
ptCloud = pointCloud([loc1;loc2]);
pcshow(ptCloud)
title('Point Cloud')
a = ptCloud.Location;

%% 欧式距离聚类
% 设置参数r
r = 0.5;
% 半径搜索
ind = rangesearch(a,a,r,'Distance','euclidean','NSMethod','kdtree'); 
% 设置索引列
num = numel(a(:,1));
idx = zeros(num,1);
% 设置指针
newlable = 0;
for i = 1:num
    if idx(i)~=0
        continue
    end
    
    % 选取第i个点的索引
    curp = ind(i,:);
    % cell转换为数组mat
    curp = cell2mat(curp);
    % 第一个索引是自己,所以去除
    curp = curp(:,2:end);
    
    for j = 1:length(curp)
        temp = curp(j);
        if idx(i)>0 && idx(temp)>0
            if idx(i) > idx(temp)
                idx(idx==idx(i)) = idx(temp);
            elseif idx(temp) > idx(i)
                idx(idx==idx(temp)) = idx(i);
            end
        else
            if idx(i)>0
                idx(temp) = idx(i);
            elseif idx(temp)>0
                idx(i) = idx(temp);
            end
        end
    end
    
    if idx(i) == 0
        newlable = newlable+1;
        idx(i) = newlable;
        idx(curp) = newlable;
    end
end

pcshow(a,idx)

模拟的数据:

Matlab点云欧式距离聚类-2021-12-06_第1张图片

Matlab点云欧式距离聚类-2021-12-06_第2张图片

你可能感兴趣的:(#,点云处理-matlab,聚类,matlab,算法)