0

I want to use a raster for a A* and bidirectional Dijkstra path analysis in NetworkX. I am using Python for this project.

Raster example (it's a png file converted when uploaded, but the real problem is TIFF): [Here](https://i.stack.imgur.com/fz9CM.png)

First I read in the raster with GDAL

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

Next I read the raster as an array

bandraster = raster.GetRasterBand(1)
arr = bandraster.ReadAsArray()

So, I'll transform coords using a function:

def coord2pixelOffset(rasterfn, x, y):
    raster = gdal.Open(rasterfn)
    geotransform = raster.GetGeoTransform()
    originX = geotransform[0]
    originY = geotransform[3]
    pixelWidth = geotransform[1]
    pixelHeight = geotransform[5]
    xOffset = int((x - originX)/pixelWidth)
    yOffset = int((y - originY)/pixelHeight)
    return xOffset, yOffset

CostSurfacefn = 'raster.tif'
source_coord = (-41.1823753163, -13.83393276)
target_coord = (-40.3726182077, -14.2361991946)

# coordinates to array index
source = coord2pixelOffset(CostSurfacefn, source_coord[0], source_coord[1])
target = coord2pixelOffset(CostSurfacefn, target_coord[0], target_coord[1])

The array is like this (example):

# Grid with 2x2. The float numbers are the pixel values 
[[  1.83781120e+08   1.90789248e+08]
[  1.83781120e+08   1.90789248e+08]]

# array[0][0] is 1.83781120e+08
# array[0][1] is 1.90789248e+08
# array[1][0] is 1.83781120e+08
# array[1][1] is 1.90789248e+08

Next, the graph is loaded and bi-dijkstra function is called (but I want for example from array[0][0] to array[1][1] ):

G = nx.from_numpy_matrix(np.array(arr))
length, path = nx.bidirectional_dijkstra(G, source, target)

How to get the node id of source and target by array?

  • Not knowing all of the packages you're using, is it obvious why you expect `bandraster.ReadAsArray` to give coordinates that correspond to the output of `coord2pixelOffset`? – Joel May 14 '17 at 04:32
  • Hi @Joel! The packages are GDAL and Networkx only. I expect to get the correct pixel index based on the coordinates, but this is not happening. I do not know the correct approach to solve this. Thanks! – Ailton Filho May 14 '17 at 14:45
  • have you checked what nodes are in the graph? (are they definitely integer tuples)? – Joel May 14 '17 at 14:50
  • Hi @Joel! I check the image and it's ok. I'm load the graph in this way: G = nx.from_numpy_matrix(np.array(array)) But, i don't know how to convert the matrix index(x,y) in node index # Node 1 to Node 38 length, path = nx.bidirectional_dijkstra(G, 1, 38) – Ailton Filho May 16 '17 at 01:42

0 Answers0