Fast and direct raster I/O for use with Numpy and SciPy
npx @tessl/cli install tessl/pypi-rasterio@1.4.0Rasterio provides fast and direct raster I/O for use with NumPy and SciPy. Built on top of GDAL, it offers efficient raster I/O operations, geospatial transformations, coordinate reference system management, and windowed reading/writing capabilities for handling large datasets.
pip install rasterioimport rasterio
from rasterio import openFor specific functionality:
from rasterio.crs import CRS
from rasterio.warp import reproject
from rasterio.transform import from_bounds
from rasterio.windows import Windowimport rasterio
import numpy as np
# Open and read a raster file
with rasterio.open('example.tif') as dataset:
# Read the full raster
data = dataset.read()
# Get dataset metadata
print(f"Shape: {data.shape}")
print(f"CRS: {dataset.crs}")
print(f"Transform: {dataset.transform}")
print(f"Bounds: {dataset.bounds}")
# Read a specific band
band1 = dataset.read(1)
# Read a windowed subset
from rasterio.windows import Window
window = Window(0, 0, 512, 512) # col_off, row_off, width, height
subset = dataset.read(1, window=window)
# Create and write a new raster
profile = {
'driver': 'GTiff',
'dtype': 'float32',
'nodata': -9999,
'width': 100,
'height': 100,
'count': 1,
'crs': 'EPSG:4326',
'transform': rasterio.transform.from_bounds(-180, -90, 180, 90, 100, 100)
}
with rasterio.open('output.tif', 'w', **profile) as dst:
# Create sample data
data = np.random.rand(100, 100).astype('float32')
dst.write(data, 1)Rasterio is built around several key components:
DatasetReader and DatasetWriter provide file I/O capabilitiesCRS class handles coordinate reference system transformationsWindow class enables efficient partial reading of large rastersCore functionality for opening, reading, and writing raster datasets. Supports numerous formats through GDAL including GeoTIFF, NetCDF, HDF5, and many others.
def open(fp, mode='r', driver=None, **kwargs): ...
def copy(src_path, dst_path, **kwargs): ...
def band(ds, bidx): ...
def pad(array, transform, pad_width, mode=None, **kwargs): ...Comprehensive coordinate reference system support including EPSG codes, PROJ4 strings, and WKT definitions. Handles CRS transformations and validation.
class CRS:
def __init__(self, initialdata=None, **kwargs): ...
@classmethod
def from_epsg(cls, code): ...
@classmethod
def from_proj4(cls, proj4): ...
def to_epsg(self): ...
def to_proj4(self): ...Affine transformations for converting between pixel and geographic coordinates. Supports creating transforms from bounds, origins, and ground control points.
def from_bounds(west, south, east, north, width, height): ...
def from_origin(west, north, xsize, ysize): ...
def xy(transform, rows, cols, **kwargs): ...
def rowcol(transform, xs, ys, **kwargs): ...Efficient reading and writing of rectangular subsets of raster data. Supports coordinate-based and index-based windowing with geometric operations.
class Window:
def __init__(self, col_off, row_off, width, height): ...
def from_bounds(left, bottom, right, top, transform, **kwargs): ...
def bounds(window, transform): ...
def union(*windows): ...
def intersection(*windows): ...Advanced processing operations including reprojection, masking, merging, and resampling with support for various algorithms and coordinate systems.
def reproject(source, destination, **kwargs): ...
def mask(dataset, shapes, **kwargs): ...
def merge(datasets, **kwargs): ...Conversion between raster and vector data including shape extraction, geometry rasterization, and spatial analysis operations.
def shapes(image, **kwargs): ...
def rasterize(shapes, **kwargs): ...
def geometry_mask(geometries, **kwargs): ...Comprehensive data type support with validation and conversion utilities. Includes enumerations for resampling algorithms and color interpretation.
# Data types
uint8: numpy.dtype
int16: numpy.dtype
float32: numpy.dtype
float64: numpy.dtype
# Enumerations
class Resampling(Enum): ...
class ColorInterp(Enum): ...Complete command-line interface with 23+ subcommands for raster operations including format conversion, reprojection, masking, and analysis.
rio info input.tif
rio warp input.tif output.tif --dst-crs EPSG:3857
rio merge *.tif merged.tif# Core classes
class DatasetReader: ...
class DatasetWriter: ...
class CRS: ...
class Window: ...
# Transformation matrix
class Affine: ...
# Coordinate bounds
class BoundingBox:
left: float
bottom: float
right: float
top: float
# Profile dictionary structure
Profile = dict[str, Any] # Contains driver, dtype, nodata, width, height, count, crs, transformRasterio provides specific exception types for different error conditions:
# Core exceptions
class RasterioError(Exception): ...
class RasterioIOError(RasterioError, OSError): ...
class RasterioDeprecationWarning(FutureWarning): ...
# Specific error types
class InvalidArrayError(RasterioError): ...
class WindowError(RasterioError): ...
class WindowEvaluationError(ValueError): ...
class CRSError(ValueError): ...
class TransformError(RasterioError): ...
class PathError(RasterioError): ...
class EnvError(RasterioError): ...
class DriverCapabilityError(RasterioError, ValueError): ...
class DriverRegistrationError(ValueError): ...
class UnsupportedOperation(RasterioError): ...
class DatasetAttributeError(RasterioError, NotImplementedError): ...
class ResamplingAlgorithmError(RasterioError): ...
class WarpOperationError(RasterioError): ...
class WarpOptionsError(RasterioError): ...
class WarpedVRTError(RasterioError): ...
class StatisticsError(RasterioError): ...
class MergeError(RasterioError): ...
class StackError(RasterioError): ...
class RPCError(ValueError): ...
# Warning types
class NodataShadowWarning(UserWarning): ...
class NotGeoreferencedWarning(UserWarning): ...
class TransformWarning(UserWarning): ...
class ShapeSkipWarning(UserWarning): ...
class BandOverviewError(UserWarning): ...