- Published on
Combining rasters with rasterio
- Authors
- Name
- James Gardiner
- @_JamesRG
I've recently been using LiDAR derived Digital Terrain Models, available from DataMapWales as 1km x 1km tile downloads. Although this keeps the file size small, being able to work with a single raster file is easier.
We can use Rasterio's merge method to combine the rasters into a single image.
First, install the requirements into a Python environment:
$ pip install rasterio
Create an iterable of the raster file paths and pass it to the merge method; this will return a tuple with two elements. The first, dest
, is the raster in the form of a numpy ndarray, and the second, out_transform
is an affine transformation that we will add to the Geotiff's metadata when writing to the file system.
from pathlib import Path
import rasterio
path = Path(".")
dest, output_transform = rasterio.merge(list(path.glob("**/*.tif")))
Next, get a copy of the metadata from one of the original raster files, and update the height, width and transform values:
with rasterio.open("original1.tif") as src:
out_meta = src.meta.copy()
out_meta.update(
{
"driver": "GTiff",
"height": dest.shape[1],
"width": dest.shape[2],
"transform": output_transform
}
)
And then simply write the new, merged raster to a tif file:
with rasterio.open("merged.tif", "w", **out_meta) as fp:
fp.write(dest)
The whole process looks like this:
from pathlib import Path
import rasterio
path = Path(".")
dest, output_transform = rasterio.merge(list(path.glob("**/*.tif")))
with rasterio.open("original1.tif") as src:
out_meta = src.meta.copy()
out_meta.update(
{
"driver": "GTiff",
"height": dest.shape[1],
"width": dest.shape[2],
"transform": output_transform
}
)
with rasterio.open("merged.tif", "w", **out_meta) as fp:
fp.write(dest)