2014-12-21 51 views
0

我想將圖論方法應用於圖像處理問題。我想從包含我想要繪製的點的數組中生成一個鄰接矩陣。我想要生成數組中點的完整圖。如果我需要繪製數組中的N個點,則需要一個NxN矩陣。權重應該是點之間的距離,所以這是我的代碼:從Python中的數組中向量化壓縮的稀疏矩陣

''' vertexarray is an array where the points that are to be 
    included in the complete graph are True and all others False.''' 

import numpy as np 
def array_to_complete_graph(vertexarray): 

    vertcoords = np.transpose(np.where(vertexarray == True)) 

    cg_array = np.eye(len(vertcoords)) 

    for idx, vals in enumerate(vertcoords): 
     x_val_1, y_val_1 = vals 
     for jdx, wals in enumerate(vertcoords): 
      x_diff = wals[0] - vals[0] 
      y_diff = wals[1] - vals[1] 
      cg_array[idx,jdx] = np.sqrt(x_diff**2 + y_diff**2) 
    return cg_array 

這個工作,當然,但我的問題是:可以在此同一陣列可以不嵌套的for循環產生的?

回答

0

使用功能scipy.spatial.distance.cdist()

import numpy as np 

def array_to_complete_graph(vertexarray): 

    vertcoords = np.transpose(np.where(vertexarray == True)) 

    cg_array = np.eye(len(vertcoords)) 

    for idx, vals in enumerate(vertcoords): 
     x_val_1, y_val_1 = vals 
     for jdx, wals in enumerate(vertcoords): 
      x_diff = wals[0] - vals[0] 
      y_diff = wals[1] - vals[1] 
      cg_array[idx,jdx] = np.sqrt(x_diff**2 + y_diff**2) 
    return cg_array 

arr = np.random.rand(10, 20) > 0.75 

from scipy.spatial.distance import cdist 
y, x = np.where(arr) 
p = np.c_[x, y] 
dist = cdist(p, p) 
np.allclose(array_to_complete_graph(arr), dist) 
+0

這是令人難以置信的快速。非常感謝。我只感到遺憾,我沒有足夠的聲望投票。再次感謝你。 – carsonc