Getting data from odo.resource(source) to odo.resource(target)

59 Views Asked by At

I'm trying to extend the odo library with functionality to convert a GDAL dataset (raster with spatial information) to a NetCDF file.

Reading in the gdal dataset goes fine. But in the creation stage of the netcdf I need some metadata of the gdal dataset (metadata that is not know yet when calling odo.odo(source,target) ). How could I achieve this?

a short version of my code so far:

import odo
from odo import resource, append
import gdal
import netCDF4 as nc4
import numpy as np

@resource.register('.+\.tif')
def resource_gdal(uri, **kwargs):
    ds = gdal.Open(uri)

    # metadata I need to transfer to netcdf
    b = ds.GetGeoTransform() #bbox, interval

   return ds


@resource.register('.+\.nc')
def resource_netcdf(uri, dshape=None, **kwargs):
    ds = nc4.Dataset(uri,'w')

    # create lat lon dimensions and variables
    ds.createDimension(lat, dshape[0].val)
    ds.createDimension(lon, dshape[1].val)
    lat = ds.createVariable('lat','f4', ('lat',))
    lon = ds.createVariable('lon','f4', ('lon',))

    # create a range from the **gdal metadata**
    lat_array = np.arange(dshape[0].val)*b[1]+b[0]
    lon_array = np.arange(dshape[1].val)*b[5]+b[3]

    # assign the range to the netcdf variable
    lat[:] = lat_array
    lon[:] = lon_array

    # create the variable which will hold the gdal data
    data = ds.createVariable('data', 'f4', ('lat', 'lon',))

   return data


@append.register(nc4.Variable, gdal.Dataset)
def append_gdal_to_nc4(tgt, src, **kwargs):
    arr = src.ReadAsArray()
    tgt[:] = arr

    return tgt

Thanks!

1

There are 1 best solutions below

0
On

I don't have much experience with odo, but from browsing the source code and docs it looks like resource_netcdf() should not be involved in translating gdal data to netcdf. Translating should be the job of a gdal_to_netcdf() function decorated by convert.register. In such a case, the gdal.Dataset object returned by resource_gdal would have all sufficient information (georeferencing, pixel size) to make a netcdf.