Rasterio
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
- breaking Rasterio 1.5.0 introduced significant minimum version requirements: Python 3.12+, GDAL 3.8+, and NumPy 2+. Older Rasterio versions have different requirements (e.g., 1.4.x required Python 3.10+, GDAL 3.6+).
- gotcha Rasterio relies on an external GDAL C/C++ library. Installing GDAL (and its dependencies like PROJ and GEOS) can be complex and platform-dependent, often requiring specific system packages or conda environments.
- gotcha Behavioral changes in masking and `reproject()`: Prior to 1.4.3, boundless, masked reads could erroneously mask 0-valued data. Also, `reproject()` in versions before 1.4.2 might not consistently return 2-D arrays.
- gotcha Passing an open dataset object to `rasterio.open()`: Prior to Rasterio 1.4.3, this common mistake could lead to unexpected crashes. It now raises a `TypeError` for safer error handling.
Install
-
pip install rasterio
Imports
- rasterio
import rasterio
- open
import rasterio src = rasterio.open('path/to/file.tif') - CRS
from rasterio.crs import CRS
Quickstart
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)