Search code examples
pythongdal

GDAL driver.Create() TypeError


I have used the osgeo.gdal module to save numpy arrays as GeoTIFF files successfully in python for some time. Today I decided to write a simple module to handle the driver and file creation routines. Calling my module to save a numpy array gives the following error:

Traceback (most recent call last):
File "saveRaster.py", line 30, in <module>
    save_raster(destination,1,array,srs,gt)
File "saveRaster.py", line 10, in save_raster
    dataset_out = driver.Create(path, cols, rows, bands, dtype)
File "/Library/Frameworks/GDAL.framework/Versions/2.1/Python/2.7/site-packages/osgeo/gdal.py", line 1440, in Create
    return _gdal.Driver_Create(self, *args, **kwargs)
TypeError: in method 'Driver_Create', argument 5 of type 'int'

This is odd since argument 5 is the datatype argument, which should take a gdal data type such as gdal.GDT_Float32. However, if it try type(gdal.GDT_Float32) it returns <type 'int'>. Why then is gdal giving me a TypeError if an integer ought to be exactly what it is expecting?

My code is below:

#! /usr/bin/env python

from osgeo import gdal,osr
import numpy as np

def save_raster(path, band_count, bands, srs, gt, format='GTiff', dtype=gdal.GDT_Float32):
    cols,rows = bands.shape
    # Initialize driver & create file
    driver = gdal.GetDriverByName(format)
    dataset_out = driver.Create(path, cols, rows, bands, dtype)
    dataset_out.SetGeoTransform(gt)
    dataset_out.SetProjection(srs)
    # Write the array to raster bands
    for b in range(band_count):
        out_band = dataset_out.GetRasterBand(b+1)
        out_band.WriteArray(bands[b])
    # Write file to disk
    dataset_out.FlushCache()

gt = [0,1,0,0,0,-1]

srs = osr.SpatialReference()
srs.ImportFromEPSG(epsg)
srs = srs.ExportToWkt()

destination = '~/Desktop/arr.tif'

array = np.arange(0,25).reshape(5,5)

save_raster(destination,1,array,srs,gt)

Solution

  • This question is a bit old, but I encountered this issue and identified the problem.

    As you can see from your traceback, driver.Create is an API for _gdal.Driver_Create, which has a different sequence of arguments. When the Exception mentions argument 5 of type 'int' it is referring to the band count. It is likely that you had a data type that is not 'int' for you bands parameter.

    These types of issues have tripped me up frequently when using numpy and GDAL together, since the GDAL Python API has a tight control over accepted types.