1

I created several velocity maps from .nc files through gdal.Translate. Each .nc file is organized in several bands, I am only interested in 1: velocities. gdal.Translate allows me to select only the velocities and cut them to my area of interest.

I would like to calculate the velocities' mean on a specific time-period, and for that I intended to open on Python my cut files (.vrt). However, when I open them in Python they are all "NoneType", while when I open them in QGIS I can see the velocities.

To calculate the means, my idea was to use:

myarray = np.array(ds.ReadAsArray())

Where ds is my cut velocity map. Then in a loop, I stack the myarray in a 3D matrix, and calculate the mean over the time axis.

Do you know if there is a better way to do it? Also, why do I have only NoneType files? I am new to gdal, and I am surprised QGIS can recognize my cut velocities maps while Python sees only a NoneType. I could calculate the mean through Raster Calculator in QGIS, but I want to automatize this task.

Ps: this is how I open my .nc file, cut and select the velocities only:

ds = gdal.Open("NETCDF:{0}:{1}".format(netcdf_name, layer_name))
gdal.Translate('output/' + Name + '.vrt', ds, projWin = [-3353315, 380000, -3257001, 260460])
0

The Python package osgeo.gdal is not really "Pythonic", so there are several quirks and gotchas to be aware of.

The NoneType returned from Open means that the file could not be opened. Here's a quick demo:

from osgeo import gdal

ds = gdal.Open("NETCDF:file.nc:velocity")
# you may see the following message in a console:
# ERROR 4: `NETCDF:file.nc:velocity' does not exist in the file system, and is not recognized as a supported dataset name.
print(ds)  # None

gdal.UseExceptions()
ds = gdal.Open("NETCDF:file.nc:velocity")
RuntimeError: `NETCDF:file.nc:velocity' does not exist in the file system, and is not recognized as a supported dataset name.

By setting gdal.UseExceptions(), the above throws RuntimeError if the dataset cannot be opened.

An alternative GDAL-based package is rasterio.

import rasterio

with rasterio.open("NETCDF:file.nc:velocity", "r") as ds:
    ar = ds.read()

which will usually raise useful errors, where appropriate.


As for the other part of the question to process netCDF files, I've found NCO tools to be the best. They are not easy to use, but there is extensive documentation and examples on how to use them. They can be used to calculate averages of time-varying variables in an efficient manner. The result could possibly be viewed directly or post-processed and re-projected to a different GIS format.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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