2014-04-03 43 views

回答

1

这里是代码

def connected_components(self,SWTImage): 
    width=SWTImage.shape[1] 
    heigth=SWTImage.shape[0] 
    G=nx.Graph() 
    row_loc=np.zeros(SWTImage.shape[0]*SWTImage.shape[1]) 

    for y in xrange(1,heigth): 
     for x in xrange(1,width): 
      currentPix=SWTImage.item(y,x) 
      if currentPix>0: 
       left=x-1 
       up=y-1 
       rigth=x+1 

       leftPix=SWTImage.item(y,left) 
       if(leftPix>0 and (leftPix/currentPix<=3.0 or currentPix/leftPix<=3.0)): 
        G.add_edge(y*width+x,y*width+left) 
        row_loc.itemset((y*width+left),y) 

       leftUpPix=SWTImage.item(up,left) 
       if(leftUpPix>0 and (leftUpPix/currentPix<=3.0 or currentPix/leftUpPix<=3.0)): 
        G.add_edge(y*width+x,up*width+left) 
        row_loc.itemset((up*width+left),up) 

       upPix=SWTImage.item(up,x) 
       if(upPix>0 and (upPix/currentPix<=3.0 or currentPix/upPix<=3.0)): 
        G.add_edge(y*width+x,up*width+x) 
        row_loc.itemset((up*width+x),up) 

       if(rigth<width): 
        rightUpPix=SWTImage.item(up,rigth) 
        if (rightUpPix>0 and (rightUpPix/currentPix<=3.0 or currentPix/rightUpPix<=3.0)): 
         G.add_edge(y*width+x,up*width+rigth) 
         row_loc.itemset(up*width+rigth,up) 

       row_loc.itemset((y*width+x),y) 

    components=nx.algorithms.components.connected_components(G) 
    return components,row_loc 

我已经使用DFS寻找连接的组件的列表。

0

执行此操作的经典方法是使用disjoint set数据结构描述的两遍算法here。它可以很容易地修改以适应任意条件。