Rasters merging/mosaic is one of the common task in raster processing. In this tutorial, we will merge multiple rasters into one in python using Rioxarray. Merging/mosaic multiple rasters into one is also known as union of rasters. Rioxarray is open source gis package that extends the functionality of xarray by rasterio.
Before merging multiple rasters into one, we will set up conda environment and install required python GIS packages for this task. Make sure conda is installed on your system. Use following commands to create a conda environment and to install python libraries.
When you install geocube library using conda, it will automatically install related dependencies that includes gdal, shapely, rasterio, geopandas, xarray, rioxarray etc.
And we will also install pygeos library which is used to speed up the vectorized operations in GeoPandas and Shapely.
(base) geoknight@pop-os:~$conda create -n spatial-dev.guru python=3.10
(base) geoknight@pop-os:~$conda activate spatial-dev.guru
(spatial-dev.guru) geoknight@pop-os:~$conda install -c conda-forge geocube
(spatial-dev.guru) geoknight@pop-os:~$conda install -c conda-forge pygeos
Once you have successfully installed required libraries, the we will use rioxarray to merge multiple rasters.
Before merging multiple rasters, make sure all rasters are in same projection system. In our given example, all rasters are in 3857 projection system.
To merge multiple rasters, follow the below steps:
1. Import rioxarray module and merge_arrays method from rioxarray.merge module.
2. Read rasters that you want to merge. In this example, we are reading two raster tiles using rioxarray that belongs to same area of interest.
3. And finally, we will use merge_arrays method to merge rasters geospatially. You can pass various parameters to this method to alter the merged output. dataarrays parameter is recommended parameter which represents array of rasters that we read at line number 5 and 6. res parameter means the the resolution of raster or cell size or pixel size for merged output. The crs parameter means the projection system for merged output. The nodata parameter means nodata value for merged output.
Note: The default values for parameters will be taken from first element of data arrays object if not specified explicitly.
# Import libraries
import rioxarray as riox
from rioxarray.merge import merge_arrays
# Read rasters file
tile_1 = riox.open_rasterio("raster_tiles/tile_1.tiff")
tile_2 = riox.open_rasterio("raster_tiles/tile_2.tiff")
# Merge/Mosaic multiple rasters using merge_arrays method of rioxarray
merged_raster = merge_arrays(dataarrays = [tile_1, tile_2], res = (500, 500), crs="EPSG:3857", nodata = 0)
# Save Raster to disk
I hope this tutorial will create a good foundation for you. If you want tutorials on another GIS topic or you have any queries, please send an email at email@example.com.