Code of the week

Connected-component labeling (alternatively connected-componentanalysis, blob extraction, region labeling, blob discovery, or region extraction) is an algorithmic application of graph theory, where subsets of connected components are uniquely labeled based on a given heuristic.

Matlab Code for Component Labeling without using inbuilt function

Source code:

clear;clc;clear all;

img = imread('img.png');
bwimage = im2bw(img,0.74);
img8 = uint8(bwimage) ;

[ypixelxpixel ] = size(bwimage);

c = 3;

color_mat= zeros(20,2);
k=0;

for j=2:ypixel
      fori=2:xpixel
            if(bwimage(j,i)==0)
                  if(bwimage(j,i-1)~=0 &&bwimage(j-1,i)~=0)
                              c = c + 1;
                              img8(j,i)=c;

                  elseif(bwimage(j,i-1)~=0 &&bwimage(j-1,i)==0)
                              img8(j,i)=img8(j-1,i);

                  elseif(bwimage(j,i-1)==0 &&bwimage(j-1,i)~=0)
                              img8(j,i) = img8(j,i-1);

                  else
                        img8(j,i) = img8(j-1,i);
                        f = img8(j,i-1);
                        g = img8(j-1,i);
                        if (img8(j,i-1)~=img8(j-1,i))
                              flag =0;
                              for l=1:k
                                    if(color_mat(l,1)==f &&color_mat(l,2) ==g)||(color_mat(l,1)==g &&color_mat(l,2)==f)
                                          flag = 1;
                                          break;
                                    end
                              end
                              if(flag==0)
                                    k=k+1;
                                    color_mat(k,1)=f;
                                    color_mat(k,2)=g;
                              end
                        end
                  end
            end
      end
end

colorans = zeros(c-3,2);
fori=4:c
      b =0;
      prev = 0;
      curr = i;
      while(prev ~= curr)
            prev = curr;
            for j=1:k
                  if(color_mat(j,1)==curr&&curr>color_mat(j,2))
                        curr =  color_mat(j,2);
                  elseif(color_mat(j,2)==curr&&curr>color_mat(j,1))
                        curr =  color_mat(j,1);
                  end
            end
      end
      colorans(i-3,1)=i;
      colorans(i-3,2)=curr;
end
     
for j=1:ypixel
      fori=1:xpixel
           
            if(bwimage(j,i)==0)
                  img8(j,i) = colorans((img8(j,i)-3),2)*30;
            else
                  img8(j,i)= 255;
            end
      end
end


imshow(img8);


INPUT: 



OUTPUT


No comments:

Post a Comment