Rasterio

1.5.0 · active · verified Thu Apr 09

Rasterio provides fast and direct raster I/O for use with NumPy, built on top of GDAL. It's a fundamental library for reading, writing, and manipulating geospatial raster data in Python. Rasterio typically releases new versions in response to GDAL updates and Python version changes, with minor releases for bug fixes and new features.

Warnings

Install

Imports

Quickstart

Demonstrates how to open a raster dataset, access its metadata (profile, CRS, bounds), and read a specific band into a NumPy array. A dummy GeoTIFF is created for standalone execution.

import rasterio
import numpy as np
import os

# Create a dummy GeoTIFF for demonstration purposes
# In a real application, you would open an existing file
dummy_filepath = '/tmp/example_rasterio.tif'

# Ensure the directory exists
if not os.path.exists(os.path.dirname(dummy_filepath)):
    os.makedirs(os.path.dirname(dummy_filepath))

with rasterio.open(
    dummy_filepath,
    'w',
    driver='GTiff',
    height=10,
    width=10,
    count=1,
    dtype=rasterio.uint8,
    crs='EPSG:4326',
    transform=rasterio.transform.from_origin(0, 0, 1, 1),
) as dst:
    dst.write(np.zeros((10, 10), dtype=rasterio.uint8), 1)

# --- Quickstart: Open and inspect a raster --- 
try:
    with rasterio.open(dummy_filepath) as src:
        print(f"Dataset profile: {src.profile}")
        print(f"Number of bands: {src.count}")
        print(f"Coordinate Reference System: {src.crs}")
        print(f"Bounds: {src.bounds}")

        # Read the first band as a NumPy array
        band1 = src.read(1)
        print(f"Shape of band 1: {band1.shape}")
        print(f"Data type of band 1: {band1.dtype}")

except rasterio.errors.RasterioIOError as e:
    print(f"Error opening raster: {e}. Make sure '{dummy_filepath}' exists and is a valid raster.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

# Clean up the dummy file
if os.path.exists(dummy_filepath):
    os.remove(dummy_filepath)

view raw JSON →