compute_ndvi
Calculate NDVI (Normalized Difference Vegetation Index) from input raster bands, specifying red and near-infrared band indices, and save the result as a GeoTIFF file for vegetation analysis.
Instructions
Compute NDVI (Normalized Difference Vegetation Index) and save to GeoTIFF.
Parameters:
- source: input raster path.
- red_band_index: index of red band (1-based).
- nir_band_index: index of near-infrared band (1-based).
- destination: output NDVI raster path.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| destination | Yes | ||
| nir_band_index | Yes | ||
| red_band_index | Yes | ||
| source | Yes |
Implementation Reference
- The core handler function for the 'compute_ndvi' tool. It reads the specified red and NIR bands from the input raster, computes the NDVI using the formula (NIR - RED) / (NIR + RED + epsilon), handles NoData implicitly via numpy, updates the raster profile for a single float32 band, and writes the output to the specified destination path.@gis_mcp.tool() def compute_ndvi( source: str, red_band_index: int, nir_band_index: int, destination: str ) -> Dict[str, Any]: """ Compute NDVI (Normalized Difference Vegetation Index) and save to GeoTIFF. Parameters: - source: input raster path. - red_band_index: index of red band (1-based). - nir_band_index: index of near-infrared band (1-based). - destination: output NDVI raster path. """ try: import rasterio import numpy as np src_path = os.path.expanduser(source.replace("`", "")) dst_path = os.path.expanduser(destination.replace("`", "")) with rasterio.open(src_path) as src: red = src.read(red_band_index).astype("float32") nir = src.read(nir_band_index).astype("float32") ndvi = (nir - red) / (nir + red + 1e-6) # avoid division by zero profile = src.profile.copy() profile.update(dtype="float32", count=1) os.makedirs(os.path.dirname(dst_path) or ".", exist_ok=True) with rasterio.open(dst_path, "w", **profile) as dst: dst.write(ndvi, 1) return { "status": "success", "destination": str(dst_path), "message": f"NDVI calculated and saved to '{dst_path}'." } except Exception as e: raise ValueError(f"Failed to compute NDVI: {e}")
- src/gis_mcp/rasterio_functions.py:11-35 (registration)Resource listing that includes 'compute_ndvi' as one of the available rasterio operations, potentially used for tool discovery.@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" ] }