Skip to content

Rasterio Library

siapy.entities.images.rasterio_lib

RasterioLibImage dataclass

RasterioLibImage(file: XarrayType)

Bases: ImageBase

PARAMETER DESCRIPTION
file

An xarray DataArray containing the raster data loaded via rioxarray.

TYPE: XarrayType

Source code in siapy/entities/images/rasterio_lib.py
24
25
26
27
28
29
30
def __init__(self, file: "XarrayType"):
    """Initialize a RasterioLibImage wrapper around an xarray DataArray.

    Args:
        file: An xarray DataArray containing the raster data loaded via rioxarray.
    """
    self._file = file

file property

file: XarrayType

Get the underlying xarray DataArray.

RETURNS DESCRIPTION
XarrayType

The wrapped xarray DataArray containing the raster data.

filepath property

filepath: Path

Get the file path of the raster image.

RETURNS DESCRIPTION
Path

A Path object representing the location of the raster file, extracted from the xarray encoding information.

metadata property

metadata: dict[str, Any]

Get the raster metadata from the xarray attributes.

RETURNS DESCRIPTION
dict[str, Any]

A dictionary containing raster metadata such as coordinate reference system, geotransform information, and other properties stored in xarray attrs.

shape property

shape: tuple[int, int, int]

Get the dimensions of the raster image.

RETURNS DESCRIPTION
tuple[int, int, int]

A tuple (height, width, bands) representing the image dimensions. Note that rioxarray uses (band, y, x) ordering internally, which is converted to the standard (y, x, band) format.

rows property

rows: int

Get the number of rows (height) in the image.

RETURNS DESCRIPTION
int

The number of rows in the raster image.

cols property

cols: int

Get the number of columns (width) in the image.

RETURNS DESCRIPTION
int

The number of columns in the raster image.

bands property

bands: int

Get the number of bands in the raster image.

RETURNS DESCRIPTION
int

The number of bands (channels) in the raster image.

default_bands property

default_bands: list[int]

Get the default band indices for RGB display.

RETURNS DESCRIPTION
list[int]

A list of 1-based band indices commonly used for RGB display. For satellite imagery, this typically returns [1, 2, 3] for images with 3+ bands, or [1, 2] for images with 2 bands, etc. Note that these are 1-based indices as used by rioxarray.

Note

Returns 1-based band indices (not 0-based) to match rioxarray's band coordinate system. This differs from numpy array indexing which is 0-based.

wavelengths property

wavelengths: list[float]

Get the band values, which may represent wavelengths or band numbers.

RETURNS DESCRIPTION
list[float]

A numpy array of band coordinate values from the xarray DataArray. For spectral data, these may represent wavelengths in nanometers; for other raster data, these are typically just sequential band numbers (1, 2, 3, etc.).

Note

The interpretation of these values depends on the source data. Check the metadata to determine if these represent actual wavelengths or just band identifiers.

camera_id property

camera_id: str

Get the camera or sensor identifier from metadata.

RETURNS DESCRIPTION
str

A string identifying the camera or sensor used to capture the image. Returns empty string if no camera_id is found in the metadata.

Note

This property looks for 'camera_id' in the metadata, which is not a standard raster metadata field and may not be present in most files.

open classmethod

open(filepath: str | Path) -> RasterioLibImage

Open a raster image using the rioxarray library.

PARAMETER DESCRIPTION
filepath

Path to the raster file (supports formats like GeoTIFF, NetCDF, HDF5, etc.).

TYPE: str | Path

RETURNS DESCRIPTION
RasterioLibImage

A RasterioLibImage instance wrapping the opened raster data.

RAISES DESCRIPTION
InvalidFilepathError

If the file path does not exist.

InvalidInputError

If the file cannot be opened (e.g., unsupported format, corrupted file) or if rioxarray returns a list instead of DataArray/Dataset.

Example
# Open a GeoTIFF file
image = RasterioLibImage.open("satellite_image.tif")

# Open a NetCDF file
image = RasterioLibImage.open("climate_data.nc")
Note

The method uses rioxarray.open_rasterio() internally, which supports most GDAL-compatible raster formats. Some formats may require additional dependencies.

Source code in siapy/entities/images/rasterio_lib.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
@classmethod
def open(cls, filepath: str | Path) -> "RasterioLibImage":
    """Open a raster image using the rioxarray library.

    Args:
        filepath: Path to the raster file (supports formats like GeoTIFF, NetCDF, HDF5, etc.).

    Returns:
        A RasterioLibImage instance wrapping the opened raster data.

    Raises:
        InvalidFilepathError: If the file path does not exist.
        InvalidInputError: If the file cannot be opened (e.g., unsupported format,
                         corrupted file) or if rioxarray returns a list instead of
                         DataArray/Dataset.

    Example:
        ```python
        # Open a GeoTIFF file
        image = RasterioLibImage.open("satellite_image.tif")

        # Open a NetCDF file
        image = RasterioLibImage.open("climate_data.nc")
        ```

    Note:
        The method uses rioxarray.open_rasterio() internally, which supports most
        GDAL-compatible raster formats. Some formats may require additional dependencies.
    """
    filepath = Path(filepath)
    if not filepath.exists():
        raise InvalidFilepathError(filepath)

    try:
        raster = rioxarray.open_rasterio(filepath)
    except Exception as e:
        raise InvalidInputError({"filepath": str(filepath)}, f"Failed to open raster file: {e}") from e

    if isinstance(raster, list):
        raise InvalidInputError({"file_type": type(raster).__name__}, "Expected DataArray or Dataset, got list")

    return cls(raster)

to_display

to_display(equalize: bool = True) -> Image

Convert the image to a PIL Image for display purposes.

PARAMETER DESCRIPTION
equalize

Whether to apply histogram equalization to enhance contrast. Defaults to True.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
Image

A PIL Image object suitable for display, created from the default RGB bands with values scaled to 0-255 range and optional histogram equalization.

Example
# Display the image with default settings
pil_image = raster_image.to_display()
pil_image.show()

# Display without histogram equalization
pil_image = raster_image.to_display(equalize=False)
Source code in siapy/entities/images/rasterio_lib.py
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
def to_display(self, equalize: bool = True) -> Image.Image:
    """Convert the image to a PIL Image for display purposes.

    Args:
        equalize: Whether to apply histogram equalization to enhance contrast. Defaults to True.

    Returns:
        A PIL Image object suitable for display, created from the default RGB bands with values scaled to 0-255 range and optional histogram equalization.

    Example:
        ```python
        # Display the image with default settings
        pil_image = raster_image.to_display()
        pil_image.show()

        # Display without histogram equalization
        pil_image = raster_image.to_display(equalize=False)
        ```
    """
    bands_data = self.file.sel(band=self.default_bands)
    image_3ch = bands_data.transpose("y", "x", "band").values
    image_3ch_clean = np.nan_to_num(np.asarray(image_3ch))
    min_val = np.nanmin(image_3ch_clean)
    max_val = np.nanmax(image_3ch_clean)

    image_scaled = ((image_3ch_clean - min_val) * (255.0 / (max_val - min_val))).astype(np.uint8)

    image = Image.fromarray(image_scaled)
    if equalize:
        image = ImageOps.equalize(image)
    return image

to_numpy

to_numpy(
    nan_value: float | None = None,
) -> NDArray[floating[Any]]

Convert the image to a numpy array.

PARAMETER DESCRIPTION
nan_value

Optional value to replace NaN values with. If None, NaN values are preserved.

TYPE: float | None DEFAULT: None

RETURNS DESCRIPTION
NDArray[floating[Any]]

A 3D numpy array with shape (height, width, bands) containing the raster data. The array is transposed from rioxarray's native (band, y, x) to (y, x, band) format.

Example
# Get the raw data with NaN values preserved
data = raster_image.to_numpy()

# Replace NaN values with zero
data = raster_image.to_numpy(nan_value=0.0)
Source code in siapy/entities/images/rasterio_lib.py
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
def to_numpy(self, nan_value: float | None = None) -> NDArray[np.floating[Any]]:
    """Convert the image to a numpy array.

    Args:
        nan_value: Optional value to replace NaN values with. If None, NaN values are preserved.

    Returns:
        A 3D numpy array with shape (height, width, bands) containing the raster data. The array is transposed from rioxarray's native (band, y, x) to (y, x, band) format.

    Example:
        ```python
        # Get the raw data with NaN values preserved
        data = raster_image.to_numpy()

        # Replace NaN values with zero
        data = raster_image.to_numpy(nan_value=0.0)
        ```
    """
    image = np.asarray(self.file.transpose("y", "x", "band").values)
    if nan_value is not None:
        image = np.nan_to_num(image, nan=nan_value)
    return image

to_xarray

to_xarray() -> XarrayType

Convert the image to an xarray DataArray.

RETURNS DESCRIPTION
XarrayType

The underlying xarray DataArray with all original coordinates, dimensions, and metadata preserved.

Example
# Access the xarray representation
xr_data = raster_image.to_xarray()

# Use xarray functionality
subset = xr_data.sel(x=slice(100, 200), y=slice(100, 200))
Source code in siapy/entities/images/rasterio_lib.py
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
def to_xarray(self) -> "XarrayType":
    """Convert the image to an xarray DataArray.

    Returns:
        The underlying xarray DataArray with all original coordinates, dimensions, and metadata preserved.

    Example:
        ```python
        # Access the xarray representation
        xr_data = raster_image.to_xarray()

        # Use xarray functionality
        subset = xr_data.sel(x=slice(100, 200), y=slice(100, 200))
        ```
    """
    return self.file