Skip to content

Mock Image

siapy.entities.images.mock

MockImage

MockImage(array: NDArray[floating[Any]])

Bases: ImageBase

PARAMETER DESCRIPTION
array

A 3D numpy array with shape (height, width, bands) containing spectral data. The array will be automatically converted to float32 dtype.

TYPE: NDArray[floating[Any]]

RAISES DESCRIPTION
InvalidInputError

If the input array is not 3-dimensional.

Example
import numpy as np

# Create a synthetic spectral image
data = np.random.rand(100, 100, 10).astype(np.float32)
mock_image = MockImage(data)
Note

The input array is automatically converted to float32 dtype regardless of input type.

Source code in siapy/entities/images/mock.py
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
def __init__(
    self,
    array: NDArray[np.floating[Any]],
) -> None:
    """Initialize a MockImage from a numpy array.

    Args:
        array: A 3D numpy array with shape (height, width, bands) containing spectral data.
               The array will be automatically converted to float32 dtype.

    Raises:
        InvalidInputError: If the input array is not 3-dimensional.

    Example:
        ```python
        import numpy as np

        # Create a synthetic spectral image
        data = np.random.rand(100, 100, 10).astype(np.float32)
        mock_image = MockImage(data)
        ```

    Note:
        The input array is automatically converted to float32 dtype regardless of input type.
    """
    if len(array.shape) != 3:
        raise InvalidInputError(
            input_value=array.shape,
            message="Input array must be 3-dimensional (height, width, bands)",
        )

    self._array = array.astype(np.float32)

filepath property

filepath: Path

Get a placeholder file path for the mock image.

RETURNS DESCRIPTION
Path

An empty Path object since mock images are not associated with files.

metadata property

metadata: dict[str, Any]

Get empty metadata for the mock image.

RETURNS DESCRIPTION
dict[str, Any]

An empty dictionary since mock images have no associated metadata.

shape property

shape: tuple[int, int, int]

Get the dimensions of the mock image.

RETURNS DESCRIPTION
tuple[int, int, int]

A tuple (height, width, bands) representing the image dimensions extracted from the underlying numpy array shape.

bands property

bands: int

Get the number of spectral bands in the mock image.

RETURNS DESCRIPTION
int

The number of bands (third dimension) in the underlying array.

default_bands property

default_bands: list[int]

Get the default band indices for RGB display.

RETURNS DESCRIPTION
list[int]

A list of band indices for RGB display. If the image has 3 or more bands, returns [0, 1, 2]. Otherwise, returns indices for all available bands up to a maximum of 3.

wavelengths property

wavelengths: list[float]

Get placeholder wavelength values for the mock image.

RETURNS DESCRIPTION
list[float]

A list of sequential integers as float values, starting from 0, representing mock wavelengths for each band.

camera_id property

camera_id: str

Get a placeholder camera identifier for the mock image.

RETURNS DESCRIPTION
str

An empty string since mock images are not associated with real cameras.

open classmethod

open(array: NDArray[floating[Any]]) -> MockImage

Create a MockImage instance from a numpy array.

PARAMETER DESCRIPTION
array

A 3D numpy array with shape (height, width, bands) containing spectral data.

TYPE: NDArray[floating[Any]]

RETURNS DESCRIPTION
MockImage

A MockImage instance wrapping the provided array.

Example
import numpy as np

# Create synthetic data
data = np.random.rand(50, 50, 5).astype(np.float32)
mock_image = MockImage.open(data)
Source code in siapy/entities/images/mock.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
@classmethod
def open(cls, array: NDArray[np.floating[Any]]) -> "MockImage":
    """Create a MockImage instance from a numpy array.

    Args:
        array: A 3D numpy array with shape (height, width, bands) containing spectral data.

    Returns:
        A MockImage instance wrapping the provided array.

    Example:
        ```python
        import numpy as np

        # Create synthetic data
        data = np.random.rand(50, 50, 5).astype(np.float32)
        mock_image = MockImage.open(data)
        ```
    """
    return cls(array=array)

to_display

to_display(equalize: bool = True) -> Image

Convert the mock 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. For images with 3+ bands, uses the first 3 bands as RGB. For images with fewer bands, duplicates the first band across all RGB channels.

Example
# Display the mock image
pil_image = mock_image.to_display()
pil_image.show()

# Display without histogram equalization
pil_image = mock_image.to_display(equalize=False)
Note

NaN values in the image are automatically handled by replacing them with 0 during the scaling process. The method always returns an RGB image regardless of the number of input bands.

Source code in siapy/entities/images/mock.py
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
def to_display(self, equalize: bool = True) -> Image.Image:
    """Convert the mock 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. For images with 3+ bands, uses the first 3 bands as RGB. For images with fewer bands, duplicates the first band across all RGB channels.

    Example:
        ```python
        # Display the mock image
        pil_image = mock_image.to_display()
        pil_image.show()

        # Display without histogram equalization
        pil_image = mock_image.to_display(equalize=False)
        ```

    Note:
        NaN values in the image are automatically handled by replacing them with 0
        during the scaling process. The method always returns an RGB image regardless
        of the number of input bands.
    """
    if self.bands >= 3:
        display_bands = self._array[:, :, self.default_bands]
    else:
        display_bands = np.stack([self._array[:, :, 0]] * 3, axis=2)

    if equalize:
        for i in range(display_bands.shape[2]):
            band = display_bands[:, :, i]
            non_nan = ~np.isnan(band)
            if np.any(non_nan):
                min_val = np.nanmin(band)
                max_val = np.nanmax(band)
                if max_val > min_val:
                    band = (band - min_val) / (max_val - min_val) * 255
                display_bands[:, :, i] = band

    display_array = np.nan_to_num(display_bands).astype(np.uint8)
    return Image.fromarray(display_array)

to_numpy

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

Convert the mock 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 copy of the underlying 3D numpy array with shape (height, width, bands). If nan_value is provided, all NaN values are replaced with this value.

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

# Replace NaN values with zero
data = mock_image.to_numpy(nan_value=0.0)
Source code in siapy/entities/images/mock.py
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
def to_numpy(self, nan_value: float | None = None) -> NDArray[np.floating[Any]]:
    """Convert the mock image to a numpy array.

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

    Returns:
        A copy of the underlying 3D numpy array with shape (height, width, bands). If nan_value is provided, all NaN values are replaced with this value.

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

        # Replace NaN values with zero
        data = mock_image.to_numpy(nan_value=0.0)
        ```
    """
    if nan_value is not None:
        return np.nan_to_num(self._array, nan=nan_value)
    return self._array.copy()

to_xarray

to_xarray() -> XarrayType

Convert the mock image to an xarray DataArray.

RETURNS DESCRIPTION
XarrayType

An xarray DataArray with labeled dimensions (y, x, band) and coordinates, including mock wavelength values and minimal metadata.

Example
# Convert to xarray for analysis
xr_data = mock_image.to_xarray()

# Access specific bands
first_band = xr_data.sel(band=0)
Source code in siapy/entities/images/mock.py
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
def to_xarray(self) -> "XarrayType":
    """Convert the mock image to an xarray DataArray.

    Returns:
        An xarray DataArray with labeled dimensions (y, x, band) and coordinates, including mock wavelength values and minimal metadata.

    Example:
        ```python
        # Convert to xarray for analysis
        xr_data = mock_image.to_xarray()

        # Access specific bands
        first_band = xr_data.sel(band=0)
        ```
    """
    return xr.DataArray(
        self._array,
        dims=["y", "x", "band"],
        coords={
            "band": self.wavelengths,
            "x": np.arange(self.shape[1]),
            "y": np.arange(self.shape[0]),
        },
        attrs={
            "camera_id": self.camera_id,
        },
    )