Debian Codegraph @

imageio/plugins/tifffile.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 # imageio is distributed under the terms of the (new) BSD License.
3
4 """Read/Write TIFF files.
5
6 Backend: internal
7
8 Provides support for a wide range of Tiff images using the tifffile
9 backend.
10
11 Parameters for reading
12 ----------------------
13 offset : int
14 Optional start position of embedded file. By default this is
15 the current file position.
16 size : int
17 Optional size of embedded file. By default this is the number
18 of bytes from the 'offset' to the end of the file.
19 multifile : bool
20 If True (default), series may include pages from multiple files.
21 Currently applies to OME-TIFF only.
22 multifile_close : bool
23 If True (default), keep the handles of other files in multifile
24 series closed. This is inefficient when few files refer to
25 many pages. If False, the C runtime may run out of resources.
26
27 Parameters for saving
28 ---------------------
29 bigtiff : bool
30 If True, the BigTIFF format is used.
31 byteorder : {'<', '>'}
32 The endianness of the data in the file.
33 By default this is the system's native byte order.
34 software : str
35 Name of the software used to create the image.
36 Saved with the first page only.
37
38 Metadata for reading
39 --------------------
40 planar_configuration : {'contig', 'planar'}
41 Specifies if samples are stored contiguous or in separate planes.
42 By default this setting is inferred from the data shape.
43 'contig': last dimension contains samples.
44 'planar': third last dimension contains samples.
45 resolution_unit : int
46 The resolution unit stored in the TIFF tag. Usually 1 means no/unknown unit,
47 2 means dpi (inch), 3 means dpc (centimeter).
48 resolution : (float, float, str)
49 A tuple formatted as (X_resolution, Y_resolution, unit). The unit is a
50 string representing one of the following units::
51
52 NONE # No unit or unit unknown
53 INCH # dpi
54 CENTIMETER # cpi
55 MILLIMETER
56 MICROMETER
57
58 compression : int
59 Value indicating the compression algorithm used, e.g. 5 is LZW,
60 7 is JPEG, 8 is deflate.
61 If 1, data are uncompressed.
62 predictor : int
63 Value 2 indicates horizontal differencing was used before compression,
64 while 3 indicates floating point horizontal differencing.
65 If 1, no prediction scheme was used before compression.
66 orientation : {'top_left', 'bottom_right', ...}
67 Oriented of image array.
68 is_rgb : bool
69 True if page contains a RGB image.
70 is_contig : bool
71 True if page contains a contiguous image.
72 is_tiled : bool
73 True if page contains tiled image.
74 is_palette : bool
75 True if page contains a palette-colored image and not OME or STK.
76 is_reduced : bool
77 True if page is a reduced image of another image.
78 is_shaped : bool
79 True if page contains shape in image_description tag.
80 is_fluoview : bool
81 True if page contains FluoView MM_STAMP tag.
82 is_nih : bool
83 True if page contains NIH image header.
84 is_micromanager : bool
85 True if page contains Micro-Manager metadata.
86 is_ome : bool
87 True if page contains OME-XML in image_description tag.
88 is_sgi : bool
89 True if page contains SGI image and tile depth tags.
90 is_mdgel : bool
91 True if page contains md_file_tag tag.
92 is_mediacy : bool
93 True if page contains Media Cybernetics Id tag.
94 is_stk : bool
95 True if page contains UIC2Tag tag.
96 is_lsm : bool
97 True if page contains LSM CZ_LSM_INFO tag.
98 description : str
99 Image description
100 description1 : str
101 Additional description
102 is_imagej : None or str
103 ImageJ metadata
104 software : str
105 Software used to create the TIFF file
106 datetime : datetime.datetime
107 Creation date and time
108
109 Metadata for writing
110 --------------------
111 photometric : {'minisblack', 'miniswhite', 'rgb'}
112 The color space of the image data.
113 By default this setting is inferred from the data shape.
114 planarconfig : {'contig', 'planar'}
115 Specifies if samples are stored contiguous or in separate planes.
116 By default this setting is inferred from the data shape.
117 'contig': last dimension contains samples.
118 'planar': third last dimension contains samples.
119 resolution : (float, float) or ((int, int), (int, int))
120 X and Y resolution in dots per inch as float or rational numbers.
121 description : str
122 The subject of the image. Saved with the first page only.
123 compress : int
124 Values from 0 to 9 controlling the level of zlib (deflate) compression.
125 If 0, data are written uncompressed (default).
126 compression : str, (int, int)
127 Compression scheme used while writing the image. If omitted (default) the
128 image is not uncompressed. Compression cannot be used to write contiguous
129 series. Compressors may require certain data shapes, types or value ranges.
130 For example, JPEG compression requires grayscale or RGB(A), uint8 or 12-bit
131 uint16. JPEG compression is experimental. JPEG markers and TIFF tags may not
132 match. Only a limited set of compression schemes are implemented. 'ZLIB' is
133 short for ADOBE_DEFLATE. The value is written to the Compression tag.
134 compressionargs:
135 Extra arguments passed to compression codec, e.g., compression level. Refer
136 to the Imagecodecs implementation for supported arguments.
137 predictor : bool
138 If True, horizontal differencing is applied before compression.
139 Note that using an int literal 1 actually means no prediction scheme
140 will be used.
141 volume : bool
142 If True, volume data are stored in one tile (if applicable) using
143 the SGI image_depth and tile_depth tags.
144 Image width and depth must be multiple of 16.
145 Few software can read this format, e.g. MeVisLab.
146 writeshape : bool
147 If True, write the data shape to the image_description tag
148 if necessary and no other description is given.
149 extratags: sequence of tuples
150 Additional tags as [(code, dtype, count, value, writeonce)].
151
152 code : int
153 The TIFF tag Id.
154 dtype : str
155 Data type of items in 'value' in Python struct format.
156 One of B, s, H, I, 2I, b, h, i, f, d, Q, or q.
157 count : int
158 Number of data values. Not used for string values.
159 value : sequence
160 'Count' values compatible with 'dtype'.
161 writeonce : bool
162 If True, the tag is written to the first page only.
163
164 Notes
165 -----
166 Global metadata is stored with the first frame in a TIFF file.
167 Thus calling :py:meth:`Format.Writer.set_meta_data` after the first frame
168 was written has no effect. Also, global metadata is ignored if metadata is
169 provided via the `meta` argument of :py:meth:`Format.Writer.append_data`.
170
171 If you have installed tifffile as a Python package, imageio will attempt
172 to use that as backend instead of the bundled backend. Doing so can
173 provide access to new performance improvements and bug fixes.
174
175 """
176
177 import datetime
178
179 from ..core import Format
180 from ..core.request import URI_BYTES, URI_FILE
181
182 import numpy as np
183 import warnings
184
185 try:
186 import tifffile as _tifffile
187 except ImportError:
188 warnings.warn(
189 "ImageIO's vendored tifffile backend is deprecated and will be"
190 " removed in ImageIO v3. Install the tifffile directly:"
191 " `pip install imageio[tifffile]`",
192 DeprecationWarning,
193 )
194 from . import _tifffile
195
196
197 TIFF_FORMATS = (".tif", ".tiff", ".stk", ".lsm")
198 WRITE_METADATA_KEYS = (
199 "photometric",
200 "planarconfig",
201 "resolution",
202 "description",
203 "compress",
204 "compression",
205 "compressionargs",
206 "predictor",
207 "volume",
208 "writeshape",
209 "extratags",
210 "datetime",
211 )
212 READ_METADATA_KEYS = (
213 "planar_configuration",
214 "is_fluoview",
215 "is_nih",
216 "is_contig",
217 "is_micromanager",
218 "is_ome",
219 "is_lsm",
220 "is_palette",
221 "is_reduced",
222 "is_rgb",
223 "is_sgi",
224 "is_shaped",
225 "is_stk",
226 "is_tiled",
227 "is_mdgel",
228 "resolution_unit",
229 "compression",
230 "predictor",
231 "is_mediacy",
232 "orientation",
233 "description",
234 "description1",
235 "is_imagej",
236 "software",
237 )
238
239
240 class TiffFormat(Format):
241 """Provides support for a wide range of Tiff images using the tifffile
242 backend.
243
244 Images that contain multiple pages can be read using ``imageio.mimread()``
245 to read the individual pages, or ``imageio.volread()`` to obtain a
246 single (higher dimensional) array.
247
248 Note that global metadata is stored with the first frame in a TIFF file.
249 Thus calling :py:meth:`Format.Writer.set_meta_data` after the first frame
250 was written has no effect. Also, global metadata is ignored if metadata is
251 provided via the `meta` argument of :py:meth:`Format.Writer.append_data`.
252
253 If you have installed tifffile as a Python package, imageio will attempt
254 to use that as backend instead of the bundled backend. Doing so can
255 provide access to new performance improvements and bug fixes.
256
257 Parameters for reading
258 ----------------------
259 offset : int
260 Optional start position of embedded file. By default this is
261 the current file position.
262 size : int
263 Optional size of embedded file. By default this is the number
264 of bytes from the 'offset' to the end of the file.
265 multifile : bool
266 If True (default), series may include pages from multiple files.
267 Currently applies to OME-TIFF only.
268 multifile_close : bool
269 If True (default), keep the handles of other files in multifile
270 series closed. This is inefficient when few files refer to
271 many pages. If False, the C runtime may run out of resources.
272
273 Parameters for saving
274 ---------------------
275 bigtiff : bool
276 If True, the BigTIFF format is used.
277 byteorder : {'<', '>'}
278 The endianness of the data in the file.
279 By default this is the system's native byte order.
280 software : str
281 Name of the software used to create the image.
282 Saved with the first page only.
283
284 Metadata for reading
285 --------------------
286 planar_configuration : {'contig', 'planar'}
287 Specifies if samples are stored contiguous or in separate planes.
288 By default this setting is inferred from the data shape.
289 'contig': last dimension contains samples.
290 'planar': third last dimension contains samples.
291 resolution_unit : (float, float) or ((int, int), (int, int))
292 X and Y resolution in dots per inch as float or rational numbers.
293 compression : int
294 Value indicating the compression algorithm used, e.g. 5 is LZW,
295 7 is JPEG, 8 is deflate.
296 If 1, data are uncompressed.
297 predictor : int
298 Value 2 indicates horizontal differencing was used before compression,
299 while 3 indicates floating point horizontal differencing.
300 If 1, no prediction scheme was used before compression.
301 orientation : {'top_left', 'bottom_right', ...}
302 Oriented of image array.
303 is_rgb : bool
304 True if page contains a RGB image.
305 is_contig : bool
306 True if page contains a contiguous image.
307 is_tiled : bool
308 True if page contains tiled image.
309 is_palette : bool
310 True if page contains a palette-colored image and not OME or STK.
311 is_reduced : bool
312 True if page is a reduced image of another image.
313 is_shaped : bool
314 True if page contains shape in image_description tag.
315 is_fluoview : bool
316 True if page contains FluoView MM_STAMP tag.
317 is_nih : bool
318 True if page contains NIH image header.
319 is_micromanager : bool
320 True if page contains Micro-Manager metadata.
321 is_ome : bool
322 True if page contains OME-XML in image_description tag.
323 is_sgi : bool
324 True if page contains SGI image and tile depth tags.
325 is_stk : bool
326 True if page contains UIC2Tag tag.
327 is_mdgel : bool
328 True if page contains md_file_tag tag.
329 is_mediacy : bool
330 True if page contains Media Cybernetics Id tag.
331 is_stk : bool
332 True if page contains UIC2Tag tag.
333 is_lsm : bool
334 True if page contains LSM CZ_LSM_INFO tag.
335 description : str
336 Image description
337 description1 : str
338 Additional description
339 is_imagej : None or str
340 ImageJ metadata
341 software : str
342 Software used to create the TIFF file
343 datetime : datetime.datetime
344 Creation date and time
345
346 Metadata for writing
347 --------------------
348 photometric : {'minisblack', 'miniswhite', 'rgb'}
349 The color space of the image data.
350 By default this setting is inferred from the data shape.
351 planarconfig : {'contig', 'planar'}
352 Specifies if samples are stored contiguous or in separate planes.
353 By default this setting is inferred from the data shape.
354 'contig': last dimension contains samples.
355 'planar': third last dimension contains samples.
356 resolution : (float, float) or ((int, int), (int, int))
357 X and Y resolution in dots per inch as float or rational numbers.
358 description : str
359 The subject of the image. Saved with the first page only.
360 compress : int
361 Values from 0 to 9 controlling the level of zlib (deflate) compression.
362 If 0, data are written uncompressed (default).
363 predictor : bool
364 If True, horizontal differencing is applied before compression.
365 Note that using an int literal 1 actually means no prediction scheme
366 will be used.
367 volume : bool
368 If True, volume data are stored in one tile (if applicable) using
369 the SGI image_depth and tile_depth tags.
370 Image width and depth must be multiple of 16.
371 Few software can read this format, e.g. MeVisLab.
372 writeshape : bool
373 If True, write the data shape to the image_description tag
374 if necessary and no other description is given.
375 extratags: sequence of tuples
376 Additional tags as [(code, dtype, count, value, writeonce)].
377
378 code : int
379 The TIFF tag Id.
380 dtype : str
381 Data type of items in 'value' in Python struct format.
382 One of B, s, H, I, 2I, b, h, i, f, d, Q, or q.
383 count : int
384 Number of data values. Not used for string values.
385 value : sequence
386 'Count' values compatible with 'dtype'.
387 writeonce : bool
388 If True, the tag is written to the first page only.
389 """
390
391 def _can_read(self, request):
392 try:
393 _tifffile.TiffFile(request.get_file(), **request.kwargs)
394 except ValueError:
395 # vendored backend raises value exception
396 return False
397 except _tifffile.TiffFileError: # pragma: no-cover
398 # current version raises custom exception
399 return False
400 finally:
401 request.get_file().seek(0)
402
403 return True
404
405 def _can_write(self, request):
406 if request._uri_type in [URI_FILE, URI_BYTES]:
407 pass # special URI
408 elif request.extension not in self.extensions:
409 return False
410
411 try:
412 _tifffile.TiffWriter(request.get_file(), **request.kwargs)
413 except ValueError:
414 # vendored backend raises value exception
415 return False
416 except _tifffile.TiffFileError: # pragma: no-cover
417 # current version raises custom exception
418 return False
419 finally:
420 request.get_file().seek(0)
421 return True
422
423 # -- reader
424
425 class Reader(Format.Reader):
426 def _open(self, **kwargs):
427 # Allow loading from http; tifffile uses seek, so download first
428 if self.request.filename.startswith(("http://", "https://")):
429 self._f = f = open(self.request.get_local_filename(), "rb")
430 else:
431 self._f = None
432 f = self.request.get_file()
433 self._tf = _tifffile.TiffFile(f, **kwargs)
434
435 def _close(self):
436 self._tf.close()
437 if self._f is not None:
438 self._f.close()
439
440 def _get_length(self):
441 return len(self._tf.series)
442
443 def _get_data(self, index):
444 if index < 0 or index >= self._get_length():
445 raise IndexError("Index out of range while reading from tiff file")
446
447 im = self._tf.asarray(series=index)
448 meta = self._get_meta_data(index)
449
450 return im, meta
451
452 def _get_meta_data(self, index):
453 meta = {}
454 page = self._tf.pages[index or 0]
455 for key in READ_METADATA_KEYS:
456 try:
457 meta[key] = getattr(page, key)
458 except Exception:
459 pass
460
461 # tifffile <= 0.12.1 use datetime, newer use DateTime
462 for key in ("datetime", "DateTime"):
463 try:
464 meta["datetime"] = datetime.datetime.strptime(
465 page.tags[key].value, "%Y:%m:%d %H:%M:%S"
466 )
467 break
468 except Exception:
469 pass
470
471 if 296 in page.tags:
472 meta["resolution_unit"] = page.tags[296].value.value
473
474 if 282 in page.tags and 283 in page.tags and 296 in page.tags:
475 resolution_x = page.tags[282].value
476 resolution_y = page.tags[283].value
477 if resolution_x[1] == 0 or resolution_y[1] == 0:
478 warnings.warn(
479 "Ignoring resolution metadata, "
480 "because at least one direction has a 0 denominator.",
481 RuntimeWarning,
482 )
483 else:
484 meta["resolution"] = (
485 resolution_x[0] / resolution_x[1],
486 resolution_y[0] / resolution_y[1],
487 page.tags[296].value.name,
488 )
489
490 return meta
491
492 # -- writer
493 class Writer(Format.Writer):
494 def _open(self, bigtiff=None, byteorder=None, software=None):
495 try:
496 self._tf = _tifffile.TiffWriter(
497 self.request.get_file(),
498 bigtiff=bigtiff,
499 byteorder=byteorder,
500 software=software,
501 )
502 self._software = None
503 except TypeError:
504 # In tifffile >= 0.15, the `software` arg is passed to
505 # TiffWriter.save
506 self._tf = _tifffile.TiffWriter(
507 self.request.get_file(), bigtiff=bigtiff, byteorder=byteorder
508 )
509 self._software = software
510
511 self._meta = {}
512 self._frames_written = 0
513
514 def _close(self):
515 self._tf.close()
516
517 def _append_data(self, im, meta):
518 if meta is not None:
519 meta = self._sanitize_meta(meta)
520 else:
521 # Use global metadata for first frame
522 meta = self._meta if self._frames_written == 0 else {}
523 if self._software is not None and self._frames_written == 0:
524 meta["software"] = self._software
525 # No need to check self.request.mode; tifffile figures out whether
526 # this is a single page, or all page data at once.
527 try:
528 # TiffWriter.save has been deprecated in version 2020.9.30
529 write_meth = self._tf.write
530 except AttributeError:
531 write_meth = self._tf.save
532 write_meth(np.asanyarray(im), contiguous=False, **meta)
533 self._frames_written += 1
534
535 @staticmethod
536 def _sanitize_meta(meta):
537 ret = {}
538 for key, value in meta.items():
539 if key in WRITE_METADATA_KEYS:
540 # Special case of previously read `predictor` int value
541 # 1(=NONE) translation to False expected by TiffWriter.save
542 if key == "predictor" and not isinstance(value, bool):
543 ret[key] = value > 1
544 elif key == "compress" and value != 0:
545 warnings.warn(
546 "The use of `compress` is deprecated. Use `compression` and `compressionargs` instead.",
547 DeprecationWarning,
548 )
549
550 if _tifffile.__version__ < "2022":
551 ret["compression"] = (8, value)
552 else:
553 ret["compression"] = "zlib"
554 ret["compressionargs"] = {"level": value}
555 else:
556 ret[key] = value
557 return ret
558
559 def set_meta_data(self, meta):
560 self._meta = self._sanitize_meta(meta)