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):
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?