Search code examples
rastergdalnetcdfqgis

QGIS gdal_contour not respecting scale_factor/offset for netCDF


I am working with some netCDF files and want to import netCDF parameter's data as a Raster and build a contour layer for it. I am using gdal_contour for this.

When I import the netCDF and choose a parameter (water_temp) in QGIS, the raster is loaded into the map with no problem and displays values in the range of roughly 4 degC to 31.25 degC.

However, when I use gdal_contour to make a contour layer for it, the values are in the range of -15944 to 11250. It certainly doesn't help that among other issues, it takes forever to generate the layer because I'm specifying an interval of 1.0 and the value range is far larger than the expected temperatures for Celsius.

From what I can tell, it looks like perhaps gdal_contour either isn't respecting the raster band's offset and scale_factor or has no knowledge of it. I understand that the netCDF is storing the temperature values as integers instead of floats to optimize file size, but I'm a bit confused by why QGIS can understand the offset when reading the netCDF into a raster layer, but not when generating a contour layer.

Am I missing something, or is there perhaps a caveat to using gdal_contour of which I'm unaware?


The command I am using to generate the conotur layer is:

gdal_contour -b 1 -a water_temp -i 1.0 -snodata -30000.0 -f "ESRI Shapefile" NETCDF:"C:/path/to/input/netcdf/INPUT.nc":water_temp C:/path/to/output/layer/OUTPUT.shp

The scale_factor, offset, and associated metadata for the band are:

  • add_offset=20
  • missing_value=-30000
  • NETCDF_VARNAME=water_temp
  • scale_factor=0.001
  • STATISTICS_MAXIMUM=11250
  • STATISTICS_MEAN=5475.011083141
  • STATISTICS_MINIMUM=-15944
  • STATISTICS_STDDEV=5863.9957197805
  • units=degC
  • _FillValue=-30000

Solution

  • This question was answered here.

    TLDR; Convert the netCDF to a GeoTIFF first using gdal_translate with the -unscale option to get GDAL to unpack the values, then perform gdal_contour on the GeoTIFF to get a contour layer with the correctly unpacked values.

    However, one thing that may be important to note is the scaled/unscaled data types, which may have to be explicitly set for gdal_translate (using the -ot option) in order to not lose data precision during unscaling if the scaled data type is a smaller size than the unscaled data type.