在python中从图像创建大的邻接矩阵 [英] Creating large adjacency matrix from image in python

查看:1514
本文介绍了在python中从图像创建大的邻接矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在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:
返回0
elif abs(y1 - y2)> 1:
return 0
elif abs(x1 - x2)+ abs(y1 - y2)> = 2:
返回0

返回util.colorGradient(im,p1,p2)

def adjForPixel(pixels,p1,im):
return [isAdj(p1 ,p2,im)for p2 in pixels]

#以下是我用来从图像创建邻接矩阵的函数
def getAdjMatrix(im):
width, height = im.size
pixels = [x(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)
解决方案

Python模块/ library NetworkX有一个邻接矩阵实现。它返回一个SciPy的矩阵



https://networkx.github.io/documentation/latest/reference/generated/networkx.linalg.graphmatrix.adjacency_matrix.html

 导入networkx为nx 
导入scipy为sp
g = nx.Graph([(1,1)])
a = nx。 adjacency_matrix(g)
打印a,类型(a)

返回

 (0,0)1< class'scipy.sparse.csr.csr_matrix'> 


I would like to create a large, weighted adjacency matrix from an image (so lots of vertices... in the order of > 10^5 vertices) in python. Weights between adjacent pixels are color gradients (I take care of this). Doing it by iterating through pixels is very slow... it takes over 4 minutes. :-( Are there any libraries that can do this nicely in reasonable time?

The following is my code which runs very slowly:

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)

Thank you!

解决方案

Python module/library NetworkX has an adjacency matrix implementation. It returns a scipy matrix

https://networkx.github.io/documentation/latest/reference/generated/networkx.linalg.graphmatrix.adjacency_matrix.html

import networkx as nx
import scipy as sp
g = nx.Graph([(1,1)])
a = nx.adjacency_matrix(g)
print a, type(a)

returns

(0, 0)  1 <class 'scipy.sparse.csr.csr_matrix'>

这篇关于在python中从图像创建大的邻接矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆