Wednesday, December 3, 2008

Create a GeoTiff with Python and GDAL

It looks like the GDAL tutorial on creating GeoTiff's is slightly outdated (2008/05). I received this error with Python 2.5.2, GDAL 1.53 and NumPy 1.0.4:
Traceback (most recent call last):
File "", line 9, in <module>
File "/usr/lib/python2.5/site-packages/", line 796, in WriteArray

File "usr/lib/python2.5/site-packages/osgeo/", line 154, in BandWriteArray
AttributeError: dtype

As far as I can tell this occurs because the matrix raster doesn't have the attribute (property) dtype. Something must have changed, but I managed to get it going by using the numpy lib rather than Numeric.

The code that worked for me looks like this:
import numpy
from osgeo import osr, gdal
format = "GTiff"
driver = gdal.GetDriverByName( format )
dst_ds = driver.Create("out.tif", 512, 512, 1, gdal.GDT_Byte )
raster = numpy.zeros( (512, 512) )

One can also explicitly state the matrix's data type by adding the dtype attribute:
raster = numpy.zeros( (512, 512), dtype = numpy.uint8)


Anonymous said...

Cheers for this snippet ;)

Aron said...

Thanks for this. You should explicitly close the file as well. I don't see anything too Pythonic, but you might try:

del dst_ds