How to get GDAL to create statistics for GTiff in Python

You can use GetStatistics Method to get the stats.

eg.

stats =   ds.GetRasterBand(1).GetStatistics(0,1)

it will return (Min, Max, Mean, StdDev)

so the xml can be read:

<PAMDataset>
  <PAMRasterBand band="1">
    <Metadata>
      <MDI key="STATISTICS_MINIMUM">stats[0]</MDI>
      <MDI key="STATISTICS_MAXIMUM">stats[1]</MDI>
      <MDI key="STATISTICS_MEAN">stats[2]</MDI>
      <MDI key="STATISTICS_STDDEV">stats[3]</MDI>
    </Metadata>
  </PAMRasterBand>
</PAMDataset>

I dont know any pythonic way to create/manipulate xml file.But given the simplistic nature of the accompanying xml it should pretty trival to create one it with file I/O operations


If the statistics are already calculated and included in the file internally, gdalinfo -stats wont create a additional PAM statistics file(.aux.xml) for using GDAL 2.1.0. But its very easy to implement the .xml for your own. Here are some built-in Python modules explained to do that stuff. For myself i used The ElementTree XML API with the code below:

import xml.etree.cElementTree as ET

stats = file.GetRasterBand(band).GetStatistics(0,1)

pamDataset = ET.Element("PAMDataset")
pamRasterband = ET.SubElement(pamDataset, "PAMRasterBand", band="1")
metadata = ET.SubElement(pamRasterband, "Metadata")
ET.SubElement(metadata, "MDI", key = "STATISTICS_MAXIMUM").text = str(stats[1])
ET.SubElement(metadata, "MDI", key = "STATISTICS_MEAN").text = str(stats[2])
ET.SubElement(metadata, "MDI", key = "STATISTICS_MINIMUM").text = str(stats[0])
ET.SubElement(metadata, "MDI", key = "STATISTICS_STDDEV").text = str(stats[3])

tree = ET.ElementTree(pamDataset)
tree.write(destFilePath + ".aux.xml")

The result looks like:

<PAMDataset>
    <PAMRasterBand band="1">
        <Metadata>
            <MDI key="STATISTICS_MINIMUM">-40.65</MDI>
            <MDI key="STATISTICS_MEAN">10.2929293137</MDI>
            <MDI key="STATISTICS_MAXIMUM">45.050012207</MDI>
            <MDI key="STATISTICS_STDDEV">17.4892321447</MDI>
        </Metadata>
    </PAMRasterBand>
</PAMDataset>