Making a empty/template raster using rioxarray / rasterio in Python

79 Views Asked by At

I am currently trying to convert R code into Python. I am trying to make a 'template' raster file which I will then "reproject_match" many other rasters to in my workflow so that they all align.

I can do it in R using the terra package, but am unsure how to do so in python using the rioxarray package. I'm hoping someone might be able to help? Here is my R code:

# load lib
library("terra")

# Make an empty raster. By default is has extent of the earth and projection wgs84. Setting the resolution means the rows and cols are automatically calculated.
a <- rast(res = 1)

# Fill it with some random integer values
vals(a) <- as.integer(runif(nrow(a) * ncol(a), 1, 10))

# Write it out to file as an
writeRaster(a, "my_integer_rast.tif", wopt = list(datatype = "INT1U"))

I got this far then kind of got lost/confused and thought I would reach out for some help:

import xarray
import rioxarray

data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]  # Example data
coords = {'x': [0, target_res, target_res*2], 'y': [0, target_res, target_res*2]} 
ds = xr.Dataset({'data': (['y', 'x'], data)}, coords=coords)
ds.rio.set_spatial_dims(x_dim='x', y_dim='y', inplace=True)
ds.rio.write_crs("EPSG:4326", inplace=True)
ds.rio.write_transform(inplace=True)
with rasterio.open(
        "test.tif, 'w',
        driver='GTiff',
        transform = ds.rio.transform(),
        crs=ds.rio.crs,
        dtype=rasterio.float32,
        #nodata=ds.rio.nodata,
        count=1, 
        width=ref.rio.width,
        
        height=ref.rio.height) as dst:
    dst.write(ds.values)
0

There are 0 best solutions below