1

I am trying to extract some statistics from all rasters in a directory and saving them into a CSV file using Python. The script works, but the results for all percentile values are always nan. Any clue why this is happening?

import os
from osgeo import gdal
import csv
import numpy as np
import argparse


def getStatsFromRaster(input_tif_dir, band_num, output_file):

    # Get a list of all tif files in the input folder
    tif_files = [f for f in os.listdir(input_tif_dir) if f.endswith('.tif')]
    band_int = int(band_num)

    # Initialize a list to hold the results
    results = []

    # Loop through each tif file
    for tif_file in tif_files:
        # Open the raster file
        ds = gdal.Open(os.path.join(input_tif_dir, tif_file))

        # Get the raster band
        band = ds.GetRasterBand(band_int)
        nodata = band.GetNoDataValue()

        if nodata is None:
            print('Nodata value is not present')
        # Check if nodata is present
        else:
            print('Nodata value is:', nodata)

        # Get the statistics for the band
        stats = band.GetStatistics(0, 1)

        # Get the percentiles for the band
        data = band.ReadAsArray()
        # data[data == nodata] = np.nan
        p1, p5, p25, p50, p75, p95, p99 = np.percentile(data, [1, 5, 25, 50, 75, 95, 99])

        # Add the results to the list
        results.append([tif_file] + stats + [p1, p5, p25, p50, p75, p95, p99])

    # Write the results to a CSV file
    with open(output_file, 'w', newline='') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow(
            ['File Name', 'Minimum', 'Maximum', 'Mean', 'Standard Deviation', 'P1', 'P5', 'P25', 'P50', 'P75', 'P95',
             'P99'])
        writer.writerows(results)

    print('Results written to', output_file)


if __name__ == "__main__":
    aparser = argparse.ArgumentParser(
        description='It gets the statistics of a raster file'
    )
    aparser.add_argument(
        '--input-tif-dir',
        default=None
    )
    aparser.add_argument(
        '--band',
        default=None
    )
    aparser.add_argument(
        '--output-file',
        default=None
    )

    args = aparser.parse_args()
    getStatsFromRaster(args.input_tif_dir, args.band, args.output_file)

1 Answer 1

2

Changing np.percentile by np.nanpercentile made the script work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.