[gdal-dev] Correct way to create a new GTiff, with numpy.zeros() and python bindings

Antonio Valentino antonio.valentino at tiscali.it
Sat Jun 7 04:59:21 EDT 2008


Il giorno Fri, 6 Jun 2008 17:20:44 -0700
Dane Springmeyer <blake at hailmail.net> ha scritto:

> Hi list,
> 
> Im just starting to use the python bindings and have been  
> experimenting with gdal_rasterize which great results, effectively  
> burning in multiple different colors based on some related vector  
> shapefile attributes.  The trick to getting started was that I did
> not have any raster (at the right extent and resolution) to copy
> from, so to get started I followed the api tutorial to create and new
> Gtiff.
> 
> This code works perfectly for my usecase:
> 
> from osgeo import gdal
> from osgeo import osr
> import numpy
> 
> driver = gdal.GetDriverByName('GTiff')
> dst_ds = driver.Create( "/Users/spring/projects/wind/data/processed/ 
> wpc_final.tif", 7850, 3500, 4, gdal.GDT_Byte)
> dst_ds.SetGeoTransform( [-124.75, .001, 0.0, 49.02, 0.0, -.001] )
> srs = osr.SpatialReference()
> srs.ImportFromEPSG(4326)
> dst_ds.SetProjection( srs.ExportToWkt() )
> 
> 
> But the tutorial also has the step of writing zeros over the image  
> with numpy. Since I am already burning in the required values into
> my raster with gdal_rasterize this seems not to matter, but I am
> really curious for future uses how to get this step working. Starting
> with zeros, or any default value would be useful.
> 
> So, if I execute the following code block next:
> 
> zeros = numpy.zeros( (7850, 3500) )

Dane,
here you are getting a floating point array. Try to print zeros.dtype.
In my opinion the correct code should be

zeros = numpy.zeros( (7850, 3500), dtype=numpy.uint8 )

or something similar.

> dst_ds.GetRasterBand(1).WriteArray( zeros )
> dst_ds.GetRasterBand(2).WriteArray( zeros )
> dst_ds.GetRasterBand(3).WriteArray( zeros )
> dst_ds.GetRasterBand(4).WriteArray( zeros )
> 
> 
> I get the error:
> 'ValueError: array larger than output file, or offset off edge'
> which obviously means that I am writing the wrong size numpy array
> into my raster.
> 
> So, what do I need to know to figure out the right dimensions for
> the numpy.zeros() function? Some slick fraction of my image size in
> pixels and my geotransform?
> 
> Thanks,
> 
> Dane
> 


-- 
Antonio Valentino


More information about the gdal-dev mailing list