rasterio
| Language | Python |
|---|---|
| License | BSD 3-Clause |
| Repository | github.com/rasterio/rasterio |
| Documentation | rasterio.readthedocs.io |
| Depends on | GDAL (included in the wheels), NumPy |
| Read / write | yes / yes, GeoTIFF, BigTIFF, COG, tiles, overviews, all compressions of GDAL's GTiff driver |
rasterio is a Pythonic API over GDAL for raster geodata. It reads bands into NumPy arrays and exposes the coordinate reference system (crs), the affine transform from pixel to map coordinates, nodata values and tags. Writing takes the same keywords GDAL’s GTiff driver uses (compress, tiled, blockxsize, bigtiff).
Use it for maps, satellite and drone images and elevation models. For ordinary photos and scans, Pillow or tifffile are lighter.
Installation#
Shell
pip install rasterio
Basic usage: read a GeoTIFF#
Python
import rasterio
with rasterio.open("dem.tif") as src:
print(src.width, src.height, src.count, src.dtypes)
print(src.crs) # e.g. EPSG:32633
print(src.transform) # affine pixel -> map transform
print(src.bounds, src.nodata)
band1 = src.read(1) # NumPy array of band 1 (bands are 1-based)
print(band1.min(), band1.max())
How to write a compressed GeoTIFF#
Python
import numpy as np
import rasterio
from rasterio.transform import from_origin
data = np.random.rand(1000, 1000).astype("float32")
transform = from_origin(10.0, 50.0, 0.001, 0.001) # west, north, pixel width, pixel height
with rasterio.open(
"out.tif", "w",
driver="GTiff",
width=data.shape[1], height=data.shape[0],
count=1, dtype="float32",
crs="EPSG:4326", transform=transform,
nodata=-9999,
compress="deflate", predictor=3, tiled=True,
) as dst:
dst.write(data, 1)
How to get the value at a coordinate#
Python
with rasterio.open("dem.tif") as src:
row, col = src.index(13.4, 52.5) # x (lon), y (lat) in the file's CRS
value = src.read(1)[row, col]
# or sample many points without reading the whole band
for vals in src.sample([(13.4, 52.5), (13.5, 52.6)]):
print(vals)
How to read a window of a large GeoTIFF#
Python
from rasterio.windows import Window
with rasterio.open("big.tif") as src:
part = src.read(1, window=Window(col_off=5000, row_off=5000, width=512, height=512))
How to write a Cloud Optimized GeoTIFF#
Python
import rasterio
from rasterio.shutil import copy
copy("in.tif", "out_cog.tif", driver="COG", compress="deflate")
How to read tags and copy the profile#
Python
with rasterio.open("in.tif") as src:
print(src.tags()) # TIFF and GDAL metadata, e.g. TIFFTAG_SOFTWARE
profile = src.profile # driver, dtype, size, crs, transform, compression...
data = src.read()
profile.update(compress="zstd")
with rasterio.open("recompressed.tif", "w", **profile) as dst:
dst.write(data)
Tips#
- Open remote COGs directly:
rasterio.open("https://example.com/cog.tif")reads only the needed byte ranges. rio info file.tif(the command-line tool installed with rasterio) prints the profile as JSON.