[Gdal-dev] export an image to ascii text file
Bryan Keith
bryan at geomega.com
Fri Feb 3 16:37:27 EST 2006
Xiaodong,
Attached is a python script that I've used to do part of what you've
asked for (I'm pretty sure this list accepts attachments). It's not a
polished tool, but the code may help you get started.
Note that the xy calculations are dependent on the cell size being the
same in x and y. You'll notice that this will only output a single band
as it's currently written. Also it doesn't attempt to project to lat
and lon. It outputs the coordinates of the images projection.
Even with these caveats maybe it helps.
Bryan
Bryan Keith
GIS Specialist
Geomega, Inc.
Boulder, CO, USA
Xiaodong Zhang wrote:
> Hi,
>
> I need to export an image (any projection) into an ascii file: coma
> delimited columns of lat, lon, band 1, band 2, ..... Before I get on
> that with GDAL library, does anyone have developed or know of such a
> program, which can be shared.
>
> Thanks
> Xiaodong
>
-------------- next part --------------
import gdal, sys, struct
from gdalconst import *
def Usage():
print "Usage: RasterToXYZ.py rastername rasterband outputasciifile"
print "This routine will write out ascii XYZ data for the input raster."
print "rasterband is typically 1 (the first band)"
return
if len(sys.argv) != 4:
Usage()
sys.exit()
dataset = gdal.Open(sys.argv[1],GA_ReadOnly)
band = dataset.GetRasterBand(int(sys.argv[2]))
geotransform = dataset.GetGeoTransform()
#geotransform[0],geotransform[3] are the (x,y) of the upper left corner of the upper left
#pixel
#geotransform[1] is the cell size in x
#geotransform[5] is the cell size in y (in this case cell size is the same in x and y)
#the following line reads a row (constant y) of data (the top most (ymax) row)
#scanline = band.ReadRaster(0,0,band.XSize,1,band.XSize,1,GDT_Float32)
#tuple_of_floats = struct.unpack('f' * band.XSize, scanline)
#the following line reads the second row of data
#scanline = band.ReadRaster(0,1,band.XSize,1,band.XSize,1,GDT_Float32)
f = open(sys.argv[3],'w')
f.write('x,y,z\n')
for y in range(band.YSize): #from 0 to 838
scanline = band.ReadRaster(0,y,band.XSize,1,band.XSize,1)
tuple_of_floats = struct.unpack('f' * band.XSize, scanline)
x = 0
strY = str((geotransform[3] - (geotransform[1] * 0.5)) - (y * geotransform[1]))
for z in tuple_of_floats:
f.write(str((x * geotransform[1]) + geotransform[0] + (geotransform[1] * 0.5)) + ",")
f.write(strY + ",")
f.write(str(z) + '\n')
x = x + 1
f.close()
More information about the Gdal-dev
mailing list