wiki:GdalOgrInPython

Version 6 (modified by warmerdam, 11 years ago) (diff)

--

GDAL/OGR In Python

The GDAL project (primarily Howard Butler) maintains SWIG generated Python bindings for GDAL and OGR. Generally speaking the classes and methods mostly match those of the GDAL and OGR C++ classes. There is no python specific reference documentation, but the GDAL API Tutorial includes Python examples.

New vs. Old Bindings

Python was the first set of bindings supported by GDAL/OGR and though the bindings were generated with SWIG, the process was very python specific. In 2005 Kevin Ruland launched an effort for a set of Next Generation bindings generated with SWIG and supported by a variety of languages. With GDAL 1.4.0 the various bindings are becoming fairly mature, and the next generation python bindings are becoming the preferred set in place of the old bindings. However for python both are still available.

The old generation bindings live in the gdal/pymod directory, and are mixed up with various python utility scripts, and samples. The new generation bindings live in the gdal/swig/python directory. On unix to build with the old generation bindings you would configure --with-python --without-ngpython. To build with the new generation bindings you would use --without-python --with-ngpython.

The new python bindings are generally compatible with the old bindings though some quirks exist. As time goes on the new bindings will continue to be extended as GDAL is extended, but the old generation bindings will not. At this time the test suite should pass with either the old or new bindings. Some applications, such as OpenEV 1.x still depend on the old Python bindings (which is why FWTools still ships with the old bindings).

Numpy / Numeric

One advanced feature of the GDAL python bindings not found in the other bindings is integration with the Python numerical array facilities. The gdal.Dataset.ReadAsArray() method can be used to read raster data as numerical arrays, ready to use with the Python numerical array capabilities.

These facilities have evolved somewhat over time. In the past the package was known as "Numeric" and imported using "import Numeric". A new generation is imported using "import numpy". Currently the old generation bindings only support the older Numeric package, and the new generatio bindings only support the new generation numpy package. They are mostly compatible, and by importing gdalnumeric you will get whichever is appropriate to the current bindings type.

One example of GDAL/numpy integration is found in the sample pymod/samples/val_repl.py script.

Examples