Matlab图像处理-连通域分析

连通域分析(connected component analysis)的目的是在二值图像中,利用像素之间的连接关系,获得分割不同的区域。

详细解释,参见wiki

下面是two-pass方法的Matlab实现,这里采用的是4邻域:

image = [0,0,1,0,0,1,0;
         1,1,1,0,1,1,1;
         0,0,1,0,0,1,0;
         0,1,1,0,1,1,0];
         
[row, col] = size(image);

map_label_first = zeros(size(image)); % first pass
map_label_second = zeros(size(image)); % second pass

label_ID = 1;
label_set = [];

%% First pass for temporary labels.
for i = 1:1:row
    for j = 1:1:col
        tmp_neighbors = [];
        if(1==image(i,j)) % foreground
            if(i-1>0 && 1==image(i-1,j) && map_label_first(i-1,j)~=0) % up
                tmp_neighbors(1, length(tmp_neighbors)+1) = map_label_first(i-1,j);
            end
            
            if(j-1>0 && 1==image(i,j-1) && map_label_first(i,j-1)~=0) % left
                tmp_neighbors(1, length(tmp_neighbors)+1) = map_label_first(i,j-1);
            end
            
            label_neighbors = unique(tmp_neighbors);
            
            if(true == isempty(label_neighbors)) % Assign a new label_ID
                map_label_first(i,j) = label_ID;
                
                label_set(1, label_ID) = label_ID;
                label_ID = label_ID + 1;
                
            else % Update label_set
                map_label_first(i,j) = min(label_neighbors);
                
                label_set(1, max(label_neighbors)) = min(label_neighbors);               
            end
        end
    end
end

%% Second pass for merging labels.
for i = 1:1:row
    for j = 1:1:col
        if(map_label_first(i,j)~=0)
            map_label_second(i,j) = label_set(1, map_label_first(i,j));
        end
    end
end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值