Search code examples
pythoncompressionrasterpython-xarray

How to compress the output of Python Module xarray rio.to_raster


I am utilizing geocube to rasterize polygon data and then exporting that raster as a tiff. The output is an xarray and I am using the rio.to_raster method to save it as a tiff file. My issue is that the output is uncompressed and generally larger than expected. I was wondering if anyone knew how to get the output of this method into a compressed format? I know rasterio and other packages can set the parameter "compress=" to do this, but I am not seeing this option with rio.to_raster. Any insight would be great!


Solution

  • compress='zstd' works fine:

    import os
    
    import rioxarray as rio
    import xarray as xr
    
    
    def size(path):
        return f"{os.path.getsize(path)/2**20:.4f}Mo"
    
    
    ds = xr.tutorial.open_dataset("air_temperature")
    ds = ds.isel(time=999)
    ds.rio.to_raster('/tmp/dataset1.tif')
    ds.rio.to_raster('/tmp/dataset2.tif', compress='zstd')
    
    size("/tmp/dataset1.tif"), size("/tmp/dataset2.tif")
    >>> ('0.0064Mo', '0.0035Mo')