|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from dataclasses import dataclass |
| 4 | +from typing import TYPE_CHECKING |
| 5 | + |
| 6 | +import numpy as np |
| 7 | +import pandas as pd |
| 8 | +import xarray as xr |
| 9 | + |
| 10 | +if TYPE_CHECKING: |
| 11 | + import os |
| 12 | + from typing import Any, Literal, Protocol |
| 13 | + |
| 14 | + import numpy.typing as npt |
| 15 | + |
| 16 | + class FileLike(Protocol): ... |
| 17 | + |
| 18 | + class LockType(Protocol): |
| 19 | + def __enter__(self) -> Any: ... |
| 20 | + |
| 21 | + def acquire(self, blocking: bool = True, timeout: int = -1) -> bool: ... |
| 22 | + def release(self) -> None: ... |
| 23 | + |
| 24 | + IndexerType = int | slice | npt.NDArray[np.integer] |
| 25 | + FilenameOrObjectType = str | os.PathLike | bytes | FileLike |
| 26 | + |
| 27 | + |
| 28 | +@dataclass |
| 29 | +class ImageIOBackendArray(xr.backends.BackendArray): |
| 30 | + filename_or_obj: FilenameOrObjectType |
| 31 | + |
| 32 | + shape: tuple[int] |
| 33 | + dtype: npt.DtypeLike |
| 34 | + |
| 35 | + lock: LockType |
| 36 | + |
| 37 | + def __getitem__(self, key: tuple[IndexerType]): |
| 38 | + return xr.core.indexing.explicit_indexing_adapter( |
| 39 | + key, |
| 40 | + self.shape, |
| 41 | + xr.core.indexing.IndexingSupport.BASIC, |
| 42 | + self.basic_indexing, |
| 43 | + ) |
| 44 | + |
| 45 | + def basic_indexing(self, key: tuple[IndexerType]) -> npt.NDArray: |
| 46 | + import imageio.v3 as iio |
| 47 | + |
| 48 | + with self.lock, iio.imopen(self.filename_or_obj, io_mode="r") as f: |
| 49 | + if key == (slice(None),) * len(self.shape): |
| 50 | + return f.read() |
| 51 | + |
| 52 | + first_indexer = key[0] |
| 53 | + if isinstance(first_indexer, int): |
| 54 | + data = f.read(index=first_indexer, mode="P", writable=True) |
| 55 | + |
| 56 | + remaining_indexers = key[1:] |
| 57 | + else: |
| 58 | + if isinstance(first_indexer, slice): |
| 59 | + indices = range(*first_indexer.indices(self.shape[0])) |
| 60 | + else: |
| 61 | + indices = first_indexer |
| 62 | + |
| 63 | + data = np.concatenate([f.read(index=index, mode="P") for index in indices], axis=0) |
| 64 | + |
| 65 | + remaining_indexers = (..., *key[1:]) |
| 66 | + |
| 67 | + return data[remaining_indexers] |
| 68 | + |
| 69 | + |
| 70 | +class ImageIOBackend(xr.backends.BackendEntrypoint): |
| 71 | + def open_dataset( |
| 72 | + self, |
| 73 | + filename_or_obj: FilenameOrObjectType, |
| 74 | + *, |
| 75 | + drop_variables: bool | None = None, |
| 76 | + mode: Literal["grayscale", "color"] = "color", |
| 77 | + ) -> xr.Dataset: |
| 78 | + import imageio.v3 as iio |
| 79 | + |
| 80 | + with iio.imopen(filename_or_obj, io_mode="r") as f: |
| 81 | + properties = f.properties() |
| 82 | + metadata = f.metadata() |
| 83 | + |
| 84 | + dims = ["time", "height", "width", "color"] |
| 85 | + |
| 86 | + background = metadata["background"] |
| 87 | + duration = metadata["duration"] |
| 88 | + loop = metadata["loop"] |
| 89 | + |
| 90 | + shape = properties.shape |
| 91 | + dtype = properties.dtype |
| 92 | + |
| 93 | + if isinstance(duration, (int, float)): |
| 94 | + time_values = np.timedelta64(duration, "ms") * np.arange(shape[0]) |
| 95 | + else: |
| 96 | + time_values = np.array(duration, dtype="timedelta64[ms]") |
| 97 | + |
| 98 | + time = xr.indexes.PandasIndex(pd.Index(time_values), dim="time") |
| 99 | + |
| 100 | + backend_array = ImageIOBackendArray( |
| 101 | + filename_or_obj=filename_or_obj, |
| 102 | + shape=shape, |
| 103 | + dtype=dtype, |
| 104 | + lock=xr.backends.locks.SerializableLock(), |
| 105 | + ) |
| 106 | + data = xr.core.indexing.LazilyIndexedArray(backend_array) |
| 107 | + |
| 108 | + var = xr.Variable( |
| 109 | + dims=dims, |
| 110 | + data=data, |
| 111 | + attrs={"loop": loop}, |
| 112 | + encoding={ |
| 113 | + "preferred_chunks": dict(zip(dims, (1, *shape[1:]))), |
| 114 | + "fill_value": background, |
| 115 | + }, |
| 116 | + ) |
| 117 | + coords = xr.Coordinates.from_xindex(time).assign(color=["red", "green", "blue"]) |
| 118 | + |
| 119 | + return xr.Dataset({"data": var}, coords=coords) |
0 commit comments