| 1 |
"""Read/Write TIFF files using tifffile. |
| 2 |
|
| 3 |
.. note:: |
| 4 |
To use this plugin you need to have `tifffile |
| 5 |
<https://github.com/cgohlke/tifffile>`_ installed:: |
| 6 |
|
| 7 |
pip install tifffile |
| 8 |
|
| 9 |
This plugin wraps tifffile, a powerful library to manipulate TIFF files. It |
| 10 |
superseeds our previous tifffile plugin and aims to expose all the features of |
| 11 |
tifffile. |
| 12 |
|
| 13 |
The plugin treats individual TIFF series as ndimages. A series is a sequence of |
| 14 |
TIFF pages that, when combined describe a meaningful unit, e.g., a volumetric |
| 15 |
image (where each slice is stored on an individual page) or a multi-color |
| 16 |
staining picture (where each stain is stored on an individual page). Different |
| 17 |
TIFF flavors/variants use series in different ways and, as such, the resulting |
| 18 |
reading behavior may vary depending on the program used while creating a |
| 19 |
particular TIFF file. |
| 20 |
|
| 21 |
Methods |
| 22 |
------- |
| 23 |
.. note:: |
| 24 |
Check the respective function for a list of supported kwargs and detailed |
| 25 |
documentation. |
| 26 |
|
| 27 |
.. autosummary:: |
| 28 |
:toctree: |
| 29 |
|
| 30 |
TifffilePlugin.read |
| 31 |
TifffilePlugin.iter |
| 32 |
TifffilePlugin.write |
| 33 |
TifffilePlugin.properties |
| 34 |
TifffilePlugin.metadata |
| 35 |
|
| 36 |
Additional methods available inside the :func:`imopen <imageio.v3.imopen>` |
| 37 |
context: |
| 38 |
|
| 39 |
.. autosummary:: |
| 40 |
:toctree: |
| 41 |
|
| 42 |
TifffilePlugin.iter_pages |
| 43 |
|
| 44 |
""" |
| 45 |
|
| 46 |
from io import BytesIO |
| 47 |
from typing import Any, Dict, Optional, cast |
| 48 |
import warnings |
| 49 |
|
| 50 |
import numpy as np |
| 51 |
import tifffile |
| 52 |
|
| 53 |
from ..core.request import URI_BYTES, InitializationError, Request |
| 54 |
from ..core.v3_plugin_api import ImageProperties, PluginV3 |
| 55 |
from ..typing import ArrayLike |
| 56 |
|
| 57 |
|
| 58 |
def _get_resolution(page: tifffile.TiffPage) -> Dict[str, Any]: |
| 59 |
metadata = {} |
| 60 |
|
| 61 |
try: |
| 62 |
metadata["resolution_unit"] = page.tags[296].value.value |
| 63 |
except KeyError: |
| 64 |
|
| 65 |
return metadata |
| 66 |
|
| 67 |
try: |
| 68 |
resolution_x = page.tags[282].value |
| 69 |
resolution_y = page.tags[283].value |
| 70 |
|
| 71 |
metadata["resolution"] = ( |
| 72 |
resolution_x[0] / resolution_x[1], |
| 73 |
resolution_y[0] / resolution_y[1], |
| 74 |
) |
| 75 |
except KeyError: |
| 76 |
|
| 77 |
pass |
| 78 |
except ZeroDivisionError: |
| 79 |
warnings.warn( |
| 80 |
"Ignoring resolution metadata because at least one direction has a 0 " |
| 81 |
"denominator.", |
| 82 |
RuntimeWarning, |
| 83 |
) |
| 84 |
|
| 85 |
return metadata |
| 86 |
|
| 87 |
|
| 88 |
class TifffilePlugin(PluginV3): |
| 89 |
"""Support for tifffile as backend. |
| 90 |
|
| 91 |
Parameters |
| 92 |
---------- |
| 93 |
request : iio.Request |
| 94 |
A request object that represents the users intent. It provides a |
| 95 |
standard interface for a plugin to access the various ImageResources. |
| 96 |
Check the docs for details. |
| 97 |
kwargs : Any |
| 98 |
Additional kwargs are forwarded to tifffile's constructor, i.e. |
| 99 |
to ``TiffFile`` for reading or ``TiffWriter`` for writing. |
| 100 |
|
| 101 |
""" |
| 102 |
|
| 103 |
def __init__(self, request: Request, **kwargs) -> None: |
| 104 |
super().__init__(request) |
| 105 |
self._fh = None |
| 106 |
|
| 107 |
if request.mode.io_mode == "r": |
| 108 |
try: |
| 109 |
self._fh = tifffile.TiffFile(request.get_file(), **kwargs) |
| 110 |
except tifffile.tifffile.TiffFileError: |
| 111 |
raise InitializationError("Tifffile can not read this file.") |
| 112 |
else: |
| 113 |
self._fh = tifffile.TiffWriter(request.get_file(), **kwargs) |
| 114 |
|
| 115 |
|
| 116 |
|
| 117 |
|
| 118 |
|
| 119 |
def read(self, *, index: int = None, page: int = None, **kwargs) -> np.ndarray: |
| 120 |
"""Read a ndimage or page. |
| 121 |
|
| 122 |
The ndimage returned depends on the value of both ``index`` and |
| 123 |
``page``. ``index`` selects the series to read and ``page`` allows |
| 124 |
selecting a single page from the selected series. If ``index=None``, |
| 125 |
``page`` is understood as a flat index, i.e., the selection ignores |
| 126 |
individual series inside the file. If both ``index`` and ``page`` are |
| 127 |
``None``, then all the series are read and returned as a batch. |
| 128 |
|
| 129 |
Parameters |
| 130 |
---------- |
| 131 |
index : int |
| 132 |
If ``int``, select the ndimage (series) located at that index inside |
| 133 |
the file and return ``page`` from it. If ``None`` and ``page`` is |
| 134 |
``int`` read the page located at that (flat) index inside the file. |
| 135 |
If ``None`` and ``page=None``, read all ndimages from the file and |
| 136 |
return them as a batch. |
| 137 |
page : int |
| 138 |
If ``None`` return the full selected ndimage. If ``int``, read the |
| 139 |
page at the selected index and return it. |
| 140 |
kwargs : Any |
| 141 |
Additional kwargs are forwarded to TiffFile's ``as_array`` method. |
| 142 |
|
| 143 |
Returns |
| 144 |
------- |
| 145 |
ndarray : np.ndarray |
| 146 |
The decoded ndimage or page. |
| 147 |
""" |
| 148 |
|
| 149 |
if "key" not in kwargs: |
| 150 |
kwargs["key"] = page |
| 151 |
elif page is not None: |
| 152 |
raise ValueError("Can't use `page` and `key` at the same time.") |
| 153 |
|
| 154 |
|
| 155 |
if index is not None and "series" in kwargs: |
| 156 |
raise ValueError("Can't use `series` and `index` at the same time.") |
| 157 |
elif "series" in kwargs: |
| 158 |
index = kwargs.pop("series") |
| 159 |
elif index is not None: |
| 160 |
pass |
| 161 |
else: |
| 162 |
index = 0 |
| 163 |
|
| 164 |
if index is Ellipsis and page is None: |
| 165 |
|
| 166 |
ndimage = np.stack([x for x in self.iter(**kwargs)]) |
| 167 |
else: |
| 168 |
index = None if index is Ellipsis else index |
| 169 |
ndimage = self._fh.asarray(series=index, **kwargs) |
| 170 |
|
| 171 |
return ndimage |
| 172 |
|
| 173 |
def iter(self, **kwargs) -> np.ndarray: |
| 174 |
"""Yield ndimages from the TIFF. |
| 175 |
|
| 176 |
Parameters |
| 177 |
---------- |
| 178 |
kwargs : Any |
| 179 |
Additional kwargs are forwarded to the TiffPageSeries' ``as_array`` |
| 180 |
method. |
| 181 |
|
| 182 |
Yields |
| 183 |
------ |
| 184 |
ndimage : np.ndarray |
| 185 |
A decoded ndimage. |
| 186 |
""" |
| 187 |
|
| 188 |
for sequence in self._fh.series: |
| 189 |
yield sequence.asarray(**kwargs) |
| 190 |
|
| 191 |
def write( |
| 192 |
self, ndimage: ArrayLike, *, is_batch: bool = False, **kwargs |
| 193 |
) -> Optional[bytes]: |
| 194 |
"""Save a ndimage as TIFF. |
| 195 |
|
| 196 |
Parameters |
| 197 |
---------- |
| 198 |
ndimage : ArrayLike |
| 199 |
The ndimage to encode and write to the ImageResource. |
| 200 |
is_batch : bool |
| 201 |
If True, the first dimension of the given ndimage is treated as a |
| 202 |
batch dimension and each element will create a new series. |
| 203 |
kwargs : Any |
| 204 |
Additional kwargs are forwarded to TiffWriter's ``write`` method. |
| 205 |
|
| 206 |
Returns |
| 207 |
------- |
| 208 |
encoded_image : bytes |
| 209 |
If the ImageResource is ``"<bytes>"``, return the encoded bytes. |
| 210 |
Otherwise write returns None. |
| 211 |
|
| 212 |
Notes |
| 213 |
----- |
| 214 |
Incremental writing is supported. Subsequent calls to ``write`` will |
| 215 |
create new series unless ``contiguous=True`` is used, in which case the |
| 216 |
call to write will append to the current series. |
| 217 |
|
| 218 |
When ``photometric`` / ``planarconfig`` are omitted, ImageIO sets |
| 219 |
defaults for common RGB layouts so tifffile does not emit deprecation |
| 220 |
warnings about ambiguous channel-axis interpretation: |
| 221 |
|
| 222 |
- channel-last arrays (shape ``(..., 3)`` or ``(..., 4)``): |
| 223 |
``photometric="rgb"`` |
| 224 |
- channel-first arrays (shape ``(3, ...)`` or ``(4, ...)`` on the |
| 225 |
third-to-last axis): ``photometric="rgb"`` and |
| 226 |
``planarconfig="separate"`` |
| 227 |
""" |
| 228 |
|
| 229 |
if not is_batch: |
| 230 |
ndimage = np.asarray(ndimage)[None, :] |
| 231 |
|
| 232 |
for image in ndimage: |
| 233 |
write_kwargs = dict(kwargs) |
| 234 |
arr = np.asarray(image) |
| 235 |
if arr.ndim >= 3 and arr.shape[-1] in (3, 4): |
| 236 |
write_kwargs.setdefault("photometric", "rgb") |
| 237 |
elif arr.ndim >= 3 and arr.shape[-3] in (3, 4): |
| 238 |
write_kwargs.setdefault("photometric", "rgb") |
| 239 |
write_kwargs.setdefault("planarconfig", "separate") |
| 240 |
self._fh.write(image, **write_kwargs) |
| 241 |
|
| 242 |
if self._request._uri_type == URI_BYTES: |
| 243 |
self._fh.close() |
| 244 |
file = cast(BytesIO, self._request.get_file()) |
| 245 |
return file.getvalue() |
| 246 |
|
| 247 |
def metadata( |
| 248 |
self, *, index: int = Ellipsis, page: int = None, exclude_applied: bool = True |
| 249 |
) -> Dict[str, Any]: |
| 250 |
"""Format-Specific TIFF metadata. |
| 251 |
|
| 252 |
The metadata returned depends on the value of both ``index`` and |
| 253 |
``page``. ``index`` selects a series and ``page`` allows selecting a |
| 254 |
single page from the selected series. If ``index=Ellipsis``, ``page`` is |
| 255 |
understood as a flat index, i.e., the selection ignores individual |
| 256 |
series inside the file. If ``index=Ellipsis`` and ``page=None`` then |
| 257 |
global (file-level) metadata is returned. |
| 258 |
|
| 259 |
Parameters |
| 260 |
---------- |
| 261 |
index : int |
| 262 |
Select the series of which to extract metadata from. If Ellipsis, treat |
| 263 |
page as a flat index into the file's pages. |
| 264 |
page : int |
| 265 |
If not None, select the page of which to extract metadata from. If |
| 266 |
None, read series-level metadata or, if ``index=...`` global, |
| 267 |
file-level metadata. |
| 268 |
exclude_applied : bool |
| 269 |
For API compatibility. Currently ignored. |
| 270 |
|
| 271 |
Returns |
| 272 |
------- |
| 273 |
metadata : dict |
| 274 |
A dictionary with information regarding the tiff flavor (file-level) |
| 275 |
or tiff tags (page-level). |
| 276 |
""" |
| 277 |
|
| 278 |
if index is not Ellipsis and page is not None: |
| 279 |
target = self._fh.series[index].pages[page] |
| 280 |
elif index is not Ellipsis and page is None: |
| 281 |
|
| 282 |
|
| 283 |
target = self._fh.series[index].pages[0] |
| 284 |
elif index is Ellipsis and page is not None: |
| 285 |
target = self._fh.pages[page] |
| 286 |
else: |
| 287 |
target = None |
| 288 |
|
| 289 |
metadata = {} |
| 290 |
if target is None: |
| 291 |
|
| 292 |
metadata["byteorder"] = self._fh.byteorder |
| 293 |
|
| 294 |
for flag in tifffile.TIFF.FILE_FLAGS: |
| 295 |
flag_value = getattr(self._fh, "is_" + flag) |
| 296 |
metadata["is_" + flag] = flag_value |
| 297 |
|
| 298 |
if flag_value and hasattr(self._fh, flag + "_metadata"): |
| 299 |
flavor_metadata = getattr(self._fh, flag + "_metadata") |
| 300 |
if isinstance(flavor_metadata, tuple): |
| 301 |
metadata.update(flavor_metadata[0]) |
| 302 |
else: |
| 303 |
metadata.update(flavor_metadata) |
| 304 |
else: |
| 305 |
|
| 306 |
target = target.keyframe |
| 307 |
|
| 308 |
metadata.update({tag.name: tag.value for tag in target.tags}) |
| 309 |
metadata.update( |
| 310 |
{ |
| 311 |
"planar_configuration": target.planarconfig, |
| 312 |
"compression": target.compression, |
| 313 |
"predictor": target.predictor, |
| 314 |
"orientation": None, |
| 315 |
"description1": target.description1, |
| 316 |
"description": target.description, |
| 317 |
"software": target.software, |
| 318 |
**_get_resolution(target), |
| 319 |
"datetime": target.datetime, |
| 320 |
} |
| 321 |
) |
| 322 |
|
| 323 |
return metadata |
| 324 |
|
| 325 |
def properties(self, *, index: int = None, page: int = None) -> ImageProperties: |
| 326 |
"""Standardized metadata. |
| 327 |
|
| 328 |
The properties returned depend on the value of both ``index`` and |
| 329 |
``page``. ``index`` selects a series and ``page`` allows selecting a |
| 330 |
single page from the selected series. If ``index=Ellipsis``, ``page`` is |
| 331 |
understood as a flat index, i.e., the selection ignores individual |
| 332 |
series inside the file. If ``index=Ellipsis`` and ``page=None`` then |
| 333 |
global (file-level) properties are returned. If ``index=Ellipsis`` |
| 334 |
and ``page=...``, file-level properties for the flattened index are |
| 335 |
returned. |
| 336 |
|
| 337 |
Parameters |
| 338 |
---------- |
| 339 |
index : int |
| 340 |
If ``int``, select the ndimage (series) located at that index inside |
| 341 |
the file. If ``Ellipsis`` and ``page`` is ``int`` extract the |
| 342 |
properties of the page located at that (flat) index inside the file. |
| 343 |
If ``Ellipsis`` and ``page=None``, return the properties for the |
| 344 |
batch of all ndimages in the file. |
| 345 |
page : int |
| 346 |
If ``None`` return the properties of the full ndimage. If ``...`` |
| 347 |
return the properties of the flattened index. If ``int``, |
| 348 |
return the properties of the page at the selected index only. |
| 349 |
|
| 350 |
Returns |
| 351 |
------- |
| 352 |
image_properties : ImageProperties |
| 353 |
The standardized metadata (properties) of the selected ndimage or series. |
| 354 |
|
| 355 |
""" |
| 356 |
index = index or 0 |
| 357 |
page_idx = 0 if page in (None, Ellipsis) else page |
| 358 |
|
| 359 |
if index is Ellipsis: |
| 360 |
target_page = self._fh.pages[page_idx] |
| 361 |
else: |
| 362 |
target_page = self._fh.series[index].pages[page_idx] |
| 363 |
|
| 364 |
if index is Ellipsis and page is None: |
| 365 |
n_series = len(self._fh.series) |
| 366 |
props = ImageProperties( |
| 367 |
shape=(n_series, *target_page.shape), |
| 368 |
dtype=target_page.dtype, |
| 369 |
n_images=n_series, |
| 370 |
is_batch=True, |
| 371 |
spacing=_get_resolution(target_page).get("resolution"), |
| 372 |
) |
| 373 |
elif index is Ellipsis and page is Ellipsis: |
| 374 |
n_pages = len(self._fh.pages) |
| 375 |
props = ImageProperties( |
| 376 |
shape=(n_pages, *target_page.shape), |
| 377 |
dtype=target_page.dtype, |
| 378 |
n_images=n_pages, |
| 379 |
is_batch=True, |
| 380 |
spacing=_get_resolution(target_page).get("resolution"), |
| 381 |
) |
| 382 |
else: |
| 383 |
props = ImageProperties( |
| 384 |
shape=target_page.shape, |
| 385 |
dtype=target_page.dtype, |
| 386 |
is_batch=False, |
| 387 |
spacing=_get_resolution(target_page).get("resolution"), |
| 388 |
) |
| 389 |
|
| 390 |
return props |
| 391 |
|
| 392 |
def close(self) -> None: |
| 393 |
if self._fh is not None: |
| 394 |
self._fh.close() |
| 395 |
|
| 396 |
super().close() |
| 397 |
|
| 398 |
|
| 399 |
|
| 400 |
|
| 401 |
|
| 402 |
def iter_pages(self, index=..., **kwargs): |
| 403 |
"""Yield pages from a TIFF file. |
| 404 |
|
| 405 |
This generator walks over the flat index of the pages inside an |
| 406 |
ImageResource and yields them in order. |
| 407 |
|
| 408 |
Parameters |
| 409 |
---------- |
| 410 |
index : int |
| 411 |
The index of the series to yield pages from. If Ellipsis, walk over |
| 412 |
the file's flat index (and ignore individual series). |
| 413 |
kwargs : Any |
| 414 |
Additional kwargs are passed to TiffPage's ``as_array`` method. |
| 415 |
|
| 416 |
Yields |
| 417 |
------ |
| 418 |
page : np.ndarray |
| 419 |
A page stored inside the TIFF file. |
| 420 |
|
| 421 |
""" |
| 422 |
|
| 423 |
if index is Ellipsis: |
| 424 |
pages = self._fh.pages |
| 425 |
else: |
| 426 |
pages = self._fh.series[index] |
| 427 |
|
| 428 |
for page in pages: |
| 429 |
yield page.asarray(**kwargs) |