天天看點

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