GDAL-RASTER-ZONAL-STATS(1)

NAME
gdal-raster-zonal-stats - Compute raster zonal statistics.

Added in version 3.12.

SYNOPSIS

    Usage: gdal raster zonal-stats [OPTIONS] <INPUT> <OUTPUT>
    Calculate raster zonal statistics
    Positional arguments:
      -i, --input <INPUT>                                  Input raster datasets [required] [not available in pipelines]
      -o, --output <OUTPUT>                                Output vector dataset [required] [not available in pipelines]
    Common Options:
      -h, --help                                           Display help message and exit
      --json-usage                                         Display usage as JSON document and exit
      --config <KEY>=<VALUE>                               Configuration option [may be repeated]
      -q, --quiet                                          Quiet mode (no progress bar or warning message) [not available in pipelines]
    Options:
      -f, --of, --format, --output-format <OUTPUT-FORMAT>  Output format ("GDALG" allowed) [not available in pipelines]
      --co, --creation-option <KEY>=<VALUE>                Creation option [may be repeated] [not available in pipelines]
      --lco, --layer-creation-option <KEY>=<VALUE>         Layer creation option [may be repeated] [not available in pipelines]
      --overwrite                                          Whether overwriting existing output dataset is allowed [not available in pipelines]
      --update                                             Whether to open existing dataset in update mode [not available in pipelines]
      --overwrite-layer                                    Whether overwriting existing output layer is allowed [not available in pipelines]
      --append                                             Whether appending to existing layer is allowed [not available in pipelines]
                                                           Mutually exclusive with --upsert
      --output-layer <OUTPUT-LAYER>                        Output layer name [not available in pipelines]
      --skip-errors                                        Skip errors when writing features [not available in pipelines]
      -b, --band <BAND>                                    Input band(s) (1-based index) [may be repeated]
      --zones <ZONES>                                      Dataset containing zone definitions [required]
      --zones-band <ZONES-BAND>                            Band from which zones should be read
                                                           Mutually exclusive with --zones-layer
      --zones-layer <ZONES-LAYER>                          Layer from which zones should be read
                                                           Mutually exclusive with --zones-band
      --weights <WEIGHTS>                                  Weighting raster dataset
      --weights-band <WEIGHTS-BAND>                        Band from which weights should be read (default: 1)
      --pixels <PIXELS>                                    Method to determine which pixels are included in stat calculation.. PIXELS=default|fractional|all-touched
      --stat <STAT>                                        Statistic(s) to compute for each zone. STAT=center_x|center_y|count|coverage|frac|max|max_center_x|max_center_y|mean|median|min|minority|min_center_x|min_center_y|mode|stdev|sum|unique|values|variance|variety|weighted_mean|weighted_stdev|weighted_sum|weighted_variance|weights [may be repeated] [required]
      --include-field <INCLUDE-FIELD>                      Fields from polygon zones to include in output [may be repeated]
      --include-geom                                       Include polygon zone geometry in the output
      --strategy <STRATEGY>                                For polygon zones, whether to iterate over input features or raster chunks. STRATEGY=feature|raster (default: feature)
      --chunk-size <CHUNK-SIZE>                            Maximum size of raster chunks read into memory (default: 5%)
    Advanced Options:
      --if, --input-format <INPUT-FORMAT>                  Input formats [may be repeated] [not available in pipelines]
      --oo, --open-option <KEY>=<VALUE>                    Open options [may be repeated] [not available in pipelines]
      --output-oo, --output-open-option <KEY>=<VALUE>      Output open options [may be repeated] [not available in pipelines]
      --upsert                                             Upsert features (implies 'append') [not available in pipelines]
                                                           Mutually exclusive with --append

DESCRIPTION

gdal raster zonal-stats computes raster zonal statistics -- a summary of pixel values within zones specified either polygon features or a categorical raster. [image] Mean elevation calculated for each polygon from an elevation raster..UNINDENT

A weighting raster may be provided in addition to the source raster, allowing calculation of statistics such as population-weighted mean weather conditions.

All inputs should be provided in the same spatial reference system. If input rasters use different resolutions they will be resampled to a consistent resolution using average resampling. However, no reprojection is performed.

  Pixel inclusion and weighting

When zones are defined using polygons, three methods are available for determining which pixels to include in the calculation. By default, the geometries are rasterized using default parameters, and pixels included in the rasterization are used in the calculation with equal weighting. By using --pixels all-touched, all pixels touched by the polygon are used in the calculation, again with equal weighting. If using --pixels fractional, the fraction of each pixel that is covered by the polygon is computed, and pixels are weighted according to this fraction. This option requires GDAL be built against version 3.14 or later of the GEOS library.

  Supported stats
Name | Description
center_x | Array with cell center x-coordinate for each cell that intersects the polygon. Each cell center may or may not be inside the polygon.
center_y | Array with cell center y-coordinate for each cell that intersects the polygon. Each cell center may or may not be inside the polygon.
count | Sum of all cell coverage fractions.
coverage | Array with coverage fraction of each cell that intersects the polygon
frac | Fraction of covered cells that are occupied by each distinct raster value, as provided by unique.
max | Maximum value of cells that intersect the polygon, not taking coverage fractions or weighting raster values into account.
max_center_x | Cell center x-coordinate for the cell containing the maximum value intersected by the polygon. The center of this cell may or may not be inside the polygon.
max_center_y | Cell center y-coordinate for the cell containing the maximum value intersected by the polygon. The center of this cell may or may not be inside the polygon.
mean | Mean value of cells that intersect the polygon, weighted by the percent of each cell that is covered.
min | Minimum value of cells that intersect the polygon, not taking coverage fractions or weighting raster values into account.
min_center_x | Cell center x-coordinate for the cell containing the minimum value intersected by the polygon. The center of this cell may or may not be inside the polygon.
min_center_y | Cell center y-coordinate for the cell containing the minimum value intersected by the polygon. The center of this cell may or may not be inside the polygon.
minority | The raster value occupying the least number of cells, taking into account cell coverage fractions but not weighting raster values.
mode | The raster value occupying the greatest number of cells, taking into account cell coverage fractions but not weighting raster values.
stdev | Population standard deviation of cell values that intersect the polygon, taking into account coverage fraction.
sum | Sum of values of raster cells that intersect the polygon, with each raster value weighted by its coverage fraction.
unique | Array of unique raster values for cells that intersect the polygon
values | Array of raster values for each cell that intersects the polygon
variance | Population variance of cell values that intersect the polygon, taking into account coverage fraction.
variety | The number of distinct raster values in cells wholly or partially covered by the polygon.
weighted_frac | Fraction of covered cells that are occupied by each distinct raster value, weighted by the value of a second weighting raster. Order corresponds to values returned by unique.
weighted_mean | Mean value of cells that intersect the polygon, weighted by the product over the coverage fraction and the weighting raster.
weighted_stdev | Weighted version of stdev.
weighted_variance | Weighted version of variance
weights | Array of weight values for each cell that intersects the polygon

This algorithm can be part of a gdal pipeline.

PROGRAM-SPECIFIC OPTIONS

--band, -b <BAND>
    Input band(s) to be processed.

--chunk-size <MEMORY>
    Defines the maximum size of raster chunks to read. May be expressed as either an amount of memory (500 MB, 2 GB, etc.) or as a percentage of available RAM (e.g. 10%).

--include-field <INCLUDE-FIELD>
    Specifies one or more fields from the zones to be copied to the output. Only available when vector zones are used. Since GDAL 3.13, the special values "ALL" and "NONE" can be used.

--include-geom
    Include the zone geometry in the output feature. Only available when vector zones are used.

    Added in version 3.13.

--pixels <PIXELS>
    Method to determine which pixels should be included in the calculation: default, all-touched, or fractional.

--stat <STAT>
    Specifies one or more of the Supported stats to compute for each zone.

--strategy <STRATEGY>
    Specifies the the processing strategy (raster or feature), when vector zones are used. In the default strategy (--strategy feature), GDAL will iterate over the features in the zone dataset, read the corresponding pixels from the raster, and write the statistics for that feature. This avoids the need to read the entire feature dataset into memory at once, but may cause the same pixels to be read multiple times if the polygon features are large or not ordered spatially. If --strategy raster is used, GDAL will iterate over chunks of the raster dataset, find corresponding polygon zones, and update the statistics for those features. (The size of the raster chunks can be controlled using :option:--chunk-size.) This ensures that raster pixels are only read once, but may cause the same features to be processed multiple times.

--weights <WEIGHTS>
    Optional path to a dataset to use for weighting.

--weights-band <WEIGHTS-BAND>
    Specifies the raster band from which weights can be read.

--zones <ZONES>
    The path to a dataset that defines the zones. If the dataset has more than 1 raster band or feature layer, --zones-band or --zones-layer must be specified.

--zones-band <ZONES-BAND>
    Specifies the raster band from which zones can be read.

--zones-layer <ZONES-LAYER>
    Specifies the feature layer from which zones can be read.

STANDARD OPTIONS

--append
    Whether appending features to existing layer(s) is allowed. This also creates the output dataset if it does not exist yet.

--co, --creation-option <NAME>=<VALUE>
    Many formats have one or more optional dataset creation options that can be used to control particulars about the file created. For instance, the GeoPackage driver supports creation options to control the version.

    May be repeated.

    The dataset creation options available vary by format driver, and some simple formats have no creation options at all. A list of options supported for a format can be listed with the --formats command line option but the documentation for the format is the definitive source of information on driver creation options. See Vector drivers format specific documentation for legal creation options for each format.

    Note that dataset creation options are different from layer creation options.

--if, --input-format <format>
    Format/driver name to be attempted to open the input file(s). It is generally not necessary to specify it, but it can be used to skip automatic driver detection, when it fails to select the appropriate driver. This option can be repeated several times to specify several candidate drivers. Note that it does not force those drivers to open the dataset. In particular, some drivers have requirements on file extensions.

    May be repeated.

--lco, --layer-creation-option <NAME>=<VALUE>
    Many formats have one or more optional layer creation options that can be used to control particulars about the layer created. For instance, the GeoPackage driver supports layer creation options to control the feature identifier or geometry column name, setting the identifier or description, etc.

    May be repeated.

    The layer creation options available vary by format driver, and some simple formats have no layer creation options at all. A list of options supported for a format can be listed with the --formats command line option but the documentation for the format is the definitive source of information on driver creation options. See Vector drivers format specific documentation for legal creation options for each format.

    Note that layer creation options are different from dataset creation options.

--oo, --open-option <NAME>=<VALUE>
    Dataset open option (format specific).

    May be repeated.

-f, --of, --format, --output-format <OUTPUT-FORMAT>
    Which output vector format to use. Allowed values may be given by gdal --formats | grep vector | grep rw | sort

--output-layer <NAME>
    Specifies the name of the layer to which features will be written. If not specified, output layer names will be the same as input layer names.

--output-open-option, --output-oo <NAME>=<VALUE>
    Added in version 3.12.

    Dataset open option for output dataset (format specific).

    May be repeated.

--overwrite
    Allow program to overwrite existing target file or dataset. Otherwise, by default, gdal errors out if the target file or dataset already exists.

--overwrite-layer
    Whether overwriting the existing output vector layer is allowed.

--skip-errors
    Added in version 3.12.

    Whether failures to write feature(s) should be ignored. Note that this option sets the size of the transaction unit to one feature at a time, which may cause severe slowdown when inserting into databases.

--update
    Whether to open an existing output dataset in update mode.

--upsert
    Added in version 3.12.

    Variant of --append where the OGRLayer::UpsertFeature() operation is used to insert or update features instead of appending with OGRLayer::CreateFeature().

    This is currently implemented only in a few drivers: GPKG -- GeoPackage vector, Elasticsearch: Geographically Encoded Objects for Elasticsearch and MongoDBv3 (drivers that implement upsert expose the GDAL_DCAP_UPSERT capability).

    The upsert operation uses the FID of the input feature, when it is set (and the FID column name is not the empty string), as the key to update existing features. It is crucial to make sure that the FID in the source and target layers are consistent.

    For the GPKG driver, it is also possible to upsert features whose FID is unset or non-significant (the --unset-fid option of gdal vector edit can be used to ignore the FID from the source feature), when there is a UNIQUE column that is not the integer primary key.

RETURN STATUS CODE

The program returns status code 0 in case of success, and non-zero in case of error (non-blocking errors emitted as warnings are considered as a successful execution).

EXAMPLES

  Example 1: Summarize mean elevation within 200m of points of interest

Using a nested pipeline for the zone dataset

      gdal pipeline read dem.tif ! \
          zonal-stats \
            --zones [ read points.geojson ! buffer 200 ] \
            --stat mean ! \
          write \
            --output-format CSV \
            --output /vsistdout/
    or, using the zone vector dataset as the piped dataset using the ``_PIPE_`` placeholder dataset name:

    gdal pipeline read points.geojson ! \
        buffer 200 ! \
        zonal-stats \
          --input dem.tif
          --zones _PIPE_ \
          --stat mean ! \
        write \
          --output-format CSV \
          --output /vsistdout/

  Example 2: Create a layer with the highest points in each watershed

    gdal pipeline read dem.tif !
        zonal-stats \
          --zones watersheds.shp \
          --stat max_center_x \
          --stat max_center_y ! \
        make-point \
          --x max_center_x \
          --y max_center_y \
          --output-crs EPSG:4326 ! \
        write out.geojson

AUTHOR
Dan Baston <dbaston@gmail.com>

COPYRIGHT
1998-2026