# Converting raster (array) to NetworkX graph and do * search? [closed]

I want to use a slope-raster for a a_star path analysis in NetworkX. I am using Python for this project.

My test raster looks like this

First I read in the raster with GDAL

``````input_raster = "slope5.tif"
raster = gdal.Open(input_raster)
``````

Next I read the raster as an array

``````bandraster = raster.GetRasterBand(1)
``````

The array looks like this

``````>>> arr
array([[ 15.26072407,  16.01073837,  27.81685448,  24.49266815,
32.94010162],
[ 26.0834446 ,  21.01086426,  30.02531815,  25.44641304,
19.48436928],
[ 21.98579979,  19.06574059,  24.44838905,  26.67520905,
26.61030769],
[ 20.42549133,  28.58900261,  17.00629425,  31.25236893,
32.34066772],
[  8.33120537,  24.303339  ,   7.85025167,  35.50911713,
29.56856346]], dtype=float32)
``````

Then I create from the array a graph

``````G = nx.DiGraph(arr)
``````

As far as I understand it my graph looks like this

``````(0,0) (0,1) (0,2) (0,3) (0,4)
(1,0) (1,1) (1,2) (1,3) (1,4)
(2,0) (2,1) (2,2) (2,3) (2,4)
(3,0) (3,1) (3,2) (3,3) (3,4)
(4,0) (4,1) (4,2) (4,3) (4,4)
``````

So for example the weight of `G[3][2]` is `{'weight': 17.00629425048828}`

How do I now find the A star path?

I tried the following to find the way from `(1,0)` to `(3,3)`?

``````nx.astar_path(G,(1,0),(3,3))
``````

But that only gave

``````Traceback (most recent call last):
File "<pyshell#44>", line 1, in <module>
nx.astar_path(G,(1,4),(4, 2))
File "C:\Python27\lib\site-packages\networkx\algorithms\shortest_paths\astar.py", line 108, in astar_path
for neighbor, w in G[curnode].items():
File "C:\Python27\lib\site-packages\networkx\classes\graph.py", line 319, in __getitem__
KeyError: (1, 4)
``````

My nodes and edges look likes this:

``````>>> G.nodes()
[0, 1, 2, 3, 4]
>>> G.edges()
[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (2, 0), (2, 1), (2, 2), (2, 3), (2, 4), (3, 0), (3, 1), (3, 2), (3, 3), (3, 4), (4, 0), (4, 1), (4, 2), (4, 3), (4, 4)]
``````
1. Is this the right approach?
2. How do I find the path?
3. Did I mix up something with nodes and edges?
• You might ask this question on stackoverflow.com or post an answer, if you found one by now.
– user25302
Dec 29, 2013 at 16:47
• I solved my problem using the `skimage.graph` library and this approach. But it doesn't answer my original question. Dec 30, 2013 at 18:11
• outdated question, but FWIW looks like incorrect use of translating NumPy matrix to graph - NetworkX wants the matrix to be an adjacency graph where cell values are strength of ties between nodes. For example, as written the graph created in this question does not have an edge `G[3][2]` with `weight: 17.006...` Jul 5, 2017 at 2:35