Sunday, September 30, 2012

Writing Raster Data with Python / gdal

So now I have a SAR image in a an array called "data" as described in the previous post I want to save it, let's say, in an ERDAS img data format? This is basically converting the file format:

 I first get and register the appropriate driver for the output file:

        >>> driver = gdal.GetDriverByName('HFA')
    >>> driver.Register()

I want to use the same size from the input file which is in "dataset" as in the previous post  

    >>> cols = dataset.RasterXSize
    >>> rows = dataset.RasterYSize
    >>> bands = dataset.RasterCount
    >>> datatype = band.DataType

Then Creating the output file:

    >>> outDataset = driver.Create('ERS1PRI_19920430.pix', cols, rows, bands, datatype)

I want my outputfile to have the same georeferencing and projection information as the input file (the "0" shows the execution went fine):

        >>> geoTransform = dataset.GetGeoTransform()
    >>> outDataset.SetGeoTransform(geoTransform )
    >>> proj = dataset.GetProjection()
    >>> outDataset.SetProjection(proj)

That has to be assigned before writing the data to the output band, otherwise it's not in the file!

Before writing the data, I have to get the band from the newly created file:

     >>> outBand = outDataset.GetRasterBand(1)

Now I can write the input image to the new output image:

    >>> outBand.WriteArray(data, 0, 0)

clean variables and close files
      >>> dataset = None
   >>> band = None
   >>> outBand = None
   >>> outDataset = None

[still to find out: got this to work for PCI format, with ENVI hdr the image but not the geoinformation was transferred and Erdas img did not work -- file too big?]


  1. hello max: it was very usuful blog for me... i was not able to understand the gdal tutorial but you made it such an easy task which i completed in one hour.
    i have one more doubt : is it possible to calculate slope of the image using python commandline(console)??

    1. sorry -- only see that now... what do you mean by slope of the image?

  2. I think (HPF) is the keyword for Erdas imagine format.

    1. This comment has been removed by the author.

    2. oh yes, typo -- ERDAS is in fact HFA, the whole list here: