2121
2222from rasterix .odc_compat import BoundingBox , bbox_intersection , bbox_union , maybe_int , snap_grid
2323from rasterix .rioxarray_compat import guess_dims
24+ from rasterix .utils import get_affine
2425
2526T_Xarray = TypeVar ("T_Xarray" , "DataArray" , "Dataset" )
2627
3536def assign_index (obj : T_Xarray , * , x_dim : str | None = None , y_dim : str | None = None ) -> T_Xarray :
3637 """Assign a RasterIndex to an Xarray DataArray or Dataset.
3738
39+ By default, the affine transform is guessed by first looking for a ``GeoTransform`` attribute
40+ on a ``"spatial_ref"`` variable. If not present, then the affine is determine from 1D coordinate
41+ variables named ``x_dim`` and ``y_dim`` provided to this function.
42+
3843 Parameters
3944 ----------
4045 obj : xarray.DataArray or xarray.Dataset
@@ -52,19 +57,19 @@ def assign_index(obj: T_Xarray, *, x_dim: str | None = None, y_dim: str | None =
5257 Examples
5358 --------
5459 >>> import xarray as xr
55- >>> import rioxarray # Required for rio accessor
60+ >>> import rioxarray # Required for reading TIFF
5661 >>> da = xr.open_dataset("path/to/raster.tif", engine="rasterio")
5762 >>> indexed_da = assign_index(da)
5863 """
59- import rioxarray # noqa
60-
6164 if x_dim is None or y_dim is None :
6265 guessed_x , guessed_y = guess_dims (obj )
6366 x_dim = x_dim or guessed_x
6467 y_dim = y_dim or guessed_y
6568
69+ affine = get_affine (obj , x_dim = x_dim , y_dim = y_dim )
70+
6671 index = RasterIndex .from_transform (
67- obj . rio . transform () , width = obj .sizes [x_dim ], height = obj .sizes [y_dim ], x_dim = x_dim , y_dim = y_dim
72+ affine , width = obj .sizes [x_dim ], height = obj .sizes [y_dim ], x_dim = x_dim , y_dim = y_dim , crs = obj . proj . crs
6873 )
6974 coords = Coordinates .from_xindex (index )
7075 return obj .assign_coords (coords )
0 commit comments