GDAL (Geospatial Data Abstraction Library)

3.12.3 · active · verified Wed Apr 15

GDAL (Geospatial Data Abstraction Library) is a powerful translator library for raster and vector geospatial data formats. It provides a single abstract data model for applications to interact with various data types. The `osgeo` Python bindings allow Python applications to leverage GDAL's extensive capabilities. The current version is 3.12.3, and it maintains a continuous release cycle, typically aligning with the core C++ library updates.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates basic raster and vector data handling using in-memory datasets with `osgeo.gdal` and `osgeo.ogr`. It includes setting up error handling to raise Python exceptions and ensures datasets are properly released.

from osgeo import gdal, ogr, osr

# Configure GDAL to raise Python exceptions for errors
gdal.UseExceptions()

# --- Raster Quickstart (using an in-memory dataset) ---
print("--- Raster Quickstart ---")
driver = gdal.GetDriverByName("MEM")
# Create a 10x10, 1-band, Byte-type in-memory raster dataset
ds_raster = driver.Create("dummy_raster", 10, 10, 1, gdal.GDT_Byte)
ds_raster.SetProjection("EPSG:4326") # Set a dummy geographic projection
raster_band = ds_raster.GetRasterBand(1)
raster_band.WriteArray([[i * j for j in range(10)] for i in range(10)])

print(f"Raster Driver: {ds_raster.GetDriver().LongName}")
print(f"Raster Size: {ds_raster.RasterXSize}x{ds_raster.RasterYSize}")
print(f"Raster Projection: {ds_raster.GetProjectionRef()[:20]}...") # Abbreviate for brevity
print(f"First pixel value: {raster_band.ReadAsArray()[0, 0]}")

ds_raster = None # Release the dataset

# --- Vector Quickstart (using an in-memory dataset) ---
print("\n--- Vector Quickstart ---")
driver = ogr.GetDriverByName("Memory")
# Create an in-memory vector datasource
ds_vector = driver.CreateDataSource("dummy_vector")
# Create a layer
srs = osr.SpatialReference()
srs.SetFromUserInput("EPSG:4326")
layer = ds_vector.CreateLayer("points", srs, ogr.wkbPoint)

# Add a field
field_defn = ogr.FieldDefn("name", ogr.OFTString)
layer.CreateField(field_defn)

# Create a feature
feature = ogr.Feature(layer.GetLayerDefn())
feature.SetField("name", "Test Point")
point = ogr.Geometry(ogr.wkbPoint)
point.AddPoint(10.0, 20.0) # Lon, Lat
feature.SetGeometry(point)
layer.CreateFeature(feature)

print(f"Vector Layer Name: {layer.GetName()}")
print(f"Number of Features: {layer.GetFeatureCount()}")
# Access the first feature
first_feature = layer.GetFeature(0)
print(f"First Feature Name: {first_feature.GetField("name")}")
print(f"First Feature Geometry: {first_feature.GetGeometryRef().ExportToWkt()}")

ds_vector = None # Release the datasource

view raw JSON →