我想在python中从图像(大量顶点...大约> 10 ^ 5个顶点)创建一个大的加权邻接矩阵。相邻像素之间的权重是颜色梯度(我会照顾这个)。通过迭代像素来做这件事非常慢......需要4分钟。 :-(是否有任何库可以在合理的时间内很好地完成这项工作?
以下是我的代码运行速度非常慢:
def indToCoord(ind, w, h):
x = ind % w
y = (ind - x)/h
return (x,y)
def isAdj(p1, p2, im):
adj = []
w, h = im.size
x1, y1 = p1
x2, y2 = p2
if (x1, y1) == (x2, y2):
return 0
elif abs(x1 - x2) > 1:
return 0
elif abs(y1 - y2) > 1:
return 0
elif abs(x1 - x2) + abs(y1 - y2) >= 2:
return 0
return util.colorGradient(im, p1, p2)
def adjForPixel(pixels, p1, im):
return [isAdj(p1,p2,im) for p2 in pixels]
# The following is the function I use to create an Adjacency Matrix from an image
def getAdjMatrix(im):
width, height = im.size
pixels = [(x,y) for x in xrange(width) for y in xrange(height)]
pixelAdjMatr = [adjForPixel(pixels, p, im) for p in pixels]
return pixelAdjMatr
adj_matrix = getAdjMatrix(im)
谢谢!
答案 0 :(得分:1)
Python模块/库NetworkX具有邻接矩阵实现。它返回一个scipy矩阵
import networkx as nx
import scipy as sp
g = nx.Graph([(1,1)])
a = nx.adjacency_matrix(g)
print a, type(a)
返回
(0, 0) 1 <class 'scipy.sparse.csr.csr_matrix'>