[Gdal-dev] Python Problem
Mateusz Loskot
mateusz at loskot.net
Fri May 19 11:09:57 EDT 2006
Christopher Condit wrote:
> Hi All-
> I know little to nothing about Python, but am using it to perform some
> simple math on a collection of raster images. In this case, calculating
> mean and variance cellwise on a collection of 40 raster files...
>
> Here's what my code looks like as I collect all of the input bands into
> an array:
> magnitudeBands = []
> thetaBands = []
> for depth in range(40):
> inFile = "C:\\develop\\data\\l%i\\vel-%i.tif" % (depth, month)
> inDataset = gdal.Open( inFile, GA_ReadOnly )
> magnitudeBands.append(inDataset.GetRasterBand(1))
> thetaBands.append(inDataset.GetRasterBand(2))
>
> ... At this point when I examine magnitudeBands, everything looks
> correct.
>
> for y in range(magnitudeBands[0].YSize):
> for band in range(len(magnitudeBands)):
> line = magnitudeBands[band].ReadAsArray( 0, y,
> magnitudeBands[band].XSize, 1, magnitudeBands[band].XSize, 1 )
You're misusing ReadAsArray method.
Here is small snippet that should will help you to understand how to use
ReadAsArray to read horizontal line:
#########################################################
import gdal
from gdalconst import *
import struct
inFile = "/home/mloskot/dev/gdal/data/tester.tif"
inDataset = gdal.Open( inFile, GA_ReadOnly )
band = inDataset.GetRasterBand(1)
for y in range(band.YSize):
# Read horizontal scanline
line = band.ReadAsArray(0, y, band.XSize, 1)
# Unpack block of bytes to python tuple
tpl = struct.unpack('B' * band.XSize, line)
print "Line: %d, length: %d" % (y, len(tpl))
# Print scanline values
#print str(tpl)
#########################################################
It should be easy to add nested loop to iterated through bands of raster.
> But at this point, I get an exception:
> TypeError: Access window out of range in RasterIO(). Requested
> (0,0) of size 720x1 on raster of 9479520x0.
This error says that you passed wrong arguments in 3rd and 4th and
latter positions.
Check RasterIO documentation to learn what is xoff, yoff, xsize, ysize.
http://www.gdal.org/classGDALRasterBand.html#1eef7a21cf4809425c3edced99aa088f
ReadAsArray uses RasterIO function internally.
Cheers
--
Mateusz Łoskot
http://mateusz.loskot.net
More information about the Gdal-dev
mailing list