Topics

Is it possible to create a rasterio object without exporting a file?


Leah Wasser
 

Hi All,
I am running into a consistent workflow issue. i'd like to crop a numpy array. I have metadata dict and a numpy array but then want to crop it. is there a way to crop a numpy array to a new extent (using rio.mask()) using just the meta file rather than needing to export the array and reimport it to instantiate a rasterio object and create a new numpy array and associated meta?

Perhaps i'm missing something very basic!!
thank you
Leah


Alan Snow
 

Hi Leah,

Here is an example of what you want to do:
https://github.com/corteva/geocube/blob/582ea0c2f3f0ba91326de098b75412e5033bee21/geocube/xarray_extensions/rioxarray.py#L617

It uses xarray, but the concept is the same.

Hopefully this helps,
Alan


Leah Wasser
 

Hey Alan,
this is super helpful.

digging through your code. how does this line work:

cropped_ds = self._obj.where(clip_mask_xray, drop=True).astype(self._obj.dtype)

i'm familiar with numpy.where however the drop=True is not an argument i'm familiar with.
thank you so much!
Leah


Alan Snow
 

Hi Leah,

So, this project uses xarray which has many similar operations to numpy, but with slight differences.
In the case of the example, the `drop=True` is an option they provide that is described here:
http://xarray.pydata.org/en/stable/generated/xarray.DataArray.where.html

For numpy, it is not as simple if I remember correctly for a 2D array. An example of doing this is here:
https://github.com/CI-WATER/gsshapy/blob/00fd4af0fd65f1614d75a52fe950a04fb0867f4c/gsshapy/grid/grid_to_gssha.py#L616-L631

Hopefully this is helpful and gets you in the right direction.

Best,
Alan


Alan Snow
 

Hi Leah,

If you would like to try the rioxarray as an xarray extension, it is now available on pypi.

An example of what you would like to do is here:
https://corteva.github.io/rioxarray/html/examples/clip_geom.html

Best,
Alan


Leah Wasser
 

Thank you, Alan!
that example is very helpful. i'll dig into this a bit deeper. xarray seems like a powerful tool for raster processing.
i've wanted to plan with it a bit more regardless.
Leah