I'm new here and beginner with python. I'm looking for a solution to my problem for some hours but now you are my last chance... I'm using the python (2.7.5) console in QGIS (2.4.0). Is there a solution to do loops on raster cells? I would like to create a raster in which each value cell will depend on the position (column and row number) in the raster.
I'm looking for something like this python code in Arcgis (I found it here: How to get X Y coordinates and cell value of each pixel in a raster using Python?)
for row in range(0,height):
for col in range(0,width):
#now you have access to single array of values for one cell location
Thanks!
Answer
Arcpy use the Numpy array format (hidden to the users) as PyGGIS that uses the Python GDAL module.
provider = raster.dataProvider()
# path the original file
filePath = str(provider.dataSourceUri())
# open the original file
from osgeo import gdal
raster_or = gdal.Open(filePath)
# create a numpy array
numpy_array = raster_or.ReadAsArray()
# shape of the array
print numpy_array.shape
(60, 100) # my example
# compare with
print raster.height(),raster.width()
(60, 100)
width,height = numpy_array.shape # or width = raster.width and height = raster.height()
# and
for row in range(0,width):
for col in range(0,height):
print row,col,numpy_array[row,col]
Reading the entire image at once is pretty efficient, but not the best. The most efficient way to access raster data is by blocks (look at Chris Garrard courses Reading Raster Data with GDAL)
No comments:
Post a Comment