Skip to main content
Glama

zonal_statistics

Compute raster statistics within polygons to analyze spatial data. Input raster and vector files to calculate metrics like mean, min, max, and std per polygon. Returns detailed results for geospatial analysis.

Instructions

Calculate statistics of raster values within polygons (zonal statistics). Args: raster_path: Path to the raster file. vector_path: Path to the vector file (polygons). stats: List of statistics to compute (e.g., ["mean", "min", "max", "std"]). Returns: Dictionary with status, message, and statistics per polygon.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
raster_pathYes
statsNo
vector_pathYes

Implementation Reference

  • The core handler function for the 'zonal_statistics' tool, decorated with @gis_mcp.tool(). It reads a vector file with geopandas, masks the raster using rasterio.mask for each polygon, computes specified statistics (mean, min, max, std) on masked data using numpy, and returns results per polygon.
    @gis_mcp.tool() def zonal_statistics(raster_path: str, vector_path: str, stats: list = None) -> Dict[str, Any]: """ Calculate statistics of raster values within polygons (zonal statistics). Args: raster_path: Path to the raster file. vector_path: Path to the vector file (polygons). stats: List of statistics to compute (e.g., ["mean", "min", "max", "std"]). Returns: Dictionary with status, message, and statistics per polygon. """ try: import rasterio import rasterio.mask import geopandas as gpd import numpy as np if stats is None: stats = ["mean", "min", "max", "std"] gdf = gpd.read_file(vector_path) with rasterio.open(raster_path) as src: results = [] for idx, row in gdf.iterrows(): geom = [row["geometry"]] out_image, out_transform = rasterio.mask.mask(src, geom, crop=True, filled=True) data = out_image[0] data = data[data != src.nodata] if src.nodata is not None else data stat_result = {"index": idx} if data.size == 0: for s in stats: stat_result[s] = None else: if "mean" in stats: stat_result["mean"] = float(np.mean(data)) if "min" in stats: stat_result["min"] = float(np.min(data)) if "max" in stats: stat_result["max"] = float(np.max(data)) if "std" in stats: stat_result["std"] = float(np.std(data)) results.append(stat_result) return { "status": "success", "message": "Zonal statistics computed successfully.", "results": results } except Exception as e: logger.error(f"Error in zonal_statistics: {str(e)}") return {"status": "error", "message": str(e)}
  • MCP resource handler that lists all available rasterio operations, including 'zonal_statistics', 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" ] }
  • Function signature with type annotations and docstring defining input parameters and return type for the zonal_statistics tool.
    def zonal_statistics(raster_path: str, vector_path: str, stats: list = None) -> Dict[str, Any]: """ Calculate statistics of raster values within polygons (zonal statistics). Args: raster_path: Path to the raster file. vector_path: Path to the vector file (polygons). stats: List of statistics to compute (e.g., ["mean", "min", "max", "std"]). Returns: Dictionary with status, message, and statistics per polygon. """

Other Tools

Related Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/mahdin75/gis-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server