sertit.rasters.to_np

to_np(xds: xarray.core.dataarray.DataArray, dtype: Optional[Any] = None) numpy.ndarray[source]

Convert the xarray to a np.ndarray with the correct nodata encoded.

This is particularly useful when reading with masked=True.

>>> raster_path = "path\to\mask.tif"  # Classified raster in np.uint8 with nodata = 255
>>> # We read with masked=True so the data is converted to float
>>> xds = read(raster_path)
<xarray.DataArray 'path/to/mask.tif' (band: 1, y: 322, x: 464)>
[149408 values with dtype=float64]
Coordinates:
  * band         (band) int32 1
  * y            (y) float64 4.798e+06 4.798e+06 ... 4.788e+06 4.788e+06
  * x            (x) float64 5.411e+05 5.411e+05 ... 5.549e+05 5.55e+05
    spatial_ref  int32 0
>>> to_np(xds)  # Getting back np.uint8 and encoded nodata
array([[[255, 255, 255, ..., 255, 255, 255],
    [255, 255, 255, ..., 255, 255, 255],
    [255, 255, 255, ..., 255, 255, 255],
    ...,
    [255, 255, 255, ...,   1, 255, 255],
    [255, 255, 255, ...,   1, 255, 255],
    [255, 255, 255, ...,   1, 255, 255]]], dtype=uint8)

True
Parameters
  • xds (xarray.DataArray) – xarray.DataArray to convert

  • dtype (Any) – Dtype to convert to. If None, using the origin dtype if existing or its current dtype.

Returns: