raster_algebra
Perform addition or subtraction on raster bands to combine or compare geospatial data, with automatic alignment handling for accurate results.
Instructions
Perform algebraic operations (addition or subtraction) on two raster bands, handling alignment issues automatically.
Parameters:
raster1: Path to the first raster (.tif).
raster2: Path to the second raster (.tif).
band_index: Index of the band to process (1-based index).
operation: Either "add" or "subtract" to specify the calculation.
destination: Path to save the result as a new raster.
The function aligns rasters if needed, applies the selected operation, and saves the result.
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| raster1 | Yes | ||
| raster2 | Yes | ||
| band_index | Yes | ||
| operation | Yes | ||
| destination | Yes |
Implementation Reference
- The core handler function for the 'raster_algebra' tool. It takes two raster paths, a band index, an operation ('add' or 'subtract'), and a destination path. Automatically aligns the rasters if CRS, transform, or shape differ, performs the operation on the specified bands, and writes the result to the output file.def raster_algebra( raster1: str, raster2: str, band_index: int, operation: str, # User selects "add" or "subtract" destination: str ) -> Dict[str, Any]: """ Perform algebraic operations (addition or subtraction) on two raster bands, handling alignment issues automatically. Parameters: - raster1: Path to the first raster (.tif). - raster2: Path to the second raster (.tif). - band_index: Index of the band to process (1-based index). - operation: Either "add" or "subtract" to specify the calculation. - destination: Path to save the result as a new raster. The function aligns rasters if needed, applies the selected operation, and saves the result. """ try: import rasterio import numpy as np from rasterio.warp import reproject, calculate_default_transform, Resampling # Expand file paths r1 = os.path.expanduser(raster1.replace("`", "")) r2 = os.path.expanduser(raster2.replace("`", "")) dst = os.path.expanduser(destination.replace("`", "")) # Open the raster files with rasterio.open(r1) as src1, rasterio.open(r2) as src2: # Ensure alignment of rasters if src1.crs != src2.crs or src1.transform != src2.transform or src1.shape != src2.shape: transform, width, height = calculate_default_transform( src2.crs, src1.crs, src2.width, src2.height, *src2.bounds ) aligned_data = np.zeros((height, width), dtype="float32") reproject( source=src2.read(band_index), destination=aligned_data, src_transform=src2.transform, src_crs=src2.crs, dst_transform=transform, dst_crs=src1.crs, resampling=Resampling.bilinear ) band2 = aligned_data else: band2 = src2.read(band_index).astype("float32") band1 = src1.read(band_index).astype("float32") # Perform the selected operation if operation.lower() == "add": result = band1 + band2 elif operation.lower() == "subtract": result = band1 - band2 else: raise ValueError("Invalid operation. Use 'add' or 'subtract'.") # Prepare output raster metadata profile = src1.profile.copy() profile.update(dtype="float32", count=1) # Ensure the output directory exists os.makedirs(os.path.dirname(dst) or ".", exist_ok=True) # Save the result to a new raster file with rasterio.open(dst, "w", **profile) as dstfile: dstfile.write(result, 1) return { "status": "success", "destination": dst, "message": f"Raster operation '{operation}' completed and saved." } except Exception as e: raise ValueError(f"Failed to perform raster operation: {e}")
- src/gis_mcp/rasterio_functions.py:11-35 (registration)Resource endpoint listing 'raster_algebra' as an available rasterio operation, which serves as a discovery mechanism for the tool.@gis_mcp.resource("gis://operation/rasterio") def get_rasterio_operations() -> Dict[str, List[str]]: """List available rasterio operations.""" return { "operations": [ "metadata_raster", "get_raster_crs", "clip_raster_with_shapefile", "resample_raster", "reproject_raster", "weighted_band_sum", "concat_bands", "raster_algebra", "compute_ndvi", "raster_histogram", "tile_raster", "raster_band_statistics", "extract_band", "zonal_statistics", "reclassify_raster", "focal_statistics", "hillshade", "write_raster" ] }
- src/gis_mcp/main.py:66-72 (registration)Imports the rasterio_functions module in the main entry point, which executes the decorators to register the 'raster_algebra' tool with the MCP server.from . import ( geopandas_functions, shapely_functions, rasterio_functions, pyproj_functions, pysal_functions, )