| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
"""Read image and meta data from (bio) TIFF(R) files. Save numpy arrays as TIFF. |
| 35 |
|
| 36 |
Image and metadata can be read from TIFF, BigTIFF, OME-TIFF, STK, LSM, NIH, |
| 37 |
SGI, ImageJ, MicroManager, FluoView, ScanImage, SEQ, GEL, and GeoTIFF files. |
| 38 |
|
| 39 |
Tifffile is not a general-purpose TIFF library. |
| 40 |
Only a subset of the TIFF specification is supported, mainly uncompressed and |
| 41 |
losslessly compressed 1, 8, 16, 32 and 64 bit integer, 16, 32 and 64-bit float, |
| 42 |
grayscale and RGB(A) images, which are commonly used in scientific imaging. |
| 43 |
Specifically, reading slices of image data, image trees defined via SubIFDs, |
| 44 |
CCITT and OJPEG compression, chroma subsampling without JPEG compression, |
| 45 |
or IPTC and XMP metadata are not implemented. |
| 46 |
|
| 47 |
TIFF(R), the tagged Image File Format, is a trademark and under control of |
| 48 |
Adobe Systems Incorporated. BigTIFF allows for files greater than 4 GB. |
| 49 |
STK, LSM, FluoView, SGI, SEQ, GEL, and OME-TIFF, are custom extensions |
| 50 |
defined by Molecular Devices (Universal Imaging Corporation), Carl Zeiss |
| 51 |
MicroImaging, Olympus, Silicon Graphics International, Media Cybernetics, |
| 52 |
Molecular Dynamics, and the Open Microscopy Environment consortium |
| 53 |
respectively. |
| 54 |
|
| 55 |
For command line usage run C{python -m tifffile --help} |
| 56 |
|
| 57 |
:Author: |
| 58 |
`Christoph Gohlke <https://www.lfd.uci.edu/~gohlke/>`_ |
| 59 |
|
| 60 |
:Organization: |
| 61 |
Laboratory for Fluorescence Dynamics, University of California, Irvine |
| 62 |
|
| 63 |
:Version: 2018.06.15 |
| 64 |
|
| 65 |
Requirements |
| 66 |
------------ |
| 67 |
* `CPython 3.6 64-bit <https://www.python.org>`_ |
| 68 |
* `Numpy 1.14 <http://www.numpy.org>`_ |
| 69 |
* `Matplotlib 2.2 <https://www.matplotlib.org>`_ (optional for plotting) |
| 70 |
* `Tifffile.c 2018.02.10 <https://www.lfd.uci.edu/~gohlke/>`_ |
| 71 |
(recommended for faster decoding of PackBits and LZW encoded strings) |
| 72 |
* `Tifffile_geodb.py 2018.02.10 <https://www.lfd.uci.edu/~gohlke/>`_ |
| 73 |
(optional enums for GeoTIFF metadata) |
| 74 |
* Python 2 requires 'futures', 'enum34', 'pathlib'. |
| 75 |
|
| 76 |
Revisions |
| 77 |
--------- |
| 78 |
2018.06.15 |
| 79 |
Pass 2680 tests. |
| 80 |
Towards reading JPEG and other compressions via imagecodecs package (WIP). |
| 81 |
Add function to validate TIFF using 'jhove -m TIFF-hul'. |
| 82 |
Save bool arrays as bilevel TIFF. |
| 83 |
Accept pathlib.Path as filenames. |
| 84 |
Move 'software' argument from TiffWriter __init__ to save. |
| 85 |
Raise DOS limit to 16 TB. |
| 86 |
Lazy load lzma and zstd compressors and decompressors. |
| 87 |
Add option to save IJMetadata tags. |
| 88 |
Return correct number of pages for truncated series (bug fix). |
| 89 |
Move EXIF tags to TIFF.TAG as per TIFF/EP standard. |
| 90 |
2018.02.18 |
| 91 |
Pass 2293 tests. |
| 92 |
Always save RowsPerStrip and Resolution tags as required by TIFF standard. |
| 93 |
Do not use badly typed ImageDescription. |
| 94 |
Coherce bad ASCII string tags to bytes. |
| 95 |
Tuning of __str__ functions. |
| 96 |
Fix reading 'undefined' tag values (bug fix). |
| 97 |
Read and write ZSTD compressed data. |
| 98 |
Use hexdump to print byte strings. |
| 99 |
Determine TIFF byte order from data dtype in imsave. |
| 100 |
Add option to specify RowsPerStrip for compressed strips. |
| 101 |
Allow memory map of arrays with non-native byte order. |
| 102 |
Attempt to handle ScanImage <= 5.1 files. |
| 103 |
Restore TiffPageSeries.pages sequence interface. |
| 104 |
Use numpy.frombuffer instead of fromstring to read from binary data. |
| 105 |
Parse GeoTIFF metadata. |
| 106 |
Add option to apply horizontal differencing before compression. |
| 107 |
Towards reading PerkinElmer QPTIFF (no test files). |
| 108 |
Do not index out of bounds data in tifffile.c unpackbits and decodelzw. |
| 109 |
2017.09.29 (tentative) |
| 110 |
Many backwards incompatible changes improving speed and resource usage: |
| 111 |
Pass 2268 tests. |
| 112 |
Add detail argument to __str__ function. Remove info functions. |
| 113 |
Fix potential issue correcting offsets of large LSM files with positions. |
| 114 |
Remove TiffFile sequence interface; use TiffFile.pages instead. |
| 115 |
Do not make tag values available as TiffPage attributes. |
| 116 |
Use str (not bytes) type for tag and metadata strings (WIP). |
| 117 |
Use documented standard tag and value names (WIP). |
| 118 |
Use enums for some documented TIFF tag values. |
| 119 |
Remove 'memmap' and 'tmpfile' options; use out='memmap' instead. |
| 120 |
Add option to specify output in asarray functions. |
| 121 |
Add option to concurrently decode image strips or tiles using threads. |
| 122 |
Add TiffPage.asrgb function (WIP). |
| 123 |
Do not apply colormap in asarray. |
| 124 |
Remove 'colormapped', 'rgbonly', and 'scale_mdgel' options from asarray. |
| 125 |
Consolidate metadata in TiffFile _metadata functions. |
| 126 |
Remove non-tag metadata properties from TiffPage. |
| 127 |
Add function to convert LSM to tiled BIN files. |
| 128 |
Align image data in file. |
| 129 |
Make TiffPage.dtype a numpy.dtype. |
| 130 |
Add 'ndim' and 'size' properties to TiffPage and TiffPageSeries. |
| 131 |
Allow imsave to write non-BigTIFF files up to ~4 GB. |
| 132 |
Only read one page for shaped series if possible. |
| 133 |
Add memmap function to create memory-mapped array stored in TIFF file. |
| 134 |
Add option to save empty arrays to TIFF files. |
| 135 |
Add option to save truncated TIFF files. |
| 136 |
Allow single tile images to be saved contiguously. |
| 137 |
Add optional movie mode for files with uniform pages. |
| 138 |
Lazy load pages. |
| 139 |
Use lightweight TiffFrame for IFDs sharing properties with key TiffPage. |
| 140 |
Move module constants to 'TIFF' namespace (speed up module import). |
| 141 |
Remove 'fastij' option from TiffFile. |
| 142 |
Remove 'pages' parameter from TiffFile. |
| 143 |
Remove TIFFfile alias. |
| 144 |
Deprecate Python 2. |
| 145 |
Require enum34 and futures packages on Python 2.7. |
| 146 |
Remove Record class and return all metadata as dict instead. |
| 147 |
Add functions to parse STK, MetaSeries, ScanImage, SVS, Pilatus metadata. |
| 148 |
Read tags from EXIF and GPS IFDs. |
| 149 |
Use pformat for tag and metadata values. |
| 150 |
Fix reading some UIC tags (bug fix). |
| 151 |
Do not modify input array in imshow (bug fix). |
| 152 |
Fix Python implementation of unpack_ints. |
| 153 |
2017.05.23 |
| 154 |
Pass 1961 tests. |
| 155 |
Write correct number of SampleFormat values (bug fix). |
| 156 |
Use Adobe deflate code to write ZIP compressed files. |
| 157 |
Add option to pass tag values as packed binary data for writing. |
| 158 |
Defer tag validation to attribute access. |
| 159 |
Use property instead of lazyattr decorator for simple expressions. |
| 160 |
2017.03.17 |
| 161 |
Write IFDs and tag values on word boundaries. |
| 162 |
Read ScanImage metadata. |
| 163 |
Remove is_rgb and is_indexed attributes from TiffFile. |
| 164 |
Create files used by doctests. |
| 165 |
2017.01.12 |
| 166 |
Read Zeiss SEM metadata. |
| 167 |
Read OME-TIFF with invalid references to external files. |
| 168 |
Rewrite C LZW decoder (5x faster). |
| 169 |
Read corrupted LSM files missing EOI code in LZW stream. |
| 170 |
2017.01.01 |
| 171 |
Add option to append images to existing TIFF files. |
| 172 |
Read files without pages. |
| 173 |
Read S-FEG and Helios NanoLab tags created by FEI software. |
| 174 |
Allow saving Color Filter Array (CFA) images. |
| 175 |
Add info functions returning more information about TiffFile and TiffPage. |
| 176 |
Add option to read specific pages only. |
| 177 |
Remove maxpages argument (backwards incompatible). |
| 178 |
Remove test_tifffile function. |
| 179 |
2016.10.28 |
| 180 |
Pass 1944 tests. |
| 181 |
Improve detection of ImageJ hyperstacks. |
| 182 |
Read TVIPS metadata created by EM-MENU (by Marco Oster). |
| 183 |
Add option to disable using OME-XML metadata. |
| 184 |
Allow non-integer range attributes in modulo tags (by Stuart Berg). |
| 185 |
2016.06.21 |
| 186 |
Do not always memmap contiguous data in page series. |
| 187 |
2016.05.13 |
| 188 |
Add option to specify resolution unit. |
| 189 |
Write grayscale images with extra samples when planarconfig is specified. |
| 190 |
Do not write RGB color images with 2 samples. |
| 191 |
Reorder TiffWriter.save keyword arguments (backwards incompatible). |
| 192 |
2016.04.18 |
| 193 |
Pass 1932 tests. |
| 194 |
TiffWriter, imread, and imsave accept open binary file streams. |
| 195 |
2016.04.13 |
| 196 |
Correctly handle reversed fill order in 2 and 4 bps images (bug fix). |
| 197 |
Implement reverse_bitorder in C. |
| 198 |
2016.03.18 |
| 199 |
Fix saving additional ImageJ metadata. |
| 200 |
2016.02.22 |
| 201 |
Pass 1920 tests. |
| 202 |
Write 8 bytes double tag values using offset if necessary (bug fix). |
| 203 |
Add option to disable writing second image description tag. |
| 204 |
Detect tags with incorrect counts. |
| 205 |
Disable color mapping for LSM. |
| 206 |
2015.11.13 |
| 207 |
Read LSM 6 mosaics. |
| 208 |
Add option to specify directory of memory-mapped files. |
| 209 |
Add command line options to specify vmin and vmax values for colormapping. |
| 210 |
2015.10.06 |
| 211 |
New helper function to apply colormaps. |
| 212 |
Renamed is_palette attributes to is_indexed (backwards incompatible). |
| 213 |
Color-mapped samples are now contiguous (backwards incompatible). |
| 214 |
Do not color-map ImageJ hyperstacks (backwards incompatible). |
| 215 |
Towards reading Leica SCN. |
| 216 |
2015.09.25 |
| 217 |
Read images with reversed bit order (FillOrder is LSB2MSB). |
| 218 |
2015.09.21 |
| 219 |
Read RGB OME-TIFF. |
| 220 |
Warn about malformed OME-XML. |
| 221 |
2015.09.16 |
| 222 |
Detect some corrupted ImageJ metadata. |
| 223 |
Better axes labels for 'shaped' files. |
| 224 |
Do not create TiffTag for default values. |
| 225 |
Chroma subsampling is not supported. |
| 226 |
Memory-map data in TiffPageSeries if possible (optional). |
| 227 |
2015.08.17 |
| 228 |
Pass 1906 tests. |
| 229 |
Write ImageJ hyperstacks (optional). |
| 230 |
Read and write LZMA compressed data. |
| 231 |
Specify datetime when saving (optional). |
| 232 |
Save tiled and color-mapped images (optional). |
| 233 |
Ignore void bytecounts and offsets if possible. |
| 234 |
Ignore bogus image_depth tag created by ISS Vista software. |
| 235 |
Decode floating point horizontal differencing (not tiled). |
| 236 |
Save image data contiguously if possible. |
| 237 |
Only read first IFD from ImageJ files if possible. |
| 238 |
Read ImageJ 'raw' format (files larger than 4 GB). |
| 239 |
TiffPageSeries class for pages with compatible shape and data type. |
| 240 |
Try to read incomplete tiles. |
| 241 |
Open file dialog if no filename is passed on command line. |
| 242 |
Ignore errors when decoding OME-XML. |
| 243 |
Rename decoder functions (backwards incompatible). |
| 244 |
2014.08.24 |
| 245 |
TiffWriter class for incremental writing images. |
| 246 |
Simplify examples. |
| 247 |
2014.08.19 |
| 248 |
Add memmap function to FileHandle. |
| 249 |
Add function to determine if image data in TiffPage is memory-mappable. |
| 250 |
Do not close files if multifile_close parameter is False. |
| 251 |
2014.08.10 |
| 252 |
Pass 1730 tests. |
| 253 |
Return all extrasamples by default (backwards incompatible). |
| 254 |
Read data from series of pages into memory-mapped array (optional). |
| 255 |
Squeeze OME dimensions (backwards incompatible). |
| 256 |
Workaround missing EOI code in strips. |
| 257 |
Support image and tile depth tags (SGI extension). |
| 258 |
Better handling of STK/UIC tags (backwards incompatible). |
| 259 |
Disable color mapping for STK. |
| 260 |
Julian to datetime converter. |
| 261 |
TIFF ASCII type may be NULL separated. |
| 262 |
Unwrap strip offsets for LSM files greater than 4 GB. |
| 263 |
Correct strip byte counts in compressed LSM files. |
| 264 |
Skip missing files in OME series. |
| 265 |
Read embedded TIFF files. |
| 266 |
2014.02.05 |
| 267 |
Save rational numbers as type 5 (bug fix). |
| 268 |
2013.12.20 |
| 269 |
Keep other files in OME multi-file series closed. |
| 270 |
FileHandle class to abstract binary file handle. |
| 271 |
Disable color mapping for bad OME-TIFF produced by bio-formats. |
| 272 |
Read bad OME-XML produced by ImageJ when cropping. |
| 273 |
2013.11.03 |
| 274 |
Allow zlib compress data in imsave function (optional). |
| 275 |
Memory-map contiguous image data (optional). |
| 276 |
2013.10.28 |
| 277 |
Read MicroManager metadata and little-endian ImageJ tag. |
| 278 |
Save extra tags in imsave function. |
| 279 |
Save tags in ascending order by code (bug fix). |
| 280 |
2012.10.18 |
| 281 |
Accept file like objects (read from OIB files). |
| 282 |
2012.08.21 |
| 283 |
Rename TIFFfile to TiffFile and TIFFpage to TiffPage. |
| 284 |
TiffSequence class for reading sequence of TIFF files. |
| 285 |
Read UltraQuant tags. |
| 286 |
Allow float numbers as resolution in imsave function. |
| 287 |
2012.08.03 |
| 288 |
Read MD GEL tags and NIH Image header. |
| 289 |
2012.07.25 |
| 290 |
Read ImageJ tags. |
| 291 |
... |
| 292 |
|
| 293 |
Notes |
| 294 |
----- |
| 295 |
The API is not stable yet and might change between revisions. |
| 296 |
|
| 297 |
Tested on little-endian platforms only. |
| 298 |
|
| 299 |
Other Python packages and modules for reading (bio) scientific TIFF files: |
| 300 |
|
| 301 |
* `python-bioformats <https://github.com/CellProfiler/python-bioformats>`_ |
| 302 |
* `Imread <https://github.com/luispedro/imread>`_ |
| 303 |
* `PyLibTiff <https://github.com/pearu/pylibtiff>`_ |
| 304 |
* `ITK <https://www.itk.org>`_ |
| 305 |
* `PyLSM <https://launchpad.net/pylsm>`_ |
| 306 |
* `PyMca.TiffIO.py <https://github.com/vasole/pymca>`_ (same as fabio.TiffIO) |
| 307 |
* `BioImageXD.Readers <http://www.bioimagexd.net/>`_ |
| 308 |
* `Cellcognition.io <http://cellcognition.org/>`_ |
| 309 |
* `pymimage <https://github.com/ardoi/pymimage>`_ |
| 310 |
* `pytiff <https://github.com/FZJ-INM1-BDA/pytiff>`_ |
| 311 |
|
| 312 |
Acknowledgements |
| 313 |
---------------- |
| 314 |
* Egor Zindy, University of Manchester, for lsm_scan_info specifics. |
| 315 |
* Wim Lewis for a bug fix and some LSM functions. |
| 316 |
* Hadrien Mary for help on reading MicroManager files. |
| 317 |
* Christian Kliche for help writing tiled and color-mapped files. |
| 318 |
|
| 319 |
References |
| 320 |
---------- |
| 321 |
1) TIFF 6.0 Specification and Supplements. Adobe Systems Incorporated. |
| 322 |
http://partners.adobe.com/public/developer/tiff/ |
| 323 |
2) TIFF File Format FAQ. http://www.awaresystems.be/imaging/tiff/faq.html |
| 324 |
3) MetaMorph Stack (STK) Image File Format. |
| 325 |
http://support.meta.moleculardevices.com/docs/t10243.pdf |
| 326 |
4) Image File Format Description LSM 5/7 Release 6.0 (ZEN 2010). |
| 327 |
Carl Zeiss MicroImaging GmbH. BioSciences. May 10, 2011 |
| 328 |
5) The OME-TIFF format. |
| 329 |
http://www.openmicroscopy.org/site/support/file-formats/ome-tiff |
| 330 |
6) UltraQuant(r) Version 6.0 for Windows Start-Up Guide. |
| 331 |
http://www.ultralum.com/images%20ultralum/pdf/UQStart%20Up%20Guide.pdf |
| 332 |
7) Micro-Manager File Formats. |
| 333 |
http://www.micro-manager.org/wiki/Micro-Manager_File_Formats |
| 334 |
8) Tags for TIFF and Related Specifications. Digital Preservation. |
| 335 |
http://www.digitalpreservation.gov/formats/content/tiff_tags.shtml |
| 336 |
9) ScanImage BigTiff Specification - ScanImage 2016. |
| 337 |
http://scanimage.vidriotechnologies.com/display/SI2016/ |
| 338 |
ScanImage+BigTiff+Specification |
| 339 |
10) CIPA DC-008-2016: Exchangeable image file format for digital still cameras: |
| 340 |
Exif Version 2.31. |
| 341 |
http://www.cipa.jp/std/documents/e/DC-008-Translation-2016-E.pdf |
| 342 |
|
| 343 |
Examples |
| 344 |
-------- |
| 345 |
>>> # write numpy array to TIFF file |
| 346 |
>>> data = numpy.random.rand(4, 301, 219) |
| 347 |
>>> imsave('temp.tif', data, photometric='minisblack') |
| 348 |
|
| 349 |
>>> # read numpy array from TIFF file |
| 350 |
>>> image = imread('temp.tif') |
| 351 |
>>> numpy.testing.assert_array_equal(image, data) |
| 352 |
|
| 353 |
>>> # iterate over pages and tags in TIFF file |
| 354 |
>>> with TiffFile('temp.tif') as tif: |
| 355 |
... images = tif.asarray() |
| 356 |
... for page in tif.pages: |
| 357 |
... for tag in page.tags.values(): |
| 358 |
... _ = tag.name, tag.value |
| 359 |
... image = page.asarray() |
| 360 |
|
| 361 |
""" |
| 362 |
|
| 363 |
from __future__ import division, print_function |
| 364 |
|
| 365 |
import sys |
| 366 |
import os |
| 367 |
import io |
| 368 |
import re |
| 369 |
import glob |
| 370 |
import math |
| 371 |
import zlib |
| 372 |
import time |
| 373 |
import json |
| 374 |
import enum |
| 375 |
import struct |
| 376 |
import pathlib |
| 377 |
import warnings |
| 378 |
import binascii |
| 379 |
import tempfile |
| 380 |
import datetime |
| 381 |
import threading |
| 382 |
import collections |
| 383 |
import multiprocessing |
| 384 |
import concurrent.futures |
| 385 |
|
| 386 |
import numpy |
| 387 |
|
| 388 |
|
| 389 |
|
| 390 |
|
| 391 |
__version__ = "2018.06.15" |
| 392 |
__docformat__ = "restructuredtext en" |
| 393 |
__all__ = ( |
| 394 |
"imsave", |
| 395 |
"imread", |
| 396 |
"imshow", |
| 397 |
"memmap", |
| 398 |
"TiffFile", |
| 399 |
"TiffWriter", |
| 400 |
"TiffSequence", |
| 401 |
|
| 402 |
"FileHandle", |
| 403 |
"lazyattr", |
| 404 |
"natural_sorted", |
| 405 |
"decode_lzw", |
| 406 |
"stripnull", |
| 407 |
"create_output", |
| 408 |
"repeat_nd", |
| 409 |
"format_size", |
| 410 |
"product", |
| 411 |
"xml2dict", |
| 412 |
) |
| 413 |
|
| 414 |
|
| 415 |
def imread(files, **kwargs): |
| 416 |
"""Return image data from TIFF file(s) as numpy array. |
| 417 |
|
| 418 |
Refer to the TiffFile class and member functions for documentation. |
| 419 |
|
| 420 |
Parameters |
| 421 |
---------- |
| 422 |
files : str, binary stream, or sequence |
| 423 |
File name, seekable binary stream, glob pattern, or sequence of |
| 424 |
file names. |
| 425 |
kwargs : dict |
| 426 |
Parameters 'multifile' and 'is_ome' are passed to the TiffFile class. |
| 427 |
The 'pattern' parameter is passed to the TiffSequence class. |
| 428 |
Other parameters are passed to the asarray functions. |
| 429 |
The first image series is returned if no arguments are provided. |
| 430 |
|
| 431 |
Examples |
| 432 |
-------- |
| 433 |
>>> # get image from first page |
| 434 |
>>> imsave('temp.tif', numpy.random.rand(3, 4, 301, 219)) |
| 435 |
>>> im = imread('temp.tif', key=0) |
| 436 |
>>> im.shape |
| 437 |
(4, 301, 219) |
| 438 |
|
| 439 |
>>> # get images from sequence of files |
| 440 |
>>> ims = imread(['temp.tif', 'temp.tif']) |
| 441 |
>>> ims.shape |
| 442 |
(2, 3, 4, 301, 219) |
| 443 |
|
| 444 |
""" |
| 445 |
kwargs_file = parse_kwargs(kwargs, "multifile", "is_ome") |
| 446 |
kwargs_seq = parse_kwargs(kwargs, "pattern") |
| 447 |
|
| 448 |
if isinstance(files, basestring) and any(i in files for i in "?*"): |
| 449 |
files = glob.glob(files) |
| 450 |
if not files: |
| 451 |
raise ValueError("no files found") |
| 452 |
if not hasattr(files, "seek") and len(files) == 1: |
| 453 |
files = files[0] |
| 454 |
|
| 455 |
if isinstance(files, basestring) or hasattr(files, "seek"): |
| 456 |
with TiffFile(files, **kwargs_file) as tif: |
| 457 |
return tif.asarray(**kwargs) |
| 458 |
else: |
| 459 |
with TiffSequence(files, **kwargs_seq) as imseq: |
| 460 |
return imseq.asarray(**kwargs) |
| 461 |
|
| 462 |
|
| 463 |
def imsave(file, data=None, shape=None, dtype=None, bigsize=2**32 - 2**25, **kwargs): |
| 464 |
"""Write numpy array to TIFF file. |
| 465 |
|
| 466 |
Refer to the TiffWriter class and member functions for documentation. |
| 467 |
|
| 468 |
Parameters |
| 469 |
---------- |
| 470 |
file : str or binary stream |
| 471 |
File name or writable binary stream, such as an open file or BytesIO. |
| 472 |
data : array_like |
| 473 |
Input image. The last dimensions are assumed to be image depth, |
| 474 |
height, width, and samples. |
| 475 |
If None, an empty array of the specified shape and dtype is |
| 476 |
saved to file. |
| 477 |
Unless 'byteorder' is specified in 'kwargs', the TIFF file byte order |
| 478 |
is determined from the data's dtype or the dtype argument. |
| 479 |
shape : tuple |
| 480 |
If 'data' is None, shape of an empty array to save to the file. |
| 481 |
dtype : numpy.dtype |
| 482 |
If 'data' is None, data-type of an empty array to save to the file. |
| 483 |
bigsize : int |
| 484 |
Create a BigTIFF file if the size of data in bytes is larger than |
| 485 |
this threshold and 'imagej' or 'truncate' are not enabled. |
| 486 |
By default, the threshold is 4 GB minus 32 MB reserved for metadata. |
| 487 |
Use the 'bigtiff' parameter to explicitly specify the type of |
| 488 |
file created. |
| 489 |
kwargs : dict |
| 490 |
Parameters 'append', 'byteorder', 'bigtiff', and 'imagej', are passed |
| 491 |
to TiffWriter(). Other parameters are passed to TiffWriter.save(). |
| 492 |
|
| 493 |
Returns |
| 494 |
------- |
| 495 |
If the image data are written contiguously, return offset and bytecount |
| 496 |
of image data in the file. |
| 497 |
|
| 498 |
Examples |
| 499 |
-------- |
| 500 |
>>> # save a RGB image |
| 501 |
>>> data = numpy.random.randint(0, 255, (256, 256, 3), 'uint8') |
| 502 |
>>> imsave('temp.tif', data, photometric='rgb') |
| 503 |
|
| 504 |
>>> # save a random array and metadata, using compression |
| 505 |
>>> data = numpy.random.rand(2, 5, 3, 301, 219) |
| 506 |
>>> imsave('temp.tif', data, compress=6, metadata={'axes': 'TZCYX'}) |
| 507 |
|
| 508 |
""" |
| 509 |
tifargs = parse_kwargs(kwargs, "append", "bigtiff", "byteorder", "imagej") |
| 510 |
if data is None: |
| 511 |
size = product(shape) * numpy.dtype(dtype).itemsize |
| 512 |
byteorder = numpy.dtype(dtype).byteorder |
| 513 |
else: |
| 514 |
try: |
| 515 |
size = data.nbytes |
| 516 |
byteorder = data.dtype.byteorder |
| 517 |
except Exception: |
| 518 |
size = 0 |
| 519 |
byteorder = None |
| 520 |
if ( |
| 521 |
size > bigsize |
| 522 |
and "bigtiff" not in tifargs |
| 523 |
and not (tifargs.get("imagej", False) or tifargs.get("truncate", False)) |
| 524 |
): |
| 525 |
tifargs["bigtiff"] = True |
| 526 |
if "byteorder" not in tifargs: |
| 527 |
tifargs["byteorder"] = byteorder |
| 528 |
|
| 529 |
with TiffWriter(file, **tifargs) as tif: |
| 530 |
return tif.save(data, shape, dtype, **kwargs) |
| 531 |
|
| 532 |
|
| 533 |
def memmap(filename, shape=None, dtype=None, page=None, series=0, mode="r+", **kwargs): |
| 534 |
"""Return memory-mapped numpy array stored in TIFF file. |
| 535 |
|
| 536 |
Memory-mapping requires data stored in native byte order, without tiling, |
| 537 |
compression, predictors, etc. |
| 538 |
If 'shape' and 'dtype' are provided, existing files will be overwritten or |
| 539 |
appended to depending on the 'append' parameter. |
| 540 |
Otherwise the image data of a specified page or series in an existing |
| 541 |
file will be memory-mapped. By default, the image data of the first page |
| 542 |
series is memory-mapped. |
| 543 |
Call flush() to write any changes in the array to the file. |
| 544 |
Raise ValueError if the image data in the file is not memory-mappable. |
| 545 |
|
| 546 |
Parameters |
| 547 |
---------- |
| 548 |
filename : str |
| 549 |
Name of the TIFF file which stores the array. |
| 550 |
shape : tuple |
| 551 |
Shape of the empty array. |
| 552 |
dtype : numpy.dtype |
| 553 |
Data-type of the empty array. |
| 554 |
page : int |
| 555 |
Index of the page which image data to memory-map. |
| 556 |
series : int |
| 557 |
Index of the page series which image data to memory-map. |
| 558 |
mode : {'r+', 'r', 'c'}, optional |
| 559 |
The file open mode. Default is to open existing file for reading and |
| 560 |
writing ('r+'). |
| 561 |
kwargs : dict |
| 562 |
Additional parameters passed to imsave() or TiffFile(). |
| 563 |
|
| 564 |
Examples |
| 565 |
-------- |
| 566 |
>>> # create an empty TIFF file and write to memory-mapped image |
| 567 |
>>> im = memmap('temp.tif', shape=(256, 256), dtype='float32') |
| 568 |
>>> im[255, 255] = 1.0 |
| 569 |
>>> im.flush() |
| 570 |
>>> im.shape, im.dtype |
| 571 |
((256, 256), dtype('float32')) |
| 572 |
>>> del im |
| 573 |
|
| 574 |
>>> # memory-map image data in a TIFF file |
| 575 |
>>> im = memmap('temp.tif', page=0) |
| 576 |
>>> im[255, 255] |
| 577 |
1.0 |
| 578 |
|
| 579 |
""" |
| 580 |
if shape is not None and dtype is not None: |
| 581 |
|
| 582 |
kwargs.update( |
| 583 |
data=None, |
| 584 |
shape=shape, |
| 585 |
dtype=dtype, |
| 586 |
returnoffset=True, |
| 587 |
align=TIFF.ALLOCATIONGRANULARITY, |
| 588 |
) |
| 589 |
result = imsave(filename, **kwargs) |
| 590 |
if result is None: |
| 591 |
|
| 592 |
raise ValueError("image data are not memory-mappable") |
| 593 |
offset = result[0] |
| 594 |
else: |
| 595 |
|
| 596 |
with TiffFile(filename, **kwargs) as tif: |
| 597 |
if page is not None: |
| 598 |
page = tif.pages[page] |
| 599 |
if not page.is_memmappable: |
| 600 |
raise ValueError("image data are not memory-mappable") |
| 601 |
offset, _ = page.is_contiguous |
| 602 |
shape = page.shape |
| 603 |
dtype = page.dtype |
| 604 |
else: |
| 605 |
series = tif.series[series] |
| 606 |
if series.offset is None: |
| 607 |
raise ValueError("image data are not memory-mappable") |
| 608 |
shape = series.shape |
| 609 |
dtype = series.dtype |
| 610 |
offset = series.offset |
| 611 |
dtype = tif.byteorder + dtype.char |
| 612 |
return numpy.memmap(filename, dtype, mode, offset, shape, "C") |
| 613 |
|
| 614 |
|
| 615 |
class lazyattr(object): |
| 616 |
"""Attribute whose value is computed on first access.""" |
| 617 |
|
| 618 |
|
| 619 |
__slots__ = ("func",) |
| 620 |
|
| 621 |
def __init__(self, func): |
| 622 |
self.func = func |
| 623 |
|
| 624 |
|
| 625 |
|
| 626 |
|
| 627 |
def __get__(self, instance, owner): |
| 628 |
|
| 629 |
if instance is None: |
| 630 |
return self |
| 631 |
try: |
| 632 |
value = self.func(instance) |
| 633 |
except AttributeError as e: |
| 634 |
raise RuntimeError(e) |
| 635 |
if value is NotImplemented: |
| 636 |
return getattr(super(owner, instance), self.func.__name__) |
| 637 |
setattr(instance, self.func.__name__, value) |
| 638 |
return value |
| 639 |
|
| 640 |
|
| 641 |
class TiffWriter(object): |
| 642 |
"""Write numpy arrays to TIFF file. |
| 643 |
|
| 644 |
TiffWriter instances must be closed using the 'close' method, which is |
| 645 |
automatically called when using the 'with' context manager. |
| 646 |
|
| 647 |
TiffWriter's main purpose is saving nD numpy array's as TIFF, |
| 648 |
not to create any possible TIFF format. Specifically, JPEG compression, |
| 649 |
SubIFDs, ExifIFD, or GPSIFD tags are not supported. |
| 650 |
|
| 651 |
Examples |
| 652 |
-------- |
| 653 |
>>> # successively append images to BigTIFF file |
| 654 |
>>> data = numpy.random.rand(2, 5, 3, 301, 219) |
| 655 |
>>> with TiffWriter('temp.tif', bigtiff=True) as tif: |
| 656 |
... for i in range(data.shape[0]): |
| 657 |
... tif.save(data[i], compress=6, photometric='minisblack') |
| 658 |
|
| 659 |
""" |
| 660 |
|
| 661 |
def __init__(self, file, bigtiff=False, byteorder=None, append=False, imagej=False): |
| 662 |
"""Open a TIFF file for writing. |
| 663 |
|
| 664 |
An empty TIFF file is created if the file does not exist, else the |
| 665 |
file is overwritten with an empty TIFF file unless 'append' |
| 666 |
is true. Use bigtiff=True when creating files larger than 4 GB. |
| 667 |
|
| 668 |
Parameters |
| 669 |
---------- |
| 670 |
file : str, binary stream, or FileHandle |
| 671 |
File name or writable binary stream, such as an open file |
| 672 |
or BytesIO. |
| 673 |
bigtiff : bool |
| 674 |
If True, the BigTIFF format is used. |
| 675 |
byteorder : {'<', '>', '=', '|'} |
| 676 |
The endianness of the data in the file. |
| 677 |
By default, this is the system's native byte order. |
| 678 |
append : bool |
| 679 |
If True and 'file' is an existing standard TIFF file, image data |
| 680 |
and tags are appended to the file. |
| 681 |
Appending data may corrupt specifically formatted TIFF files |
| 682 |
such as LSM, STK, ImageJ, NIH, or FluoView. |
| 683 |
imagej : bool |
| 684 |
If True, write an ImageJ hyperstack compatible file. |
| 685 |
This format can handle data types uint8, uint16, or float32 and |
| 686 |
data shapes up to 6 dimensions in TZCYXS order. |
| 687 |
RGB images (S=3 or S=4) must be uint8. |
| 688 |
ImageJ's default byte order is big-endian but this implementation |
| 689 |
uses the system's native byte order by default. |
| 690 |
ImageJ does not support BigTIFF format or LZMA compression. |
| 691 |
The ImageJ file format is undocumented. |
| 692 |
|
| 693 |
""" |
| 694 |
if append: |
| 695 |
|
| 696 |
try: |
| 697 |
with FileHandle(file, mode="rb", size=0) as fh: |
| 698 |
pos = fh.tell() |
| 699 |
try: |
| 700 |
with TiffFile(fh) as tif: |
| 701 |
if append != "force" and any( |
| 702 |
getattr(tif, "is_" + a) |
| 703 |
for a in ( |
| 704 |
"lsm", |
| 705 |
"stk", |
| 706 |
"imagej", |
| 707 |
"nih", |
| 708 |
"fluoview", |
| 709 |
"micromanager", |
| 710 |
) |
| 711 |
): |
| 712 |
raise ValueError("file contains metadata") |
| 713 |
byteorder = tif.byteorder |
| 714 |
bigtiff = tif.is_bigtiff |
| 715 |
self._ifdoffset = tif.pages.next_page_offset |
| 716 |
except Exception as e: |
| 717 |
raise ValueError("cannot append to file: %s" % str(e)) |
| 718 |
finally: |
| 719 |
fh.seek(pos) |
| 720 |
except (IOError, FileNotFoundError): |
| 721 |
append = False |
| 722 |
|
| 723 |
if byteorder in (None, "=", "|"): |
| 724 |
byteorder = "<" if sys.byteorder == "little" else ">" |
| 725 |
elif byteorder not in ("<", ">"): |
| 726 |
raise ValueError("invalid byteorder %s" % byteorder) |
| 727 |
if imagej and bigtiff: |
| 728 |
warnings.warn("writing incompatible BigTIFF ImageJ") |
| 729 |
|
| 730 |
self._byteorder = byteorder |
| 731 |
self._imagej = bool(imagej) |
| 732 |
self._truncate = False |
| 733 |
self._metadata = None |
| 734 |
self._colormap = None |
| 735 |
|
| 736 |
self._descriptionoffset = 0 |
| 737 |
self._descriptionlen = 0 |
| 738 |
self._descriptionlenoffset = 0 |
| 739 |
self._tags = None |
| 740 |
self._shape = None |
| 741 |
self._datashape = None |
| 742 |
self._datadtype = None |
| 743 |
self._dataoffset = None |
| 744 |
self._databytecounts = None |
| 745 |
self._tagoffsets = None |
| 746 |
|
| 747 |
if bigtiff: |
| 748 |
self._bigtiff = True |
| 749 |
self._offsetsize = 8 |
| 750 |
self._tagsize = 20 |
| 751 |
self._tagnoformat = "Q" |
| 752 |
self._offsetformat = "Q" |
| 753 |
self._valueformat = "8s" |
| 754 |
else: |
| 755 |
self._bigtiff = False |
| 756 |
self._offsetsize = 4 |
| 757 |
self._tagsize = 12 |
| 758 |
self._tagnoformat = "H" |
| 759 |
self._offsetformat = "I" |
| 760 |
self._valueformat = "4s" |
| 761 |
|
| 762 |
if append: |
| 763 |
self._fh = FileHandle(file, mode="r+b", size=0) |
| 764 |
self._fh.seek(0, 2) |
| 765 |
else: |
| 766 |
self._fh = FileHandle(file, mode="wb", size=0) |
| 767 |
self._fh.write({"<": b"II", ">": b"MM"}[byteorder]) |
| 768 |
if bigtiff: |
| 769 |
self._fh.write(struct.pack(byteorder + "HHH", 43, 8, 0)) |
| 770 |
else: |
| 771 |
self._fh.write(struct.pack(byteorder + "H", 42)) |
| 772 |
|
| 773 |
self._ifdoffset = self._fh.tell() |
| 774 |
self._fh.write(struct.pack(byteorder + self._offsetformat, 0)) |
| 775 |
|
| 776 |
def save( |
| 777 |
self, |
| 778 |
data=None, |
| 779 |
shape=None, |
| 780 |
dtype=None, |
| 781 |
returnoffset=False, |
| 782 |
photometric=None, |
| 783 |
planarconfig=None, |
| 784 |
tile=None, |
| 785 |
contiguous=True, |
| 786 |
align=16, |
| 787 |
truncate=False, |
| 788 |
compress=0, |
| 789 |
rowsperstrip=None, |
| 790 |
predictor=False, |
| 791 |
colormap=None, |
| 792 |
description=None, |
| 793 |
datetime=None, |
| 794 |
resolution=None, |
| 795 |
software="tifffile.py", |
| 796 |
metadata={}, |
| 797 |
ijmetadata=None, |
| 798 |
extratags=(), |
| 799 |
): |
| 800 |
"""Write numpy array and tags to TIFF file. |
| 801 |
|
| 802 |
The data shape's last dimensions are assumed to be image depth, |
| 803 |
height (length), width, and samples. |
| 804 |
If a colormap is provided, the data's dtype must be uint8 or uint16 |
| 805 |
and the data values are indices into the last dimension of the |
| 806 |
colormap. |
| 807 |
If 'shape' and 'dtype' are specified, an empty array is saved. |
| 808 |
This option cannot be used with compression or multiple tiles. |
| 809 |
Image data are written uncompressed in one strip per plane by default. |
| 810 |
Dimensions larger than 2 to 4 (depending on photometric mode, planar |
| 811 |
configuration, and SGI mode) are flattened and saved as separate pages. |
| 812 |
The SampleFormat and BitsPerSample tags are derived from the data type. |
| 813 |
|
| 814 |
Parameters |
| 815 |
---------- |
| 816 |
data : numpy.ndarray or None |
| 817 |
Input image array. |
| 818 |
shape : tuple or None |
| 819 |
Shape of the empty array to save. Used only if 'data' is None. |
| 820 |
dtype : numpy.dtype or None |
| 821 |
Data-type of the empty array to save. Used only if 'data' is None. |
| 822 |
returnoffset : bool |
| 823 |
If True and the image data in the file is memory-mappable, return |
| 824 |
the offset and number of bytes of the image data in the file. |
| 825 |
photometric : {'MINISBLACK', 'MINISWHITE', 'RGB', 'PALETTE', 'CFA'} |
| 826 |
The color space of the image data. |
| 827 |
By default, this setting is inferred from the data shape and the |
| 828 |
value of colormap. |
| 829 |
For CFA images, DNG tags must be specified in 'extratags'. |
| 830 |
planarconfig : {'CONTIG', 'SEPARATE'} |
| 831 |
Specifies if samples are stored contiguous or in separate planes. |
| 832 |
By default, this setting is inferred from the data shape. |
| 833 |
If this parameter is set, extra samples are used to store grayscale |
| 834 |
images. |
| 835 |
'CONTIG': last dimension contains samples. |
| 836 |
'SEPARATE': third last dimension contains samples. |
| 837 |
tile : tuple of int |
| 838 |
The shape (depth, length, width) of image tiles to write. |
| 839 |
If None (default), image data are written in strips. |
| 840 |
The tile length and width must be a multiple of 16. |
| 841 |
If the tile depth is provided, the SGI ImageDepth and TileDepth |
| 842 |
tags are used to save volume data. |
| 843 |
Unless a single tile is used, tiles cannot be used to write |
| 844 |
contiguous files. |
| 845 |
Few software can read the SGI format, e.g. MeVisLab. |
| 846 |
contiguous : bool |
| 847 |
If True (default) and the data and parameters are compatible with |
| 848 |
previous ones, if any, the image data are stored contiguously after |
| 849 |
the previous one. Parameters 'photometric' and 'planarconfig' |
| 850 |
are ignored. Parameters 'description', datetime', and 'extratags' |
| 851 |
are written to the first page of a contiguous series only. |
| 852 |
align : int |
| 853 |
Byte boundary on which to align the image data in the file. |
| 854 |
Default 16. Use mmap.ALLOCATIONGRANULARITY for memory-mapped data. |
| 855 |
Following contiguous writes are not aligned. |
| 856 |
truncate : bool |
| 857 |
If True, only write the first page including shape metadata if |
| 858 |
possible (uncompressed, contiguous, not tiled). |
| 859 |
Other TIFF readers will only be able to read part of the data. |
| 860 |
compress : int or 'LZMA', 'ZSTD' |
| 861 |
Values from 0 to 9 controlling the level of zlib compression. |
| 862 |
If 0 (default), data are written uncompressed. |
| 863 |
Compression cannot be used to write contiguous files. |
| 864 |
If 'LZMA' or 'ZSTD', LZMA or ZSTD compression is used, which is |
| 865 |
not available on all platforms. |
| 866 |
rowsperstrip : int |
| 867 |
The number of rows per strip used for compression. |
| 868 |
Uncompressed data are written in one strip per plane. |
| 869 |
predictor : bool |
| 870 |
If True, apply horizontal differencing to integer type images |
| 871 |
before compression. |
| 872 |
colormap : numpy.ndarray |
| 873 |
RGB color values for the corresponding data value. |
| 874 |
Must be of shape (3, 2**(data.itemsize*8)) and dtype uint16. |
| 875 |
description : str |
| 876 |
The subject of the image. Must be 7-bit ASCII. Cannot be used with |
| 877 |
the ImageJ format. Saved with the first page only. |
| 878 |
datetime : datetime |
| 879 |
Date and time of image creation in '%Y:%m:%d %H:%M:%S' format. |
| 880 |
If None (default), the current date and time is used. |
| 881 |
Saved with the first page only. |
| 882 |
resolution : (float, float[, str]) or ((int, int), (int, int)[, str]) |
| 883 |
X and Y resolutions in pixels per resolution unit as float or |
| 884 |
rational numbers. A third, optional parameter specifies the |
| 885 |
resolution unit, which must be None (default for ImageJ), |
| 886 |
'INCH' (default), or 'CENTIMETER'. |
| 887 |
software : str |
| 888 |
Name of the software used to create the file. Must be 7-bit ASCII. |
| 889 |
Saved with the first page only. |
| 890 |
metadata : dict |
| 891 |
Additional meta data to be saved along with shape information |
| 892 |
in JSON or ImageJ formats in an ImageDescription tag. |
| 893 |
If None, do not write a second ImageDescription tag. |
| 894 |
Strings must be 7-bit ASCII. Saved with the first page only. |
| 895 |
ijmetadata : dict |
| 896 |
Additional meta data to be saved in application specific |
| 897 |
IJMetadata and IJMetadataByteCounts tags. Refer to the |
| 898 |
imagej_metadata_tags function for valid keys and values. |
| 899 |
Saved with the first page only. |
| 900 |
extratags : sequence of tuples |
| 901 |
Additional tags as [(code, dtype, count, value, writeonce)]. |
| 902 |
|
| 903 |
code : int |
| 904 |
The TIFF tag Id. |
| 905 |
dtype : str |
| 906 |
Data type of items in 'value' in Python struct format. |
| 907 |
One of B, s, H, I, 2I, b, h, i, 2i, f, d, Q, or q. |
| 908 |
count : int |
| 909 |
Number of data values. Not used for string or byte string |
| 910 |
values. |
| 911 |
value : sequence |
| 912 |
'Count' values compatible with 'dtype'. |
| 913 |
Byte strings must contain count values of dtype packed as |
| 914 |
binary data. |
| 915 |
writeonce : bool |
| 916 |
If True, the tag is written to the first page only. |
| 917 |
|
| 918 |
""" |
| 919 |
|
| 920 |
fh = self._fh |
| 921 |
byteorder = self._byteorder |
| 922 |
|
| 923 |
if data is None: |
| 924 |
if compress: |
| 925 |
raise ValueError("cannot save compressed empty file") |
| 926 |
datashape = shape |
| 927 |
datadtype = numpy.dtype(dtype).newbyteorder(byteorder) |
| 928 |
datadtypechar = datadtype.char |
| 929 |
else: |
| 930 |
data = numpy.asarray(data, byteorder + data.dtype.char, "C") |
| 931 |
if data.size == 0: |
| 932 |
raise ValueError("cannot save empty array") |
| 933 |
datashape = data.shape |
| 934 |
datadtype = data.dtype |
| 935 |
datadtypechar = data.dtype.char |
| 936 |
|
| 937 |
returnoffset = returnoffset and datadtype.isnative |
| 938 |
bilevel = datadtypechar == "?" |
| 939 |
if bilevel: |
| 940 |
index = -1 if datashape[-1] > 1 else -2 |
| 941 |
datasize = product(datashape[:index]) |
| 942 |
if datashape[index] % 8: |
| 943 |
datasize *= datashape[index] // 8 + 1 |
| 944 |
else: |
| 945 |
datasize *= datashape[index] // 8 |
| 946 |
else: |
| 947 |
datasize = product(datashape) * datadtype.itemsize |
| 948 |
|
| 949 |
|
| 950 |
self._truncate = bool(truncate) |
| 951 |
if self._datashape: |
| 952 |
if ( |
| 953 |
not contiguous |
| 954 |
or self._datashape[1:] != datashape |
| 955 |
or self._datadtype != datadtype |
| 956 |
or (compress and self._tags) |
| 957 |
or tile |
| 958 |
or not numpy.array_equal(colormap, self._colormap) |
| 959 |
): |
| 960 |
|
| 961 |
self._write_remaining_pages() |
| 962 |
self._write_image_description() |
| 963 |
self._truncate = False |
| 964 |
self._descriptionoffset = 0 |
| 965 |
self._descriptionlenoffset = 0 |
| 966 |
self._datashape = None |
| 967 |
self._colormap = None |
| 968 |
if self._imagej: |
| 969 |
raise ValueError("ImageJ does not support non-contiguous data") |
| 970 |
else: |
| 971 |
|
| 972 |
self._datashape = (self._datashape[0] + 1,) + datashape |
| 973 |
if not compress: |
| 974 |
|
| 975 |
offset = fh.tell() |
| 976 |
if data is None: |
| 977 |
fh.write_empty(datasize) |
| 978 |
else: |
| 979 |
fh.write_array(data) |
| 980 |
if returnoffset: |
| 981 |
return offset, datasize |
| 982 |
return |
| 983 |
|
| 984 |
input_shape = datashape |
| 985 |
tagnoformat = self._tagnoformat |
| 986 |
valueformat = self._valueformat |
| 987 |
offsetformat = self._offsetformat |
| 988 |
offsetsize = self._offsetsize |
| 989 |
tagsize = self._tagsize |
| 990 |
|
| 991 |
MINISBLACK = TIFF.PHOTOMETRIC.MINISBLACK |
| 992 |
RGB = TIFF.PHOTOMETRIC.RGB |
| 993 |
CFA = TIFF.PHOTOMETRIC.CFA |
| 994 |
PALETTE = TIFF.PHOTOMETRIC.PALETTE |
| 995 |
CONTIG = TIFF.PLANARCONFIG.CONTIG |
| 996 |
SEPARATE = TIFF.PLANARCONFIG.SEPARATE |
| 997 |
|
| 998 |
|
| 999 |
if photometric is not None: |
| 1000 |
photometric = enumarg(TIFF.PHOTOMETRIC, photometric) |
| 1001 |
if planarconfig: |
| 1002 |
planarconfig = enumarg(TIFF.PLANARCONFIG, planarconfig) |
| 1003 |
if not compress: |
| 1004 |
compress = False |
| 1005 |
compresstag = 1 |
| 1006 |
predictor = False |
| 1007 |
else: |
| 1008 |
if isinstance(compress, (tuple, list)): |
| 1009 |
compress, compresslevel = compress |
| 1010 |
elif isinstance(compress, int): |
| 1011 |
compress, compresslevel = "ADOBE_DEFLATE", int(compress) |
| 1012 |
if not 0 <= compresslevel <= 9: |
| 1013 |
raise ValueError("invalid compression level %s" % compress) |
| 1014 |
else: |
| 1015 |
compresslevel = None |
| 1016 |
compress = compress.upper() |
| 1017 |
compresstag = enumarg(TIFF.COMPRESSION, compress) |
| 1018 |
|
| 1019 |
|
| 1020 |
if self._imagej: |
| 1021 |
if compress in ("LZMA", "ZSTD"): |
| 1022 |
raise ValueError("ImageJ cannot handle LZMA or ZSTD compression") |
| 1023 |
if description: |
| 1024 |
warnings.warn("not writing description to ImageJ file") |
| 1025 |
description = None |
| 1026 |
volume = False |
| 1027 |
if datadtypechar not in "BHhf": |
| 1028 |
raise ValueError("ImageJ does not support data type %s" % datadtypechar) |
| 1029 |
ijrgb = photometric == RGB if photometric else None |
| 1030 |
if datadtypechar not in "B": |
| 1031 |
ijrgb = False |
| 1032 |
ijshape = imagej_shape(datashape, ijrgb) |
| 1033 |
if ijshape[-1] in (3, 4): |
| 1034 |
photometric = RGB |
| 1035 |
if datadtypechar not in "B": |
| 1036 |
raise ValueError( |
| 1037 |
"ImageJ does not support data type %s " |
| 1038 |
"for RGB" % datadtypechar |
| 1039 |
) |
| 1040 |
elif photometric is None: |
| 1041 |
photometric = MINISBLACK |
| 1042 |
planarconfig = None |
| 1043 |
if planarconfig == SEPARATE: |
| 1044 |
raise ValueError("ImageJ does not support planar images") |
| 1045 |
else: |
| 1046 |
planarconfig = CONTIG if ijrgb else None |
| 1047 |
|
| 1048 |
|
| 1049 |
if compress: |
| 1050 |
if compresslevel is None: |
| 1051 |
compressor, compresslevel = TIFF.COMPESSORS[compresstag] |
| 1052 |
else: |
| 1053 |
compressor, _ = TIFF.COMPESSORS[compresstag] |
| 1054 |
compresslevel = int(compresslevel) |
| 1055 |
if predictor: |
| 1056 |
if datadtype.kind not in "iu": |
| 1057 |
raise ValueError("prediction not implemented for %s" % datadtype) |
| 1058 |
|
| 1059 |
def compress(data, level=compresslevel): |
| 1060 |
|
| 1061 |
diff = numpy.diff(data, axis=-2) |
| 1062 |
data = numpy.insert(diff, 0, data[..., 0, :], axis=-2) |
| 1063 |
return compressor(data, level) |
| 1064 |
|
| 1065 |
else: |
| 1066 |
|
| 1067 |
def compress(data, level=compresslevel): |
| 1068 |
return compressor(data, level) |
| 1069 |
|
| 1070 |
|
| 1071 |
if colormap is not None: |
| 1072 |
if datadtypechar not in "BH": |
| 1073 |
raise ValueError("invalid data dtype for palette mode") |
| 1074 |
colormap = numpy.asarray(colormap, dtype=byteorder + "H") |
| 1075 |
if colormap.shape != (3, 2 ** (datadtype.itemsize * 8)): |
| 1076 |
raise ValueError("invalid color map shape") |
| 1077 |
self._colormap = colormap |
| 1078 |
|
| 1079 |
|
| 1080 |
if tile: |
| 1081 |
tile = tuple(int(i) for i in tile[:3]) |
| 1082 |
volume = len(tile) == 3 |
| 1083 |
if ( |
| 1084 |
len(tile) < 2 |
| 1085 |
or tile[-1] % 16 |
| 1086 |
or tile[-2] % 16 |
| 1087 |
or any(i < 1 for i in tile) |
| 1088 |
): |
| 1089 |
raise ValueError("invalid tile shape") |
| 1090 |
else: |
| 1091 |
tile = () |
| 1092 |
volume = False |
| 1093 |
|
| 1094 |
|
| 1095 |
|
| 1096 |
datashape = reshape_nd(datashape, 3 if photometric == RGB else 2) |
| 1097 |
shape = datashape |
| 1098 |
ndim = len(datashape) |
| 1099 |
|
| 1100 |
samplesperpixel = 1 |
| 1101 |
extrasamples = 0 |
| 1102 |
if volume and ndim < 3: |
| 1103 |
volume = False |
| 1104 |
if colormap is not None: |
| 1105 |
photometric = PALETTE |
| 1106 |
planarconfig = None |
| 1107 |
if photometric is None: |
| 1108 |
photometric = MINISBLACK |
| 1109 |
if bilevel: |
| 1110 |
photometric = TIFF.PHOTOMETRIC.MINISWHITE |
| 1111 |
elif planarconfig == CONTIG: |
| 1112 |
if ndim > 2 and shape[-1] in (3, 4): |
| 1113 |
photometric = RGB |
| 1114 |
elif planarconfig == SEPARATE: |
| 1115 |
if volume and ndim > 3 and shape[-4] in (3, 4): |
| 1116 |
photometric = RGB |
| 1117 |
elif ndim > 2 and shape[-3] in (3, 4): |
| 1118 |
photometric = RGB |
| 1119 |
elif ndim > 2 and shape[-1] in (3, 4): |
| 1120 |
photometric = RGB |
| 1121 |
elif self._imagej: |
| 1122 |
photometric = MINISBLACK |
| 1123 |
elif volume and ndim > 3 and shape[-4] in (3, 4): |
| 1124 |
photometric = RGB |
| 1125 |
elif ndim > 2 and shape[-3] in (3, 4): |
| 1126 |
photometric = RGB |
| 1127 |
if planarconfig and len(shape) <= (3 if volume else 2): |
| 1128 |
planarconfig = None |
| 1129 |
photometric = MINISBLACK |
| 1130 |
if photometric == RGB: |
| 1131 |
if len(shape) < 3: |
| 1132 |
raise ValueError("not a RGB(A) image") |
| 1133 |
if len(shape) < 4: |
| 1134 |
volume = False |
| 1135 |
if planarconfig is None: |
| 1136 |
if shape[-1] in (3, 4): |
| 1137 |
planarconfig = CONTIG |
| 1138 |
elif shape[-4 if volume else -3] in (3, 4): |
| 1139 |
planarconfig = SEPARATE |
| 1140 |
elif shape[-1] > shape[-4 if volume else -3]: |
| 1141 |
planarconfig = SEPARATE |
| 1142 |
else: |
| 1143 |
planarconfig = CONTIG |
| 1144 |
if planarconfig == CONTIG: |
| 1145 |
datashape = (-1, 1) + shape[(-4 if volume else -3) :] |
| 1146 |
samplesperpixel = datashape[-1] |
| 1147 |
else: |
| 1148 |
datashape = (-1,) + shape[(-4 if volume else -3) :] + (1,) |
| 1149 |
samplesperpixel = datashape[1] |
| 1150 |
if samplesperpixel > 3: |
| 1151 |
extrasamples = samplesperpixel - 3 |
| 1152 |
elif photometric == CFA: |
| 1153 |
if len(shape) != 2: |
| 1154 |
raise ValueError("invalid CFA image") |
| 1155 |
volume = False |
| 1156 |
planarconfig = None |
| 1157 |
datashape = (-1, 1) + shape[-2:] + (1,) |
| 1158 |
if 50706 not in (et[0] for et in extratags): |
| 1159 |
raise ValueError("must specify DNG tags for CFA image") |
| 1160 |
elif planarconfig and len(shape) > (3 if volume else 2): |
| 1161 |
if planarconfig == CONTIG: |
| 1162 |
datashape = (-1, 1) + shape[(-4 if volume else -3) :] |
| 1163 |
samplesperpixel = datashape[-1] |
| 1164 |
else: |
| 1165 |
datashape = (-1,) + shape[(-4 if volume else -3) :] + (1,) |
| 1166 |
samplesperpixel = datashape[1] |
| 1167 |
extrasamples = samplesperpixel - 1 |
| 1168 |
else: |
| 1169 |
planarconfig = None |
| 1170 |
|
| 1171 |
while len(shape) > 2 and shape[-1] == 1: |
| 1172 |
shape = shape[:-1] |
| 1173 |
if len(shape) < 3: |
| 1174 |
volume = False |
| 1175 |
datashape = (-1, 1) + shape[(-3 if volume else -2) :] + (1,) |
| 1176 |
|
| 1177 |
|
| 1178 |
assert len(datashape) in (5, 6) |
| 1179 |
if len(datashape) == 5: |
| 1180 |
datashape = datashape[:2] + (1,) + datashape[2:] |
| 1181 |
if datashape[0] == -1: |
| 1182 |
s0 = product(input_shape) // product(datashape[1:]) |
| 1183 |
datashape = (s0,) + datashape[1:] |
| 1184 |
shape = datashape |
| 1185 |
if data is not None: |
| 1186 |
data = data.reshape(shape) |
| 1187 |
|
| 1188 |
if tile and not volume: |
| 1189 |
tile = (1, tile[-2], tile[-1]) |
| 1190 |
|
| 1191 |
if photometric == PALETTE: |
| 1192 |
if samplesperpixel != 1 or extrasamples or shape[1] != 1 or shape[-1] != 1: |
| 1193 |
raise ValueError("invalid data shape for palette mode") |
| 1194 |
|
| 1195 |
if photometric == RGB and samplesperpixel == 2: |
| 1196 |
raise ValueError("not a RGB image (samplesperpixel=2)") |
| 1197 |
|
| 1198 |
if bilevel: |
| 1199 |
if compress: |
| 1200 |
raise ValueError("cannot save compressed bilevel image") |
| 1201 |
if tile: |
| 1202 |
raise ValueError("cannot save tiled bilevel image") |
| 1203 |
if photometric not in (0, 1): |
| 1204 |
raise ValueError("cannot save bilevel image as %s" % str(photometric)) |
| 1205 |
datashape = list(datashape) |
| 1206 |
if datashape[-2] % 8: |
| 1207 |
datashape[-2] = datashape[-2] // 8 + 1 |
| 1208 |
else: |
| 1209 |
datashape[-2] = datashape[-2] // 8 |
| 1210 |
datashape = tuple(datashape) |
| 1211 |
assert datasize == product(datashape) |
| 1212 |
if data is not None: |
| 1213 |
data = numpy.packbits(data, axis=-2) |
| 1214 |
assert datashape[-2] == data.shape[-2] |
| 1215 |
|
| 1216 |
bytestr = ( |
| 1217 |
bytes |
| 1218 |
if sys.version[0] == "2" |
| 1219 |
else (lambda x: bytes(x, "ascii") if isinstance(x, str) else x) |
| 1220 |
) |
| 1221 |
tags = [] |
| 1222 |
|
| 1223 |
strip_or_tile = "Tile" if tile else "Strip" |
| 1224 |
tagbytecounts = TIFF.TAG_NAMES[strip_or_tile + "ByteCounts"] |
| 1225 |
tag_offsets = TIFF.TAG_NAMES[strip_or_tile + "Offsets"] |
| 1226 |
self._tagoffsets = tag_offsets |
| 1227 |
|
| 1228 |
def pack(fmt, *val): |
| 1229 |
return struct.pack(byteorder + fmt, *val) |
| 1230 |
|
| 1231 |
def addtag(code, dtype, count, value, writeonce=False): |
| 1232 |
|
| 1233 |
|
| 1234 |
code = int(TIFF.TAG_NAMES.get(code, code)) |
| 1235 |
try: |
| 1236 |
tifftype = TIFF.DATA_DTYPES[dtype] |
| 1237 |
except KeyError: |
| 1238 |
raise ValueError("unknown dtype %s" % dtype) |
| 1239 |
rawcount = count |
| 1240 |
|
| 1241 |
if dtype == "s": |
| 1242 |
|
| 1243 |
value = bytestr(value) + b"\0" |
| 1244 |
count = rawcount = len(value) |
| 1245 |
rawcount = value.find(b"\0\0") |
| 1246 |
if rawcount < 0: |
| 1247 |
rawcount = count |
| 1248 |
else: |
| 1249 |
rawcount += 1 |
| 1250 |
value = (value,) |
| 1251 |
elif isinstance(value, bytes): |
| 1252 |
|
| 1253 |
dtsize = struct.calcsize(dtype) |
| 1254 |
if len(value) % dtsize: |
| 1255 |
raise ValueError("invalid packed binary data") |
| 1256 |
count = len(value) // dtsize |
| 1257 |
if len(dtype) > 1: |
| 1258 |
count *= int(dtype[:-1]) |
| 1259 |
dtype = dtype[-1] |
| 1260 |
ifdentry = [pack("HH", code, tifftype), pack(offsetformat, rawcount)] |
| 1261 |
ifdvalue = None |
| 1262 |
if struct.calcsize(dtype) * count <= offsetsize: |
| 1263 |
|
| 1264 |
if isinstance(value, bytes): |
| 1265 |
ifdentry.append(pack(valueformat, value)) |
| 1266 |
elif count == 1: |
| 1267 |
if isinstance(value, (tuple, list, numpy.ndarray)): |
| 1268 |
value = value[0] |
| 1269 |
ifdentry.append(pack(valueformat, pack(dtype, value))) |
| 1270 |
else: |
| 1271 |
ifdentry.append(pack(valueformat, pack(str(count) + dtype, *value))) |
| 1272 |
else: |
| 1273 |
|
| 1274 |
ifdentry.append(pack(offsetformat, 0)) |
| 1275 |
if isinstance(value, bytes): |
| 1276 |
ifdvalue = value |
| 1277 |
elif isinstance(value, numpy.ndarray): |
| 1278 |
assert value.size == count |
| 1279 |
assert value.dtype.char == dtype |
| 1280 |
ifdvalue = value.tostring() |
| 1281 |
elif isinstance(value, (tuple, list)): |
| 1282 |
ifdvalue = pack(str(count) + dtype, *value) |
| 1283 |
else: |
| 1284 |
ifdvalue = pack(dtype, value) |
| 1285 |
tags.append((code, b"".join(ifdentry), ifdvalue, writeonce)) |
| 1286 |
|
| 1287 |
def rational(arg, max_denominator=1000000): |
| 1288 |
""" "Return nominator and denominator from float or two integers.""" |
| 1289 |
from fractions import Fraction |
| 1290 |
|
| 1291 |
try: |
| 1292 |
f = Fraction.from_float(arg) |
| 1293 |
except TypeError: |
| 1294 |
f = Fraction(arg[0], arg[1]) |
| 1295 |
f = f.limit_denominator(max_denominator) |
| 1296 |
return f.numerator, f.denominator |
| 1297 |
|
| 1298 |
if description: |
| 1299 |
|
| 1300 |
addtag("ImageDescription", "s", 0, description, writeonce=True) |
| 1301 |
|
| 1302 |
|
| 1303 |
self._metadata = {} if not metadata else metadata.copy() |
| 1304 |
if self._imagej: |
| 1305 |
description = imagej_description( |
| 1306 |
input_shape, |
| 1307 |
shape[-1] in (3, 4), |
| 1308 |
self._colormap is not None, |
| 1309 |
**self._metadata, |
| 1310 |
) |
| 1311 |
elif metadata or metadata == {}: |
| 1312 |
if self._truncate: |
| 1313 |
self._metadata.update(truncated=True) |
| 1314 |
description = json_description(input_shape, **self._metadata) |
| 1315 |
else: |
| 1316 |
description = None |
| 1317 |
if description: |
| 1318 |
|
| 1319 |
|
| 1320 |
description = str2bytes(description, "ascii") |
| 1321 |
description += b"\0" * 64 |
| 1322 |
self._descriptionlen = len(description) |
| 1323 |
addtag("ImageDescription", "s", 0, description, writeonce=True) |
| 1324 |
|
| 1325 |
if software: |
| 1326 |
addtag("Software", "s", 0, software, writeonce=True) |
| 1327 |
if datetime is None: |
| 1328 |
datetime = self._now() |
| 1329 |
addtag( |
| 1330 |
"DateTime", "s", 0, datetime.strftime("%Y:%m:%d %H:%M:%S"), writeonce=True |
| 1331 |
) |
| 1332 |
addtag("Compression", "H", 1, compresstag) |
| 1333 |
if predictor: |
| 1334 |
addtag("Predictor", "H", 1, 2) |
| 1335 |
addtag("ImageWidth", "I", 1, shape[-2]) |
| 1336 |
addtag("ImageLength", "I", 1, shape[-3]) |
| 1337 |
if tile: |
| 1338 |
addtag("TileWidth", "I", 1, tile[-1]) |
| 1339 |
addtag("TileLength", "I", 1, tile[-2]) |
| 1340 |
if tile[0] > 1: |
| 1341 |
addtag("ImageDepth", "I", 1, shape[-4]) |
| 1342 |
addtag("TileDepth", "I", 1, tile[0]) |
| 1343 |
addtag("NewSubfileType", "I", 1, 0) |
| 1344 |
if not bilevel: |
| 1345 |
sampleformat = {"u": 1, "i": 2, "f": 3, "c": 6}[datadtype.kind] |
| 1346 |
addtag( |
| 1347 |
"SampleFormat", "H", samplesperpixel, (sampleformat,) * samplesperpixel |
| 1348 |
) |
| 1349 |
addtag("PhotometricInterpretation", "H", 1, photometric.value) |
| 1350 |
if colormap is not None: |
| 1351 |
addtag("ColorMap", "H", colormap.size, colormap) |
| 1352 |
addtag("SamplesPerPixel", "H", 1, samplesperpixel) |
| 1353 |
if bilevel: |
| 1354 |
pass |
| 1355 |
elif planarconfig and samplesperpixel > 1: |
| 1356 |
addtag("PlanarConfiguration", "H", 1, planarconfig.value) |
| 1357 |
addtag( |
| 1358 |
"BitsPerSample", |
| 1359 |
"H", |
| 1360 |
samplesperpixel, |
| 1361 |
(datadtype.itemsize * 8,) * samplesperpixel, |
| 1362 |
) |
| 1363 |
else: |
| 1364 |
addtag("BitsPerSample", "H", 1, datadtype.itemsize * 8) |
| 1365 |
if extrasamples: |
| 1366 |
if photometric == RGB and extrasamples == 1: |
| 1367 |
addtag("ExtraSamples", "H", 1, 1) |
| 1368 |
else: |
| 1369 |
addtag("ExtraSamples", "H", extrasamples, (0,) * extrasamples) |
| 1370 |
if resolution is not None: |
| 1371 |
addtag("XResolution", "2I", 1, rational(resolution[0])) |
| 1372 |
addtag("YResolution", "2I", 1, rational(resolution[1])) |
| 1373 |
if len(resolution) > 2: |
| 1374 |
unit = resolution[2] |
| 1375 |
unit = 1 if unit is None else enumarg(TIFF.RESUNIT, unit) |
| 1376 |
elif self._imagej: |
| 1377 |
unit = 1 |
| 1378 |
else: |
| 1379 |
unit = 2 |
| 1380 |
addtag("ResolutionUnit", "H", 1, unit) |
| 1381 |
elif not self._imagej: |
| 1382 |
addtag("XResolution", "2I", 1, (1, 1)) |
| 1383 |
addtag("YResolution", "2I", 1, (1, 1)) |
| 1384 |
addtag("ResolutionUnit", "H", 1, 1) |
| 1385 |
if ijmetadata: |
| 1386 |
for t in imagej_metadata_tags(ijmetadata, byteorder): |
| 1387 |
addtag(*t) |
| 1388 |
|
| 1389 |
contiguous = not compress |
| 1390 |
if tile: |
| 1391 |
|
| 1392 |
tiles = ( |
| 1393 |
(shape[2] + tile[0] - 1) // tile[0], |
| 1394 |
(shape[3] + tile[1] - 1) // tile[1], |
| 1395 |
(shape[4] + tile[2] - 1) // tile[2], |
| 1396 |
) |
| 1397 |
numtiles = product(tiles) * shape[1] |
| 1398 |
stripbytecounts = [ |
| 1399 |
product(tile) * shape[-1] * datadtype.itemsize |
| 1400 |
] * numtiles |
| 1401 |
addtag(tagbytecounts, offsetformat, numtiles, stripbytecounts) |
| 1402 |
addtag(tag_offsets, offsetformat, numtiles, [0] * numtiles) |
| 1403 |
contiguous = contiguous and product(tiles) == 1 |
| 1404 |
if not contiguous: |
| 1405 |
|
| 1406 |
chunk = numpy.empty(tile + (shape[-1],), dtype=datadtype) |
| 1407 |
elif contiguous: |
| 1408 |
|
| 1409 |
if bilevel: |
| 1410 |
stripbytecounts = [product(datashape[2:])] * shape[1] |
| 1411 |
else: |
| 1412 |
stripbytecounts = [product(datashape[2:]) * datadtype.itemsize] * shape[ |
| 1413 |
1 |
| 1414 |
] |
| 1415 |
addtag(tagbytecounts, offsetformat, shape[1], stripbytecounts) |
| 1416 |
addtag(tag_offsets, offsetformat, shape[1], [0] * shape[1]) |
| 1417 |
addtag("RowsPerStrip", "I", 1, shape[-3]) |
| 1418 |
else: |
| 1419 |
|
| 1420 |
rowsize = product(shape[-2:]) * datadtype.itemsize |
| 1421 |
if rowsperstrip is None: |
| 1422 |
rowsperstrip = 65536 // rowsize |
| 1423 |
if rowsperstrip < 1: |
| 1424 |
rowsperstrip = 1 |
| 1425 |
elif rowsperstrip > shape[-3]: |
| 1426 |
rowsperstrip = shape[-3] |
| 1427 |
addtag("RowsPerStrip", "I", 1, rowsperstrip) |
| 1428 |
|
| 1429 |
numstrips = (shape[-3] + rowsperstrip - 1) // rowsperstrip |
| 1430 |
numstrips *= shape[1] |
| 1431 |
stripbytecounts = [0] * numstrips |
| 1432 |
addtag(tagbytecounts, offsetformat, numstrips, [0] * numstrips) |
| 1433 |
addtag(tag_offsets, offsetformat, numstrips, [0] * numstrips) |
| 1434 |
|
| 1435 |
if data is None and not contiguous: |
| 1436 |
raise ValueError("cannot write non-contiguous empty file") |
| 1437 |
|
| 1438 |
|
| 1439 |
for t in extratags: |
| 1440 |
addtag(*t) |
| 1441 |
|
| 1442 |
|
| 1443 |
|
| 1444 |
|
| 1445 |
tags = sorted(tags, key=lambda x: x[0]) |
| 1446 |
|
| 1447 |
if not (self._bigtiff or self._imagej) and (fh.tell() + datasize > 2**31 - 1): |
| 1448 |
raise ValueError("data too large for standard TIFF file") |
| 1449 |
|
| 1450 |
|
| 1451 |
|
| 1452 |
for pageindex in range(1 if contiguous else shape[0]): |
| 1453 |
|
| 1454 |
pos = fh.tell() |
| 1455 |
if pos % 2: |
| 1456 |
|
| 1457 |
fh.write(b"\0") |
| 1458 |
pos += 1 |
| 1459 |
fh.seek(self._ifdoffset) |
| 1460 |
fh.write(pack(offsetformat, pos)) |
| 1461 |
fh.seek(pos) |
| 1462 |
|
| 1463 |
|
| 1464 |
fh.write(pack(tagnoformat, len(tags))) |
| 1465 |
tag_offset = fh.tell() |
| 1466 |
fh.write(b"".join(t[1] for t in tags)) |
| 1467 |
self._ifdoffset = fh.tell() |
| 1468 |
fh.write(pack(offsetformat, 0)) |
| 1469 |
|
| 1470 |
|
| 1471 |
for tagindex, tag in enumerate(tags): |
| 1472 |
if tag[2]: |
| 1473 |
pos = fh.tell() |
| 1474 |
if pos % 2: |
| 1475 |
|
| 1476 |
fh.write(b"\0") |
| 1477 |
pos += 1 |
| 1478 |
fh.seek(tag_offset + tagindex * tagsize + offsetsize + 4) |
| 1479 |
fh.write(pack(offsetformat, pos)) |
| 1480 |
fh.seek(pos) |
| 1481 |
if tag[0] == tag_offsets: |
| 1482 |
stripoffsetsoffset = pos |
| 1483 |
elif tag[0] == tagbytecounts: |
| 1484 |
strip_bytecounts_offset = pos |
| 1485 |
elif tag[0] == 270 and tag[2].endswith(b"\0\0\0\0"): |
| 1486 |
|
| 1487 |
self._descriptionoffset = pos |
| 1488 |
self._descriptionlenoffset = tag_offset + tagindex * tagsize + 4 |
| 1489 |
fh.write(tag[2]) |
| 1490 |
|
| 1491 |
|
| 1492 |
data_offset = fh.tell() |
| 1493 |
skip = align - data_offset % align |
| 1494 |
fh.seek(skip, 1) |
| 1495 |
data_offset += skip |
| 1496 |
if contiguous: |
| 1497 |
if data is None: |
| 1498 |
fh.write_empty(datasize) |
| 1499 |
else: |
| 1500 |
fh.write_array(data) |
| 1501 |
elif tile: |
| 1502 |
if data is None: |
| 1503 |
fh.write_empty(numtiles * stripbytecounts[0]) |
| 1504 |
else: |
| 1505 |
stripindex = 0 |
| 1506 |
for plane in data[pageindex]: |
| 1507 |
for tz in range(tiles[0]): |
| 1508 |
for ty in range(tiles[1]): |
| 1509 |
for tx in range(tiles[2]): |
| 1510 |
c0 = min(tile[0], shape[2] - tz * tile[0]) |
| 1511 |
c1 = min(tile[1], shape[3] - ty * tile[1]) |
| 1512 |
c2 = min(tile[2], shape[4] - tx * tile[2]) |
| 1513 |
chunk[c0:, c1:, c2:] = 0 |
| 1514 |
chunk[:c0, :c1, :c2] = plane[ |
| 1515 |
tz * tile[0] : tz * tile[0] + c0, |
| 1516 |
ty * tile[1] : ty * tile[1] + c1, |
| 1517 |
tx * tile[2] : tx * tile[2] + c2, |
| 1518 |
] |
| 1519 |
if compress: |
| 1520 |
t = compress(chunk) |
| 1521 |
fh.write(t) |
| 1522 |
stripbytecounts[stripindex] = len(t) |
| 1523 |
stripindex += 1 |
| 1524 |
else: |
| 1525 |
fh.write_array(chunk) |
| 1526 |
fh.flush() |
| 1527 |
elif compress: |
| 1528 |
|
| 1529 |
assert data.shape[2] == 1 |
| 1530 |
numstrips = (shape[-3] + rowsperstrip - 1) // rowsperstrip |
| 1531 |
stripindex = 0 |
| 1532 |
for plane in data[pageindex]: |
| 1533 |
for i in range(numstrips): |
| 1534 |
strip = plane[0, i * rowsperstrip : (i + 1) * rowsperstrip] |
| 1535 |
strip = compress(strip) |
| 1536 |
fh.write(strip) |
| 1537 |
stripbytecounts[stripindex] = len(strip) |
| 1538 |
stripindex += 1 |
| 1539 |
|
| 1540 |
|
| 1541 |
pos = fh.tell() |
| 1542 |
for tagindex, tag in enumerate(tags): |
| 1543 |
if tag[0] == tag_offsets: |
| 1544 |
if tag[2]: |
| 1545 |
fh.seek(stripoffsetsoffset) |
| 1546 |
strip_offset = data_offset |
| 1547 |
for size in stripbytecounts: |
| 1548 |
fh.write(pack(offsetformat, strip_offset)) |
| 1549 |
strip_offset += size |
| 1550 |
else: |
| 1551 |
fh.seek(tag_offset + tagindex * tagsize + offsetsize + 4) |
| 1552 |
fh.write(pack(offsetformat, data_offset)) |
| 1553 |
elif tag[0] == tagbytecounts: |
| 1554 |
if compress: |
| 1555 |
if tag[2]: |
| 1556 |
fh.seek(strip_bytecounts_offset) |
| 1557 |
for size in stripbytecounts: |
| 1558 |
fh.write(pack(offsetformat, size)) |
| 1559 |
else: |
| 1560 |
fh.seek(tag_offset + tagindex * tagsize + offsetsize + 4) |
| 1561 |
fh.write(pack(offsetformat, stripbytecounts[0])) |
| 1562 |
break |
| 1563 |
fh.seek(pos) |
| 1564 |
fh.flush() |
| 1565 |
|
| 1566 |
|
| 1567 |
if pageindex == 0: |
| 1568 |
tags = [tag for tag in tags if not tag[-1]] |
| 1569 |
|
| 1570 |
self._shape = shape |
| 1571 |
self._datashape = (1,) + input_shape |
| 1572 |
self._datadtype = datadtype |
| 1573 |
self._dataoffset = data_offset |
| 1574 |
self._databytecounts = stripbytecounts |
| 1575 |
|
| 1576 |
if contiguous: |
| 1577 |
|
| 1578 |
self._tags = tags |
| 1579 |
|
| 1580 |
if returnoffset: |
| 1581 |
return data_offset, sum(stripbytecounts) |
| 1582 |
|
| 1583 |
def _write_remaining_pages(self): |
| 1584 |
"""Write outstanding IFDs and tags to file.""" |
| 1585 |
if not self._tags or self._truncate: |
| 1586 |
return |
| 1587 |
|
| 1588 |
fh = self._fh |
| 1589 |
fhpos = fh.tell() |
| 1590 |
if fhpos % 2: |
| 1591 |
fh.write(b"\0") |
| 1592 |
fhpos += 1 |
| 1593 |
byteorder = self._byteorder |
| 1594 |
offsetformat = self._offsetformat |
| 1595 |
offsetsize = self._offsetsize |
| 1596 |
tagnoformat = self._tagnoformat |
| 1597 |
tagsize = self._tagsize |
| 1598 |
dataoffset = self._dataoffset |
| 1599 |
pagedatasize = sum(self._databytecounts) |
| 1600 |
pageno = self._shape[0] * self._datashape[0] - 1 |
| 1601 |
|
| 1602 |
def pack(fmt, *val): |
| 1603 |
return struct.pack(byteorder + fmt, *val) |
| 1604 |
|
| 1605 |
|
| 1606 |
|
| 1607 |
ifd = io.BytesIO() |
| 1608 |
ifd.write(pack(tagnoformat, len(self._tags))) |
| 1609 |
tagoffset = ifd.tell() |
| 1610 |
ifd.write(b"".join(t[1] for t in self._tags)) |
| 1611 |
ifdoffset = ifd.tell() |
| 1612 |
ifd.write(pack(offsetformat, 0)) |
| 1613 |
|
| 1614 |
for tagindex, tag in enumerate(self._tags): |
| 1615 |
offset2value = tagoffset + tagindex * tagsize + offsetsize + 4 |
| 1616 |
if tag[2]: |
| 1617 |
pos = ifd.tell() |
| 1618 |
if pos % 2: |
| 1619 |
ifd.write(b"\0") |
| 1620 |
pos += 1 |
| 1621 |
ifd.seek(offset2value) |
| 1622 |
try: |
| 1623 |
ifd.write(pack(offsetformat, pos + fhpos)) |
| 1624 |
except Exception: |
| 1625 |
if self._imagej: |
| 1626 |
warnings.warn("truncating ImageJ file") |
| 1627 |
self._truncate = True |
| 1628 |
return |
| 1629 |
raise ValueError("data too large for non-BigTIFF file") |
| 1630 |
ifd.seek(pos) |
| 1631 |
ifd.write(tag[2]) |
| 1632 |
if tag[0] == self._tagoffsets: |
| 1633 |
|
| 1634 |
stripoffset2offset = offset2value |
| 1635 |
stripoffset2value = pos |
| 1636 |
elif tag[0] == self._tagoffsets: |
| 1637 |
|
| 1638 |
stripoffset2offset = None |
| 1639 |
stripoffset2value = offset2value |
| 1640 |
|
| 1641 |
if ifd.tell() % 2: |
| 1642 |
ifd.write(b"\0") |
| 1643 |
|
| 1644 |
|
| 1645 |
pos = fh.tell() |
| 1646 |
if not self._bigtiff and pos + ifd.tell() * pageno > 2**32 - 256: |
| 1647 |
if self._imagej: |
| 1648 |
warnings.warn("truncating ImageJ file") |
| 1649 |
self._truncate = True |
| 1650 |
return |
| 1651 |
raise ValueError("data too large for non-BigTIFF file") |
| 1652 |
|
| 1653 |
|
| 1654 |
for _ in range(pageno): |
| 1655 |
|
| 1656 |
pos = fh.tell() |
| 1657 |
fh.seek(self._ifdoffset) |
| 1658 |
fh.write(pack(offsetformat, pos)) |
| 1659 |
fh.seek(pos) |
| 1660 |
self._ifdoffset = pos + ifdoffset |
| 1661 |
|
| 1662 |
dataoffset += pagedatasize |
| 1663 |
if stripoffset2offset is None: |
| 1664 |
ifd.seek(stripoffset2value) |
| 1665 |
ifd.write(pack(offsetformat, dataoffset)) |
| 1666 |
else: |
| 1667 |
ifd.seek(stripoffset2offset) |
| 1668 |
ifd.write(pack(offsetformat, pos + stripoffset2value)) |
| 1669 |
ifd.seek(stripoffset2value) |
| 1670 |
stripoffset = dataoffset |
| 1671 |
for size in self._databytecounts: |
| 1672 |
ifd.write(pack(offsetformat, stripoffset)) |
| 1673 |
stripoffset += size |
| 1674 |
|
| 1675 |
fh.write(ifd.getvalue()) |
| 1676 |
|
| 1677 |
self._tags = None |
| 1678 |
self._datadtype = None |
| 1679 |
self._dataoffset = None |
| 1680 |
self._databytecounts = None |
| 1681 |
|
| 1682 |
|
| 1683 |
def _write_image_description(self): |
| 1684 |
"""Write meta data to ImageDescription tag.""" |
| 1685 |
if ( |
| 1686 |
not self._datashape |
| 1687 |
or self._datashape[0] == 1 |
| 1688 |
or self._descriptionoffset <= 0 |
| 1689 |
): |
| 1690 |
return |
| 1691 |
|
| 1692 |
colormapped = self._colormap is not None |
| 1693 |
if self._imagej: |
| 1694 |
isrgb = self._shape[-1] in (3, 4) |
| 1695 |
description = imagej_description( |
| 1696 |
self._datashape, isrgb, colormapped, **self._metadata |
| 1697 |
) |
| 1698 |
else: |
| 1699 |
description = json_description(self._datashape, **self._metadata) |
| 1700 |
|
| 1701 |
|
| 1702 |
description = description.encode("utf-8") |
| 1703 |
description = description[: self._descriptionlen - 1] |
| 1704 |
pos = self._fh.tell() |
| 1705 |
self._fh.seek(self._descriptionoffset) |
| 1706 |
self._fh.write(description) |
| 1707 |
self._fh.seek(self._descriptionlenoffset) |
| 1708 |
self._fh.write( |
| 1709 |
struct.pack(self._byteorder + self._offsetformat, len(description) + 1) |
| 1710 |
) |
| 1711 |
self._fh.seek(pos) |
| 1712 |
|
| 1713 |
self._descriptionoffset = 0 |
| 1714 |
self._descriptionlenoffset = 0 |
| 1715 |
self._descriptionlen = 0 |
| 1716 |
|
| 1717 |
def _now(self): |
| 1718 |
"""Return current date and time.""" |
| 1719 |
return datetime.datetime.now() |
| 1720 |
|
| 1721 |
def close(self): |
| 1722 |
"""Write remaining pages and close file handle.""" |
| 1723 |
if not self._truncate: |
| 1724 |
self._write_remaining_pages() |
| 1725 |
self._write_image_description() |
| 1726 |
self._fh.close() |
| 1727 |
|
| 1728 |
def __enter__(self): |
| 1729 |
return self |
| 1730 |
|
| 1731 |
def __exit__(self, exc_type, exc_value, traceback): |
| 1732 |
self.close() |
| 1733 |
|
| 1734 |
|
| 1735 |
class TiffFile(object): |
| 1736 |
"""Read image and metadata from TIFF file. |
| 1737 |
|
| 1738 |
TiffFile instances must be closed using the 'close' method, which is |
| 1739 |
automatically called when using the 'with' context manager. |
| 1740 |
|
| 1741 |
Attributes |
| 1742 |
---------- |
| 1743 |
pages : TiffPages |
| 1744 |
Sequence of TIFF pages in file. |
| 1745 |
series : list of TiffPageSeries |
| 1746 |
Sequences of closely related TIFF pages. These are computed |
| 1747 |
from OME, LSM, ImageJ, etc. metadata or based on similarity |
| 1748 |
of page properties such as shape, dtype, and compression. |
| 1749 |
byteorder : '>', '<' |
| 1750 |
The endianness of data in the file. |
| 1751 |
'>': big-endian (Motorola). |
| 1752 |
'>': little-endian (Intel). |
| 1753 |
is_flag : bool |
| 1754 |
If True, file is of a certain format. |
| 1755 |
Flags are: bigtiff, movie, shaped, ome, imagej, stk, lsm, fluoview, |
| 1756 |
nih, vista, 'micromanager, metaseries, mdgel, mediacy, tvips, fei, |
| 1757 |
sem, scn, svs, scanimage, andor, epics, pilatus, qptiff. |
| 1758 |
|
| 1759 |
All attributes are read-only. |
| 1760 |
|
| 1761 |
Examples |
| 1762 |
-------- |
| 1763 |
>>> # read image array from TIFF file |
| 1764 |
>>> imsave('temp.tif', numpy.random.rand(5, 301, 219)) |
| 1765 |
>>> with TiffFile('temp.tif') as tif: |
| 1766 |
... data = tif.asarray() |
| 1767 |
>>> data.shape |
| 1768 |
(5, 301, 219) |
| 1769 |
|
| 1770 |
""" |
| 1771 |
|
| 1772 |
def __init__( |
| 1773 |
self, |
| 1774 |
arg, |
| 1775 |
name=None, |
| 1776 |
offset=None, |
| 1777 |
size=None, |
| 1778 |
multifile=True, |
| 1779 |
movie=None, |
| 1780 |
**kwargs, |
| 1781 |
): |
| 1782 |
"""Initialize instance from file. |
| 1783 |
|
| 1784 |
Parameters |
| 1785 |
---------- |
| 1786 |
arg : str or open file |
| 1787 |
Name of file or open file object. |
| 1788 |
The file objects are closed in TiffFile.close(). |
| 1789 |
name : str |
| 1790 |
Optional name of file in case 'arg' is a file handle. |
| 1791 |
offset : int |
| 1792 |
Optional start position of embedded file. By default, this is |
| 1793 |
the current file position. |
| 1794 |
size : int |
| 1795 |
Optional size of embedded file. By default, this is the number |
| 1796 |
of bytes from the 'offset' to the end of the file. |
| 1797 |
multifile : bool |
| 1798 |
If True (default), series may include pages from multiple files. |
| 1799 |
Currently applies to OME-TIFF only. |
| 1800 |
movie : bool |
| 1801 |
If True, assume that later pages differ from first page only by |
| 1802 |
data offsets and byte counts. Significantly increases speed and |
| 1803 |
reduces memory usage when reading movies with thousands of pages. |
| 1804 |
Enabling this for non-movie files will result in data corruption |
| 1805 |
or crashes. Python 3 only. |
| 1806 |
kwargs : bool |
| 1807 |
'is_ome': If False, disable processing of OME-XML metadata. |
| 1808 |
|
| 1809 |
""" |
| 1810 |
if "fastij" in kwargs: |
| 1811 |
del kwargs["fastij"] |
| 1812 |
raise DeprecationWarning("the fastij option will be removed") |
| 1813 |
for key, value in kwargs.items(): |
| 1814 |
if key[:3] == "is_" and key[3:] in TIFF.FILE_FLAGS: |
| 1815 |
if value is not None and not value: |
| 1816 |
setattr(self, key, bool(value)) |
| 1817 |
else: |
| 1818 |
raise TypeError("unexpected keyword argument: %s" % key) |
| 1819 |
|
| 1820 |
fh = FileHandle(arg, mode="rb", name=name, offset=offset, size=size) |
| 1821 |
self._fh = fh |
| 1822 |
self._multifile = bool(multifile) |
| 1823 |
self._files = {fh.name: self} |
| 1824 |
try: |
| 1825 |
fh.seek(0) |
| 1826 |
try: |
| 1827 |
byteorder = {b"II": "<", b"MM": ">"}[fh.read(2)] |
| 1828 |
except KeyError: |
| 1829 |
raise ValueError("not a TIFF file") |
| 1830 |
sys_byteorder = {"big": ">", "little": "<"}[sys.byteorder] |
| 1831 |
self.isnative = byteorder == sys_byteorder |
| 1832 |
|
| 1833 |
version = struct.unpack(byteorder + "H", fh.read(2))[0] |
| 1834 |
if version == 43: |
| 1835 |
|
| 1836 |
self.is_bigtiff = True |
| 1837 |
offsetsize, zero = struct.unpack(byteorder + "HH", fh.read(4)) |
| 1838 |
if zero or offsetsize != 8: |
| 1839 |
raise ValueError("invalid BigTIFF file") |
| 1840 |
self.byteorder = byteorder |
| 1841 |
self.offsetsize = 8 |
| 1842 |
self.offsetformat = byteorder + "Q" |
| 1843 |
self.tagnosize = 8 |
| 1844 |
self.tagnoformat = byteorder + "Q" |
| 1845 |
self.tagsize = 20 |
| 1846 |
self.tagformat1 = byteorder + "HH" |
| 1847 |
self.tagformat2 = byteorder + "Q8s" |
| 1848 |
elif version == 42: |
| 1849 |
self.is_bigtiff = False |
| 1850 |
self.byteorder = byteorder |
| 1851 |
self.offsetsize = 4 |
| 1852 |
self.offsetformat = byteorder + "I" |
| 1853 |
self.tagnosize = 2 |
| 1854 |
self.tagnoformat = byteorder + "H" |
| 1855 |
self.tagsize = 12 |
| 1856 |
self.tagformat1 = byteorder + "HH" |
| 1857 |
self.tagformat2 = byteorder + "I4s" |
| 1858 |
else: |
| 1859 |
raise ValueError("invalid TIFF file") |
| 1860 |
|
| 1861 |
|
| 1862 |
self.pages = TiffPages(self) |
| 1863 |
|
| 1864 |
if self.is_lsm and ( |
| 1865 |
self.filehandle.size >= 2**32 |
| 1866 |
or self.pages[0].compression != 1 |
| 1867 |
or self.pages[1].compression != 1 |
| 1868 |
): |
| 1869 |
self._lsm_load_pages() |
| 1870 |
self._lsm_fix_strip_offsets() |
| 1871 |
self._lsm_fix_strip_bytecounts() |
| 1872 |
elif movie: |
| 1873 |
self.pages.useframes = True |
| 1874 |
|
| 1875 |
except Exception: |
| 1876 |
fh.close() |
| 1877 |
raise |
| 1878 |
|
| 1879 |
@property |
| 1880 |
def filehandle(self): |
| 1881 |
"""Return file handle.""" |
| 1882 |
return self._fh |
| 1883 |
|
| 1884 |
@property |
| 1885 |
def filename(self): |
| 1886 |
"""Return name of file handle.""" |
| 1887 |
return self._fh.name |
| 1888 |
|
| 1889 |
@lazyattr |
| 1890 |
def fstat(self): |
| 1891 |
"""Return status of file handle as stat_result object.""" |
| 1892 |
try: |
| 1893 |
return os.fstat(self._fh.fileno()) |
| 1894 |
except Exception: |
| 1895 |
return None |
| 1896 |
|
| 1897 |
def close(self): |
| 1898 |
"""Close open file handle(s).""" |
| 1899 |
for tif in self._files.values(): |
| 1900 |
tif.filehandle.close() |
| 1901 |
self._files = {} |
| 1902 |
|
| 1903 |
def asarray(self, key=None, series=None, out=None, validate=True, maxworkers=1): |
| 1904 |
"""Return image data from multiple TIFF pages as numpy array. |
| 1905 |
|
| 1906 |
By default, the data from the first series is returned. |
| 1907 |
|
| 1908 |
Parameters |
| 1909 |
---------- |
| 1910 |
key : int, slice, or sequence of page indices |
| 1911 |
Defines which pages to return as array. |
| 1912 |
series : int or TiffPageSeries |
| 1913 |
Defines which series of pages to return as array. |
| 1914 |
out : numpy.ndarray, str, or file-like object; optional |
| 1915 |
Buffer where image data will be saved. |
| 1916 |
If None (default), a new array will be created. |
| 1917 |
If numpy.ndarray, a writable array of compatible dtype and shape. |
| 1918 |
If 'memmap', directly memory-map the image data in the TIFF file |
| 1919 |
if possible; else create a memory-mapped array in a temporary file. |
| 1920 |
If str or open file, the file name or file object used to |
| 1921 |
create a memory-map to an array stored in a binary file on disk. |
| 1922 |
validate : bool |
| 1923 |
If True (default), validate various tags. |
| 1924 |
Passed to TiffPage.asarray(). |
| 1925 |
maxworkers : int |
| 1926 |
Maximum number of threads to concurrently get data from pages. |
| 1927 |
Default is 1. If None, up to half the CPU cores are used. |
| 1928 |
Reading data from file is limited to a single thread. |
| 1929 |
Using multiple threads can significantly speed up this function |
| 1930 |
if the bottleneck is decoding compressed data, e.g. in case of |
| 1931 |
large LZW compressed LSM files. |
| 1932 |
If the bottleneck is I/O or pure Python code, using multiple |
| 1933 |
threads might be detrimental. |
| 1934 |
|
| 1935 |
""" |
| 1936 |
if not self.pages: |
| 1937 |
return numpy.array([]) |
| 1938 |
if key is None and series is None: |
| 1939 |
series = 0 |
| 1940 |
if series is not None: |
| 1941 |
try: |
| 1942 |
series = self.series[series] |
| 1943 |
except (KeyError, TypeError): |
| 1944 |
pass |
| 1945 |
pages = series._pages |
| 1946 |
else: |
| 1947 |
pages = self.pages |
| 1948 |
|
| 1949 |
if key is None: |
| 1950 |
pass |
| 1951 |
elif isinstance(key, inttypes): |
| 1952 |
pages = [pages[key]] |
| 1953 |
elif isinstance(key, slice): |
| 1954 |
pages = pages[key] |
| 1955 |
elif isinstance(key, collections.Iterable): |
| 1956 |
pages = [pages[k] for k in key] |
| 1957 |
else: |
| 1958 |
raise TypeError("key must be an int, slice, or sequence") |
| 1959 |
|
| 1960 |
if not pages: |
| 1961 |
raise ValueError("no pages selected") |
| 1962 |
|
| 1963 |
if self.is_nih: |
| 1964 |
result = stack_pages(pages, out=out, maxworkers=maxworkers, squeeze=False) |
| 1965 |
elif key is None and series and series.offset: |
| 1966 |
typecode = self.byteorder + series.dtype.char |
| 1967 |
if out == "memmap" and pages[0].is_memmappable: |
| 1968 |
result = self.filehandle.memmap_array( |
| 1969 |
typecode, series.shape, series.offset |
| 1970 |
) |
| 1971 |
else: |
| 1972 |
if out is not None: |
| 1973 |
out = create_output(out, series.shape, series.dtype) |
| 1974 |
self.filehandle.seek(series.offset) |
| 1975 |
result = self.filehandle.read_array( |
| 1976 |
typecode, product(series.shape), out=out, native=True |
| 1977 |
) |
| 1978 |
elif len(pages) == 1: |
| 1979 |
result = pages[0].asarray(out=out, validate=validate) |
| 1980 |
else: |
| 1981 |
result = stack_pages(pages, out=out, maxworkers=maxworkers) |
| 1982 |
|
| 1983 |
if result is None: |
| 1984 |
return |
| 1985 |
|
| 1986 |
if key is None: |
| 1987 |
try: |
| 1988 |
result.shape = series.shape |
| 1989 |
except ValueError: |
| 1990 |
try: |
| 1991 |
warnings.warn( |
| 1992 |
"failed to reshape %s to %s" % (result.shape, series.shape) |
| 1993 |
) |
| 1994 |
|
| 1995 |
result.shape = (-1,) + series.shape |
| 1996 |
except ValueError: |
| 1997 |
|
| 1998 |
result.shape = (-1,) + pages[0].shape |
| 1999 |
elif len(pages) == 1: |
| 2000 |
result.shape = pages[0].shape |
| 2001 |
else: |
| 2002 |
result.shape = (-1,) + pages[0].shape |
| 2003 |
return result |
| 2004 |
|
| 2005 |
@lazyattr |
| 2006 |
def series(self): |
| 2007 |
"""Return related pages as TiffPageSeries. |
| 2008 |
|
| 2009 |
Side effect: after calling this function, TiffFile.pages might contain |
| 2010 |
TiffPage and TiffFrame instances. |
| 2011 |
|
| 2012 |
""" |
| 2013 |
if not self.pages: |
| 2014 |
return [] |
| 2015 |
|
| 2016 |
useframes = self.pages.useframes |
| 2017 |
keyframe = self.pages.keyframe |
| 2018 |
series = [] |
| 2019 |
for name in "ome imagej lsm fluoview nih mdgel shaped".split(): |
| 2020 |
if getattr(self, "is_" + name, False): |
| 2021 |
series = getattr(self, "_%s_series" % name)() |
| 2022 |
break |
| 2023 |
self.pages.useframes = useframes |
| 2024 |
self.pages.keyframe = keyframe |
| 2025 |
if not series: |
| 2026 |
series = self._generic_series() |
| 2027 |
|
| 2028 |
|
| 2029 |
series = [s for s in series if sum(s.shape) > 0] |
| 2030 |
|
| 2031 |
for i, s in enumerate(series): |
| 2032 |
s.index = i |
| 2033 |
return series |
| 2034 |
|
| 2035 |
def _generic_series(self): |
| 2036 |
"""Return image series in file.""" |
| 2037 |
if self.pages.useframes: |
| 2038 |
|
| 2039 |
page = self.pages[0] |
| 2040 |
shape = page.shape |
| 2041 |
axes = page.axes |
| 2042 |
if len(self.pages) > 1: |
| 2043 |
shape = (len(self.pages),) + shape |
| 2044 |
axes = "I" + axes |
| 2045 |
return [ |
| 2046 |
TiffPageSeries(self.pages[:], shape, page.dtype, axes, stype="movie") |
| 2047 |
] |
| 2048 |
|
| 2049 |
self.pages.clear(False) |
| 2050 |
self.pages.load() |
| 2051 |
result = [] |
| 2052 |
keys = [] |
| 2053 |
series = {} |
| 2054 |
compressions = TIFF.DECOMPESSORS |
| 2055 |
for page in self.pages: |
| 2056 |
if not page.shape: |
| 2057 |
continue |
| 2058 |
key = page.shape + (page.axes, page.compression in compressions) |
| 2059 |
if key in series: |
| 2060 |
series[key].append(page) |
| 2061 |
else: |
| 2062 |
keys.append(key) |
| 2063 |
series[key] = [page] |
| 2064 |
for key in keys: |
| 2065 |
pages = series[key] |
| 2066 |
page = pages[0] |
| 2067 |
shape = page.shape |
| 2068 |
axes = page.axes |
| 2069 |
if len(pages) > 1: |
| 2070 |
shape = (len(pages),) + shape |
| 2071 |
axes = "I" + axes |
| 2072 |
result.append( |
| 2073 |
TiffPageSeries(pages, shape, page.dtype, axes, stype="Generic") |
| 2074 |
) |
| 2075 |
|
| 2076 |
return result |
| 2077 |
|
| 2078 |
def _shaped_series(self): |
| 2079 |
"""Return image series in "shaped" file.""" |
| 2080 |
pages = self.pages |
| 2081 |
pages.useframes = True |
| 2082 |
lenpages = len(pages) |
| 2083 |
|
| 2084 |
def append_series(series, pages, axes, shape, reshape, name, truncated): |
| 2085 |
page = pages[0] |
| 2086 |
if not axes: |
| 2087 |
shape = page.shape |
| 2088 |
axes = page.axes |
| 2089 |
if len(pages) > 1: |
| 2090 |
shape = (len(pages),) + shape |
| 2091 |
axes = "Q" + axes |
| 2092 |
size = product(shape) |
| 2093 |
resize = product(reshape) |
| 2094 |
if page.is_contiguous and resize > size and resize % size == 0: |
| 2095 |
if truncated is None: |
| 2096 |
truncated = True |
| 2097 |
axes = "Q" + axes |
| 2098 |
shape = (resize // size,) + shape |
| 2099 |
try: |
| 2100 |
axes = reshape_axes(axes, shape, reshape) |
| 2101 |
shape = reshape |
| 2102 |
except ValueError as e: |
| 2103 |
warnings.warn(str(e)) |
| 2104 |
series.append( |
| 2105 |
TiffPageSeries( |
| 2106 |
pages, |
| 2107 |
shape, |
| 2108 |
page.dtype, |
| 2109 |
axes, |
| 2110 |
name=name, |
| 2111 |
stype="Shaped", |
| 2112 |
truncated=truncated, |
| 2113 |
) |
| 2114 |
) |
| 2115 |
|
| 2116 |
keyframe = axes = shape = reshape = name = None |
| 2117 |
series = [] |
| 2118 |
index = 0 |
| 2119 |
while True: |
| 2120 |
if index >= lenpages: |
| 2121 |
break |
| 2122 |
|
| 2123 |
pages.keyframe = index |
| 2124 |
keyframe = pages[index] |
| 2125 |
if not keyframe.is_shaped: |
| 2126 |
warnings.warn("invalid shape metadata or corrupted file") |
| 2127 |
return |
| 2128 |
|
| 2129 |
axes = None |
| 2130 |
shape = None |
| 2131 |
metadata = json_description_metadata(keyframe.is_shaped) |
| 2132 |
name = metadata.get("name", "") |
| 2133 |
reshape = metadata["shape"] |
| 2134 |
truncated = metadata.get("truncated", None) |
| 2135 |
if "axes" in metadata: |
| 2136 |
axes = metadata["axes"] |
| 2137 |
if len(axes) == len(reshape): |
| 2138 |
shape = reshape |
| 2139 |
else: |
| 2140 |
axes = "" |
| 2141 |
warnings.warn("axes do not match shape") |
| 2142 |
|
| 2143 |
spages = [keyframe] |
| 2144 |
size = product(reshape) |
| 2145 |
npages, mod = divmod(size, product(keyframe.shape)) |
| 2146 |
if mod: |
| 2147 |
warnings.warn("series shape does not match page shape") |
| 2148 |
return |
| 2149 |
if 1 < npages <= lenpages - index: |
| 2150 |
size *= keyframe._dtype.itemsize |
| 2151 |
if truncated: |
| 2152 |
npages = 1 |
| 2153 |
elif ( |
| 2154 |
keyframe.is_final |
| 2155 |
and keyframe.offset + size < pages[index + 1].offset |
| 2156 |
): |
| 2157 |
truncated = False |
| 2158 |
else: |
| 2159 |
|
| 2160 |
truncated = False |
| 2161 |
for j in range(index + 1, index + npages): |
| 2162 |
page = pages[j] |
| 2163 |
page.keyframe = keyframe |
| 2164 |
spages.append(page) |
| 2165 |
append_series(series, spages, axes, shape, reshape, name, truncated) |
| 2166 |
index += npages |
| 2167 |
|
| 2168 |
return series |
| 2169 |
|
| 2170 |
def _imagej_series(self): |
| 2171 |
"""Return image series in ImageJ file.""" |
| 2172 |
|
| 2173 |
|
| 2174 |
self.pages.useframes = True |
| 2175 |
self.pages.keyframe = 0 |
| 2176 |
|
| 2177 |
ij = self.imagej_metadata |
| 2178 |
pages = self.pages |
| 2179 |
page = pages[0] |
| 2180 |
|
| 2181 |
def is_hyperstack(): |
| 2182 |
|
| 2183 |
|
| 2184 |
if not page.is_final: |
| 2185 |
return False |
| 2186 |
images = ij.get("images", 0) |
| 2187 |
if images <= 1: |
| 2188 |
return False |
| 2189 |
offset, count = page.is_contiguous |
| 2190 |
if ( |
| 2191 |
count != product(page.shape) * page.bitspersample // 8 |
| 2192 |
or offset + count * images > self.filehandle.size |
| 2193 |
): |
| 2194 |
raise ValueError() |
| 2195 |
|
| 2196 |
if len(pages) > 1 and offset + count * images > pages[1].offset: |
| 2197 |
return False |
| 2198 |
return True |
| 2199 |
|
| 2200 |
try: |
| 2201 |
hyperstack = is_hyperstack() |
| 2202 |
except ValueError: |
| 2203 |
warnings.warn("invalid ImageJ metadata or corrupted file") |
| 2204 |
return |
| 2205 |
if hyperstack: |
| 2206 |
|
| 2207 |
pages = [page] |
| 2208 |
else: |
| 2209 |
self.pages.load() |
| 2210 |
|
| 2211 |
shape = [] |
| 2212 |
axes = [] |
| 2213 |
if "frames" in ij: |
| 2214 |
shape.append(ij["frames"]) |
| 2215 |
axes.append("T") |
| 2216 |
if "slices" in ij: |
| 2217 |
shape.append(ij["slices"]) |
| 2218 |
axes.append("Z") |
| 2219 |
if "channels" in ij and not ( |
| 2220 |
page.photometric == 2 and not ij.get("hyperstack", False) |
| 2221 |
): |
| 2222 |
shape.append(ij["channels"]) |
| 2223 |
axes.append("C") |
| 2224 |
remain = ij.get("images", len(pages)) // (product(shape) if shape else 1) |
| 2225 |
if remain > 1: |
| 2226 |
shape.append(remain) |
| 2227 |
axes.append("I") |
| 2228 |
if page.axes[0] == "I": |
| 2229 |
|
| 2230 |
shape.extend(page.shape[1:]) |
| 2231 |
axes.extend(page.axes[1:]) |
| 2232 |
elif page.axes[:2] == "SI": |
| 2233 |
|
| 2234 |
shape = page.shape[0:1] + tuple(shape) + page.shape[2:] |
| 2235 |
axes = list(page.axes[0]) + axes + list(page.axes[2:]) |
| 2236 |
else: |
| 2237 |
shape.extend(page.shape) |
| 2238 |
axes.extend(page.axes) |
| 2239 |
|
| 2240 |
truncated = ( |
| 2241 |
hyperstack |
| 2242 |
and len(self.pages) == 1 |
| 2243 |
and page.is_contiguous[1] != product(shape) * page.bitspersample // 8 |
| 2244 |
) |
| 2245 |
|
| 2246 |
return [ |
| 2247 |
TiffPageSeries( |
| 2248 |
pages, shape, page.dtype, axes, stype="ImageJ", truncated=truncated |
| 2249 |
) |
| 2250 |
] |
| 2251 |
|
| 2252 |
def _fluoview_series(self): |
| 2253 |
"""Return image series in FluoView file.""" |
| 2254 |
self.pages.useframes = True |
| 2255 |
self.pages.keyframe = 0 |
| 2256 |
self.pages.load() |
| 2257 |
mm = self.fluoview_metadata |
| 2258 |
mmhd = list(reversed(mm["Dimensions"])) |
| 2259 |
axes = "".join( |
| 2260 |
TIFF.MM_DIMENSIONS.get(i[0].upper(), "Q") for i in mmhd if i[1] > 1 |
| 2261 |
) |
| 2262 |
shape = tuple(int(i[1]) for i in mmhd if i[1] > 1) |
| 2263 |
return [ |
| 2264 |
TiffPageSeries( |
| 2265 |
self.pages, |
| 2266 |
shape, |
| 2267 |
self.pages[0].dtype, |
| 2268 |
axes, |
| 2269 |
name=mm["ImageName"], |
| 2270 |
stype="FluoView", |
| 2271 |
) |
| 2272 |
] |
| 2273 |
|
| 2274 |
def _mdgel_series(self): |
| 2275 |
"""Return image series in MD Gel file.""" |
| 2276 |
|
| 2277 |
self.pages.useframes = False |
| 2278 |
self.pages.keyframe = 0 |
| 2279 |
self.pages.load() |
| 2280 |
md = self.mdgel_metadata |
| 2281 |
if md["FileTag"] in (2, 128): |
| 2282 |
dtype = numpy.dtype("float32") |
| 2283 |
scale = md["ScalePixel"] |
| 2284 |
scale = scale[0] / scale[1] |
| 2285 |
if md["FileTag"] == 2: |
| 2286 |
|
| 2287 |
def transform(a): |
| 2288 |
return a.astype("float32") ** 2 * scale |
| 2289 |
|
| 2290 |
else: |
| 2291 |
|
| 2292 |
def transform(a): |
| 2293 |
return a.astype("float32") * scale |
| 2294 |
|
| 2295 |
else: |
| 2296 |
transform = None |
| 2297 |
page = self.pages[0] |
| 2298 |
return [ |
| 2299 |
TiffPageSeries( |
| 2300 |
[page], page.shape, dtype, page.axes, transform=transform, stype="MDGel" |
| 2301 |
) |
| 2302 |
] |
| 2303 |
|
| 2304 |
def _nih_series(self): |
| 2305 |
"""Return image series in NIH file.""" |
| 2306 |
self.pages.useframes = True |
| 2307 |
self.pages.keyframe = 0 |
| 2308 |
self.pages.load() |
| 2309 |
page0 = self.pages[0] |
| 2310 |
if len(self.pages) == 1: |
| 2311 |
shape = page0.shape |
| 2312 |
axes = page0.axes |
| 2313 |
else: |
| 2314 |
shape = (len(self.pages),) + page0.shape |
| 2315 |
axes = "I" + page0.axes |
| 2316 |
return [TiffPageSeries(self.pages, shape, page0.dtype, axes, stype="NIH")] |
| 2317 |
|
| 2318 |
def _ome_series(self): |
| 2319 |
"""Return image series in OME-TIFF file(s).""" |
| 2320 |
from xml.etree import cElementTree as etree |
| 2321 |
|
| 2322 |
omexml = self.pages[0].description |
| 2323 |
try: |
| 2324 |
root = etree.fromstring(omexml) |
| 2325 |
except etree.ParseError as e: |
| 2326 |
|
| 2327 |
warnings.warn("ome-xml: %s" % e) |
| 2328 |
try: |
| 2329 |
|
| 2330 |
omexml = omexml.decode("utf-8", "ignore").encode("utf-8") |
| 2331 |
root = etree.fromstring(omexml) |
| 2332 |
except Exception: |
| 2333 |
return |
| 2334 |
|
| 2335 |
self.pages.useframes = True |
| 2336 |
self.pages.keyframe = 0 |
| 2337 |
self.pages.load() |
| 2338 |
|
| 2339 |
uuid = root.attrib.get("UUID", None) |
| 2340 |
self._files = {uuid: self} |
| 2341 |
dirname = self._fh.dirname |
| 2342 |
modulo = {} |
| 2343 |
series = [] |
| 2344 |
for element in root: |
| 2345 |
if element.tag.endswith("BinaryOnly"): |
| 2346 |
|
| 2347 |
warnings.warn("ome-xml: not an ome-tiff master file") |
| 2348 |
break |
| 2349 |
if element.tag.endswith("StructuredAnnotations"): |
| 2350 |
for annot in element: |
| 2351 |
if not annot.attrib.get("Namespace", "").endswith("modulo"): |
| 2352 |
continue |
| 2353 |
for value in annot: |
| 2354 |
for modul in value: |
| 2355 |
for along in modul: |
| 2356 |
if not along.tag[:-1].endswith("Along"): |
| 2357 |
continue |
| 2358 |
axis = along.tag[-1] |
| 2359 |
newaxis = along.attrib.get("Type", "other") |
| 2360 |
newaxis = TIFF.AXES_LABELS[newaxis] |
| 2361 |
if "Start" in along.attrib: |
| 2362 |
step = float(along.attrib.get("Step", 1)) |
| 2363 |
start = float(along.attrib["Start"]) |
| 2364 |
stop = float(along.attrib["End"]) + step |
| 2365 |
labels = numpy.arange(start, stop, step) |
| 2366 |
else: |
| 2367 |
labels = [ |
| 2368 |
label.text |
| 2369 |
for label in along |
| 2370 |
if label.tag.endswith("Label") |
| 2371 |
] |
| 2372 |
modulo[axis] = (newaxis, labels) |
| 2373 |
|
| 2374 |
if not element.tag.endswith("Image"): |
| 2375 |
continue |
| 2376 |
|
| 2377 |
attr = element.attrib |
| 2378 |
name = attr.get("Name", None) |
| 2379 |
|
| 2380 |
for pixels in element: |
| 2381 |
if not pixels.tag.endswith("Pixels"): |
| 2382 |
continue |
| 2383 |
attr = pixels.attrib |
| 2384 |
dtype = attr.get("PixelType", None) |
| 2385 |
axes = "".join(reversed(attr["DimensionOrder"])) |
| 2386 |
shape = list(int(attr["Size" + ax]) for ax in axes) |
| 2387 |
size = product(shape[:-2]) |
| 2388 |
ifds = None |
| 2389 |
spp = 1 |
| 2390 |
|
| 2391 |
|
| 2392 |
|
| 2393 |
for data in pixels: |
| 2394 |
if data.tag.endswith("Channel"): |
| 2395 |
attr = data.attrib |
| 2396 |
if ifds is None: |
| 2397 |
spp = int(attr.get("SamplesPerPixel", spp)) |
| 2398 |
ifds = [None] * (size // spp) |
| 2399 |
elif int(attr.get("SamplesPerPixel", 1)) != spp: |
| 2400 |
raise ValueError("cannot handle differing SamplesPerPixel") |
| 2401 |
continue |
| 2402 |
if ifds is None: |
| 2403 |
ifds = [None] * (size // spp) |
| 2404 |
if not data.tag.endswith("TiffData"): |
| 2405 |
continue |
| 2406 |
attr = data.attrib |
| 2407 |
ifd = int(attr.get("IFD", 0)) |
| 2408 |
num = int(attr.get("NumPlanes", 1 if "IFD" in attr else 0)) |
| 2409 |
num = int(attr.get("PlaneCount", num)) |
| 2410 |
idx = [int(attr.get("First" + ax, 0)) for ax in axes[:-2]] |
| 2411 |
try: |
| 2412 |
idx = numpy.ravel_multi_index(idx, shape[:-2]) |
| 2413 |
except ValueError: |
| 2414 |
|
| 2415 |
warnings.warn("ome-xml: invalid TiffData index") |
| 2416 |
continue |
| 2417 |
for uuid in data: |
| 2418 |
if not uuid.tag.endswith("UUID"): |
| 2419 |
continue |
| 2420 |
if uuid.text not in self._files: |
| 2421 |
if not self._multifile: |
| 2422 |
|
| 2423 |
|
| 2424 |
return [] |
| 2425 |
fname = uuid.attrib["FileName"] |
| 2426 |
try: |
| 2427 |
tif = TiffFile(os.path.join(dirname, fname)) |
| 2428 |
tif.pages.useframes = True |
| 2429 |
tif.pages.keyframe = 0 |
| 2430 |
tif.pages.load() |
| 2431 |
except (IOError, FileNotFoundError, ValueError): |
| 2432 |
warnings.warn("ome-xml: failed to read '%s'" % fname) |
| 2433 |
break |
| 2434 |
self._files[uuid.text] = tif |
| 2435 |
tif.close() |
| 2436 |
pages = self._files[uuid.text].pages |
| 2437 |
try: |
| 2438 |
for i in range(num if num else len(pages)): |
| 2439 |
ifds[idx + i] = pages[ifd + i] |
| 2440 |
except IndexError: |
| 2441 |
warnings.warn("ome-xml: index out of range") |
| 2442 |
|
| 2443 |
break |
| 2444 |
else: |
| 2445 |
pages = self.pages |
| 2446 |
try: |
| 2447 |
for i in range(num if num else len(pages)): |
| 2448 |
ifds[idx + i] = pages[ifd + i] |
| 2449 |
except IndexError: |
| 2450 |
warnings.warn("ome-xml: index out of range") |
| 2451 |
|
| 2452 |
if all(i is None for i in ifds): |
| 2453 |
|
| 2454 |
continue |
| 2455 |
|
| 2456 |
|
| 2457 |
keyframe = None |
| 2458 |
for i in ifds: |
| 2459 |
|
| 2460 |
if i and i == i.keyframe: |
| 2461 |
keyframe = i |
| 2462 |
break |
| 2463 |
if not keyframe: |
| 2464 |
|
| 2465 |
for i, keyframe in enumerate(ifds): |
| 2466 |
if keyframe: |
| 2467 |
keyframe.parent.pages.keyframe = keyframe.index |
| 2468 |
keyframe = keyframe.parent.pages[keyframe.index] |
| 2469 |
ifds[i] = keyframe |
| 2470 |
break |
| 2471 |
for i in ifds: |
| 2472 |
if i is not None: |
| 2473 |
i.keyframe = keyframe |
| 2474 |
|
| 2475 |
dtype = keyframe.dtype |
| 2476 |
series.append( |
| 2477 |
TiffPageSeries( |
| 2478 |
ifds, shape, dtype, axes, parent=self, name=name, stype="OME" |
| 2479 |
) |
| 2480 |
) |
| 2481 |
for serie in series: |
| 2482 |
shape = list(serie.shape) |
| 2483 |
for axis, (newaxis, labels) in modulo.items(): |
| 2484 |
i = serie.axes.index(axis) |
| 2485 |
size = len(labels) |
| 2486 |
if shape[i] == size: |
| 2487 |
serie.axes = serie.axes.replace(axis, newaxis, 1) |
| 2488 |
else: |
| 2489 |
shape[i] //= size |
| 2490 |
shape.insert(i + 1, size) |
| 2491 |
serie.axes = serie.axes.replace(axis, axis + newaxis, 1) |
| 2492 |
serie.shape = tuple(shape) |
| 2493 |
|
| 2494 |
for serie in series: |
| 2495 |
serie.shape, serie.axes = squeeze_axes(serie.shape, serie.axes) |
| 2496 |
return series |
| 2497 |
|
| 2498 |
def _lsm_series(self): |
| 2499 |
"""Return main image series in LSM file. Skip thumbnails.""" |
| 2500 |
lsmi = self.lsm_metadata |
| 2501 |
axes = TIFF.CZ_LSMINFO_SCANTYPE[lsmi["ScanType"]] |
| 2502 |
if self.pages[0].photometric == 2: |
| 2503 |
axes = axes.replace("C", "").replace("XY", "XYC") |
| 2504 |
if lsmi.get("DimensionP", 0) > 1: |
| 2505 |
axes += "P" |
| 2506 |
if lsmi.get("DimensionM", 0) > 1: |
| 2507 |
axes += "M" |
| 2508 |
axes = axes[::-1] |
| 2509 |
shape = tuple(int(lsmi[TIFF.CZ_LSMINFO_DIMENSIONS[i]]) for i in axes) |
| 2510 |
name = lsmi.get("Name", "") |
| 2511 |
self.pages.keyframe = 0 |
| 2512 |
pages = self.pages[::2] |
| 2513 |
dtype = pages[0].dtype |
| 2514 |
series = [TiffPageSeries(pages, shape, dtype, axes, name=name, stype="LSM")] |
| 2515 |
|
| 2516 |
if self.pages[1].is_reduced: |
| 2517 |
self.pages.keyframe = 1 |
| 2518 |
pages = self.pages[1::2] |
| 2519 |
dtype = pages[0].dtype |
| 2520 |
cp, i = 1, 0 |
| 2521 |
while cp < len(pages) and i < len(shape) - 2: |
| 2522 |
cp *= shape[i] |
| 2523 |
i += 1 |
| 2524 |
shape = shape[:i] + pages[0].shape |
| 2525 |
axes = axes[:i] + "CYX" |
| 2526 |
series.append( |
| 2527 |
TiffPageSeries(pages, shape, dtype, axes, name=name, stype="LSMreduced") |
| 2528 |
) |
| 2529 |
|
| 2530 |
return series |
| 2531 |
|
| 2532 |
def _lsm_load_pages(self): |
| 2533 |
"""Load all pages from LSM file.""" |
| 2534 |
self.pages.cache = True |
| 2535 |
self.pages.useframes = True |
| 2536 |
|
| 2537 |
self.pages.keyframe = 1 |
| 2538 |
keyframe = self.pages[1] |
| 2539 |
for page in self.pages[1::2]: |
| 2540 |
page.keyframe = keyframe |
| 2541 |
|
| 2542 |
self.pages.keyframe = 0 |
| 2543 |
keyframe = self.pages[0] |
| 2544 |
for page in self.pages[::2]: |
| 2545 |
page.keyframe = keyframe |
| 2546 |
|
| 2547 |
def _lsm_fix_strip_offsets(self): |
| 2548 |
"""Unwrap strip offsets for LSM files greater than 4 GB. |
| 2549 |
|
| 2550 |
Each series and position require separate unwrapping (undocumented). |
| 2551 |
|
| 2552 |
""" |
| 2553 |
if self.filehandle.size < 2**32: |
| 2554 |
return |
| 2555 |
|
| 2556 |
pages = self.pages |
| 2557 |
npages = len(pages) |
| 2558 |
series = self.series[0] |
| 2559 |
axes = series.axes |
| 2560 |
|
| 2561 |
|
| 2562 |
positions = 1 |
| 2563 |
for i in 0, 1: |
| 2564 |
if series.axes[i] in "PM": |
| 2565 |
positions *= series.shape[i] |
| 2566 |
|
| 2567 |
|
| 2568 |
if positions > 1: |
| 2569 |
ntimes = 0 |
| 2570 |
for i in 1, 2: |
| 2571 |
if axes[i] == "T": |
| 2572 |
ntimes = series.shape[i] |
| 2573 |
break |
| 2574 |
if ntimes: |
| 2575 |
div, mod = divmod(npages, 2 * positions * ntimes) |
| 2576 |
assert mod == 0 |
| 2577 |
shape = (positions, ntimes, div, 2) |
| 2578 |
indices = numpy.arange(product(shape)).reshape(shape) |
| 2579 |
indices = numpy.moveaxis(indices, 1, 0) |
| 2580 |
else: |
| 2581 |
indices = numpy.arange(npages).reshape(-1, 2) |
| 2582 |
|
| 2583 |
|
| 2584 |
if pages[0].dataoffsets[0] > pages[1].dataoffsets[0]: |
| 2585 |
indices = indices[..., ::-1] |
| 2586 |
|
| 2587 |
|
| 2588 |
wrap = 0 |
| 2589 |
previousoffset = 0 |
| 2590 |
for i in indices.flat: |
| 2591 |
page = pages[i] |
| 2592 |
dataoffsets = [] |
| 2593 |
for currentoffset in page.dataoffsets: |
| 2594 |
if currentoffset < previousoffset: |
| 2595 |
wrap += 2**32 |
| 2596 |
dataoffsets.append(currentoffset + wrap) |
| 2597 |
previousoffset = currentoffset |
| 2598 |
page.dataoffsets = tuple(dataoffsets) |
| 2599 |
|
| 2600 |
def _lsm_fix_strip_bytecounts(self): |
| 2601 |
"""Set databytecounts to size of compressed data. |
| 2602 |
|
| 2603 |
The StripByteCounts tag in LSM files contains the number of bytes |
| 2604 |
for the uncompressed data. |
| 2605 |
|
| 2606 |
""" |
| 2607 |
pages = self.pages |
| 2608 |
if pages[0].compression == 1: |
| 2609 |
return |
| 2610 |
|
| 2611 |
pages = sorted(pages, key=lambda p: p.dataoffsets[0]) |
| 2612 |
npages = len(pages) - 1 |
| 2613 |
for i, page in enumerate(pages): |
| 2614 |
if page.index % 2: |
| 2615 |
continue |
| 2616 |
offsets = page.dataoffsets |
| 2617 |
bytecounts = page.databytecounts |
| 2618 |
if i < npages: |
| 2619 |
lastoffset = pages[i + 1].dataoffsets[0] |
| 2620 |
else: |
| 2621 |
|
| 2622 |
lastoffset = min(offsets[-1] + 2 * bytecounts[-1], self._fh.size) |
| 2623 |
offsets = offsets + (lastoffset,) |
| 2624 |
page.databytecounts = tuple( |
| 2625 |
offsets[j + 1] - offsets[j] for j in range(len(bytecounts)) |
| 2626 |
) |
| 2627 |
|
| 2628 |
def __getattr__(self, name): |
| 2629 |
"""Return 'is_flag' attributes from first page.""" |
| 2630 |
if name[3:] in TIFF.FILE_FLAGS: |
| 2631 |
if not self.pages: |
| 2632 |
return False |
| 2633 |
value = bool(getattr(self.pages[0], name)) |
| 2634 |
setattr(self, name, value) |
| 2635 |
return value |
| 2636 |
raise AttributeError( |
| 2637 |
"'%s' object has no attribute '%s'" % (self.__class__.__name__, name) |
| 2638 |
) |
| 2639 |
|
| 2640 |
def __enter__(self): |
| 2641 |
return self |
| 2642 |
|
| 2643 |
def __exit__(self, exc_type, exc_value, traceback): |
| 2644 |
self.close() |
| 2645 |
|
| 2646 |
def __str__(self, detail=0, width=79): |
| 2647 |
"""Return string containing information about file. |
| 2648 |
|
| 2649 |
The detail parameter specifies the level of detail returned: |
| 2650 |
|
| 2651 |
0: file only. |
| 2652 |
1: all series, first page of series and its tags. |
| 2653 |
2: large tag values and file metadata. |
| 2654 |
3: all pages. |
| 2655 |
|
| 2656 |
""" |
| 2657 |
info = [ |
| 2658 |
"TiffFile '%s'", |
| 2659 |
format_size(self._fh.size), |
| 2660 |
{"<": "LittleEndian", ">": "BigEndian"}[self.byteorder], |
| 2661 |
] |
| 2662 |
if self.is_bigtiff: |
| 2663 |
info.append("BigTiff") |
| 2664 |
info.append("|".join(f.upper() for f in self.flags)) |
| 2665 |
if len(self.pages) > 1: |
| 2666 |
info.append("%i Pages" % len(self.pages)) |
| 2667 |
if len(self.series) > 1: |
| 2668 |
info.append("%i Series" % len(self.series)) |
| 2669 |
if len(self._files) > 1: |
| 2670 |
info.append("%i Files" % (len(self._files))) |
| 2671 |
info = " ".join(info) |
| 2672 |
info = info.replace(" ", " ").replace(" ", " ") |
| 2673 |
info = info % snipstr(self._fh.name, max(12, width + 2 - len(info))) |
| 2674 |
if detail <= 0: |
| 2675 |
return info |
| 2676 |
info = [info] |
| 2677 |
info.append("\n".join(str(s) for s in self.series)) |
| 2678 |
if detail >= 3: |
| 2679 |
info.extend( |
| 2680 |
( |
| 2681 |
TiffPage.__str__(p, detail=detail, width=width) |
| 2682 |
for p in self.pages |
| 2683 |
if p is not None |
| 2684 |
) |
| 2685 |
) |
| 2686 |
else: |
| 2687 |
info.extend( |
| 2688 |
( |
| 2689 |
TiffPage.__str__(s.pages[0], detail=detail, width=width) |
| 2690 |
for s in self.series |
| 2691 |
if s.pages[0] is not None |
| 2692 |
) |
| 2693 |
) |
| 2694 |
if detail >= 2: |
| 2695 |
for name in sorted(self.flags): |
| 2696 |
if hasattr(self, name + "_metadata"): |
| 2697 |
m = getattr(self, name + "_metadata") |
| 2698 |
if m: |
| 2699 |
info.append( |
| 2700 |
"%s_METADATA\n%s" |
| 2701 |
% ( |
| 2702 |
name.upper(), |
| 2703 |
pformat(m, width=width, height=detail * 12), |
| 2704 |
) |
| 2705 |
) |
| 2706 |
return "\n\n".join(info).replace("\n\n\n", "\n\n") |
| 2707 |
|
| 2708 |
@lazyattr |
| 2709 |
def flags(self): |
| 2710 |
"""Return set of file flags.""" |
| 2711 |
return set( |
| 2712 |
name.lower() |
| 2713 |
for name in sorted(TIFF.FILE_FLAGS) |
| 2714 |
if getattr(self, "is_" + name) |
| 2715 |
) |
| 2716 |
|
| 2717 |
@lazyattr |
| 2718 |
def is_mdgel(self): |
| 2719 |
"""File has MD Gel format.""" |
| 2720 |
try: |
| 2721 |
return self.pages[0].is_mdgel or self.pages[1].is_mdgel |
| 2722 |
except IndexError: |
| 2723 |
return False |
| 2724 |
|
| 2725 |
@property |
| 2726 |
def is_movie(self): |
| 2727 |
"""Return if file is a movie.""" |
| 2728 |
return self.pages.useframes |
| 2729 |
|
| 2730 |
@lazyattr |
| 2731 |
def shaped_metadata(self): |
| 2732 |
"""Return Tifffile metadata from JSON descriptions as dicts.""" |
| 2733 |
if not self.is_shaped: |
| 2734 |
return |
| 2735 |
return tuple( |
| 2736 |
json_description_metadata(s.pages[0].is_shaped) |
| 2737 |
for s in self.series |
| 2738 |
if s.stype.lower() == "shaped" |
| 2739 |
) |
| 2740 |
|
| 2741 |
@lazyattr |
| 2742 |
def ome_metadata(self): |
| 2743 |
"""Return OME XML as dict.""" |
| 2744 |
|
| 2745 |
if not self.is_ome: |
| 2746 |
return |
| 2747 |
return xml2dict(self.pages[0].description)["OME"] |
| 2748 |
|
| 2749 |
@lazyattr |
| 2750 |
def qptiff_metadata(self): |
| 2751 |
"""Return PerkinElmer-QPI-ImageDescription XML element as dict.""" |
| 2752 |
if not self.is_qptiff: |
| 2753 |
return |
| 2754 |
root = "PerkinElmer-QPI-ImageDescription" |
| 2755 |
xml = self.pages[0].description.replace(" " + root + " ", root) |
| 2756 |
return xml2dict(xml)[root] |
| 2757 |
|
| 2758 |
@lazyattr |
| 2759 |
def lsm_metadata(self): |
| 2760 |
"""Return LSM metadata from CZ_LSMINFO tag as dict.""" |
| 2761 |
if not self.is_lsm: |
| 2762 |
return |
| 2763 |
return self.pages[0].tags["CZ_LSMINFO"].value |
| 2764 |
|
| 2765 |
@lazyattr |
| 2766 |
def stk_metadata(self): |
| 2767 |
"""Return STK metadata from UIC tags as dict.""" |
| 2768 |
if not self.is_stk: |
| 2769 |
return |
| 2770 |
page = self.pages[0] |
| 2771 |
tags = page.tags |
| 2772 |
result = {} |
| 2773 |
result["NumberPlanes"] = tags["UIC2tag"].count |
| 2774 |
if page.description: |
| 2775 |
result["PlaneDescriptions"] = page.description.split("\0") |
| 2776 |
|
| 2777 |
|
| 2778 |
if "UIC1tag" in tags: |
| 2779 |
result.update(tags["UIC1tag"].value) |
| 2780 |
if "UIC3tag" in tags: |
| 2781 |
result.update(tags["UIC3tag"].value) |
| 2782 |
if "UIC4tag" in tags: |
| 2783 |
result.update(tags["UIC4tag"].value) |
| 2784 |
uic2tag = tags["UIC2tag"].value |
| 2785 |
result["ZDistance"] = uic2tag["ZDistance"] |
| 2786 |
result["TimeCreated"] = uic2tag["TimeCreated"] |
| 2787 |
result["TimeModified"] = uic2tag["TimeModified"] |
| 2788 |
try: |
| 2789 |
result["DatetimeCreated"] = numpy.array( |
| 2790 |
[ |
| 2791 |
julian_datetime(*dt) |
| 2792 |
for dt in zip(uic2tag["DateCreated"], uic2tag["TimeCreated"]) |
| 2793 |
], |
| 2794 |
dtype="datetime64[ns]", |
| 2795 |
) |
| 2796 |
result["DatetimeModified"] = numpy.array( |
| 2797 |
[ |
| 2798 |
julian_datetime(*dt) |
| 2799 |
for dt in zip(uic2tag["DateModified"], uic2tag["TimeModified"]) |
| 2800 |
], |
| 2801 |
dtype="datetime64[ns]", |
| 2802 |
) |
| 2803 |
except ValueError as e: |
| 2804 |
warnings.warn("stk_metadata: %s" % e) |
| 2805 |
return result |
| 2806 |
|
| 2807 |
@lazyattr |
| 2808 |
def imagej_metadata(self): |
| 2809 |
"""Return consolidated ImageJ metadata as dict.""" |
| 2810 |
if not self.is_imagej: |
| 2811 |
return |
| 2812 |
page = self.pages[0] |
| 2813 |
result = imagej_description_metadata(page.is_imagej) |
| 2814 |
if "IJMetadata" in page.tags: |
| 2815 |
try: |
| 2816 |
result.update(page.tags["IJMetadata"].value) |
| 2817 |
except Exception: |
| 2818 |
pass |
| 2819 |
return result |
| 2820 |
|
| 2821 |
@lazyattr |
| 2822 |
def fluoview_metadata(self): |
| 2823 |
"""Return consolidated FluoView metadata as dict.""" |
| 2824 |
if not self.is_fluoview: |
| 2825 |
return |
| 2826 |
result = {} |
| 2827 |
page = self.pages[0] |
| 2828 |
result.update(page.tags["MM_Header"].value) |
| 2829 |
|
| 2830 |
result["Stamp"] = page.tags["MM_Stamp"].value |
| 2831 |
|
| 2832 |
|
| 2833 |
|
| 2834 |
|
| 2835 |
|
| 2836 |
|
| 2837 |
|
| 2838 |
|
| 2839 |
return result |
| 2840 |
|
| 2841 |
@lazyattr |
| 2842 |
def nih_metadata(self): |
| 2843 |
"""Return NIH Image metadata from NIHImageHeader tag as dict.""" |
| 2844 |
if not self.is_nih: |
| 2845 |
return |
| 2846 |
return self.pages[0].tags["NIHImageHeader"].value |
| 2847 |
|
| 2848 |
@lazyattr |
| 2849 |
def fei_metadata(self): |
| 2850 |
"""Return FEI metadata from SFEG or HELIOS tags as dict.""" |
| 2851 |
if not self.is_fei: |
| 2852 |
return |
| 2853 |
tags = self.pages[0].tags |
| 2854 |
if "FEI_SFEG" in tags: |
| 2855 |
return tags["FEI_SFEG"].value |
| 2856 |
if "FEI_HELIOS" in tags: |
| 2857 |
return tags["FEI_HELIOS"].value |
| 2858 |
|
| 2859 |
@lazyattr |
| 2860 |
def sem_metadata(self): |
| 2861 |
"""Return SEM metadata from CZ_SEM tag as dict.""" |
| 2862 |
if not self.is_sem: |
| 2863 |
return |
| 2864 |
return self.pages[0].tags["CZ_SEM"].value |
| 2865 |
|
| 2866 |
@lazyattr |
| 2867 |
def mdgel_metadata(self): |
| 2868 |
"""Return consolidated metadata from MD GEL tags as dict.""" |
| 2869 |
for page in self.pages[:2]: |
| 2870 |
if "MDFileTag" in page.tags: |
| 2871 |
tags = page.tags |
| 2872 |
break |
| 2873 |
else: |
| 2874 |
return |
| 2875 |
result = {} |
| 2876 |
for code in range(33445, 33453): |
| 2877 |
name = TIFF.TAGS[code] |
| 2878 |
if name not in tags: |
| 2879 |
continue |
| 2880 |
result[name[2:]] = tags[name].value |
| 2881 |
return result |
| 2882 |
|
| 2883 |
@lazyattr |
| 2884 |
def andor_metadata(self): |
| 2885 |
"""Return Andor tags as dict.""" |
| 2886 |
return self.pages[0].andor_tags |
| 2887 |
|
| 2888 |
@lazyattr |
| 2889 |
def epics_metadata(self): |
| 2890 |
"""Return EPICS areaDetector tags as dict.""" |
| 2891 |
return self.pages[0].epics_tags |
| 2892 |
|
| 2893 |
@lazyattr |
| 2894 |
def tvips_metadata(self): |
| 2895 |
"""Return TVIPS tag as dict.""" |
| 2896 |
if not self.is_tvips: |
| 2897 |
return |
| 2898 |
return self.pages[0].tags["TVIPS"].value |
| 2899 |
|
| 2900 |
@lazyattr |
| 2901 |
def metaseries_metadata(self): |
| 2902 |
"""Return MetaSeries metadata from image description as dict.""" |
| 2903 |
if not self.is_metaseries: |
| 2904 |
return |
| 2905 |
return metaseries_description_metadata(self.pages[0].description) |
| 2906 |
|
| 2907 |
@lazyattr |
| 2908 |
def pilatus_metadata(self): |
| 2909 |
"""Return Pilatus metadata from image description as dict.""" |
| 2910 |
if not self.is_pilatus: |
| 2911 |
return |
| 2912 |
return pilatus_description_metadata(self.pages[0].description) |
| 2913 |
|
| 2914 |
@lazyattr |
| 2915 |
def micromanager_metadata(self): |
| 2916 |
"""Return consolidated MicroManager metadata as dict.""" |
| 2917 |
if not self.is_micromanager: |
| 2918 |
return |
| 2919 |
|
| 2920 |
result = read_micromanager_metadata(self._fh) |
| 2921 |
|
| 2922 |
result.update(self.pages[0].tags["MicroManagerMetadata"].value) |
| 2923 |
return result |
| 2924 |
|
| 2925 |
@lazyattr |
| 2926 |
def scanimage_metadata(self): |
| 2927 |
"""Return ScanImage non-varying frame and ROI metadata as dict.""" |
| 2928 |
if not self.is_scanimage: |
| 2929 |
return |
| 2930 |
result = {} |
| 2931 |
try: |
| 2932 |
framedata, roidata = read_scanimage_metadata(self._fh) |
| 2933 |
result["FrameData"] = framedata |
| 2934 |
result.update(roidata) |
| 2935 |
except ValueError: |
| 2936 |
pass |
| 2937 |
|
| 2938 |
try: |
| 2939 |
result["Description"] = scanimage_description_metadata( |
| 2940 |
self.pages[0].description |
| 2941 |
) |
| 2942 |
except Exception as e: |
| 2943 |
warnings.warn("scanimage_description_metadata failed: %s" % e) |
| 2944 |
return result |
| 2945 |
|
| 2946 |
@property |
| 2947 |
def geotiff_metadata(self): |
| 2948 |
"""Return GeoTIFF metadata from first page as dict.""" |
| 2949 |
if not self.is_geotiff: |
| 2950 |
return |
| 2951 |
return self.pages[0].geotiff_tags |
| 2952 |
|
| 2953 |
|
| 2954 |
class TiffPages(object): |
| 2955 |
"""Sequence of TIFF image file directories.""" |
| 2956 |
|
| 2957 |
def __init__(self, parent): |
| 2958 |
"""Initialize instance from file. Read first TiffPage from file. |
| 2959 |
|
| 2960 |
The file position must be at an offset to an offset to a TiffPage. |
| 2961 |
|
| 2962 |
""" |
| 2963 |
self.parent = parent |
| 2964 |
self.pages = [] |
| 2965 |
self.complete = False |
| 2966 |
self._tiffpage = TiffPage |
| 2967 |
self._keyframe = None |
| 2968 |
self._cache = True |
| 2969 |
|
| 2970 |
|
| 2971 |
fh = parent.filehandle |
| 2972 |
self._nextpageoffset = fh.tell() |
| 2973 |
offset = struct.unpack(parent.offsetformat, fh.read(parent.offsetsize))[0] |
| 2974 |
|
| 2975 |
if offset == 0: |
| 2976 |
|
| 2977 |
self.complete = True |
| 2978 |
return |
| 2979 |
if offset >= fh.size: |
| 2980 |
warnings.warn("invalid page offset (%i)" % offset) |
| 2981 |
self.complete = True |
| 2982 |
return |
| 2983 |
|
| 2984 |
|
| 2985 |
fh.seek(offset) |
| 2986 |
page = TiffPage(parent, index=0) |
| 2987 |
self.pages.append(page) |
| 2988 |
self._keyframe = page |
| 2989 |
|
| 2990 |
@property |
| 2991 |
def cache(self): |
| 2992 |
"""Return if pages/frames are currently being cached.""" |
| 2993 |
return self._cache |
| 2994 |
|
| 2995 |
@cache.setter |
| 2996 |
def cache(self, value): |
| 2997 |
"""Enable or disable caching of pages/frames. Clear cache if False.""" |
| 2998 |
value = bool(value) |
| 2999 |
if self._cache and not value: |
| 3000 |
self.clear() |
| 3001 |
self._cache = value |
| 3002 |
|
| 3003 |
@property |
| 3004 |
def useframes(self): |
| 3005 |
"""Return if currently using TiffFrame (True) or TiffPage (False).""" |
| 3006 |
return self._tiffpage == TiffFrame and TiffFrame is not TiffPage |
| 3007 |
|
| 3008 |
@useframes.setter |
| 3009 |
def useframes(self, value): |
| 3010 |
"""Set to use TiffFrame (True) or TiffPage (False).""" |
| 3011 |
self._tiffpage = TiffFrame if value else TiffPage |
| 3012 |
|
| 3013 |
@property |
| 3014 |
def keyframe(self): |
| 3015 |
"""Return index of current keyframe.""" |
| 3016 |
return self._keyframe.index |
| 3017 |
|
| 3018 |
@keyframe.setter |
| 3019 |
def keyframe(self, index): |
| 3020 |
"""Set current keyframe. Load TiffPage from file if necessary.""" |
| 3021 |
if self._keyframe.index == index: |
| 3022 |
return |
| 3023 |
if self.complete or 0 <= index < len(self.pages): |
| 3024 |
page = self.pages[index] |
| 3025 |
if isinstance(page, TiffPage): |
| 3026 |
self._keyframe = page |
| 3027 |
return |
| 3028 |
elif isinstance(page, TiffFrame): |
| 3029 |
|
| 3030 |
self.pages[index] = page.offset |
| 3031 |
|
| 3032 |
useframes = self.useframes |
| 3033 |
self._tiffpage = TiffPage |
| 3034 |
self._keyframe = self[index] |
| 3035 |
self.useframes = useframes |
| 3036 |
|
| 3037 |
@property |
| 3038 |
def next_page_offset(self): |
| 3039 |
"""Return offset where offset to a new page can be stored.""" |
| 3040 |
if not self.complete: |
| 3041 |
self._seek(-1) |
| 3042 |
return self._nextpageoffset |
| 3043 |
|
| 3044 |
def load(self): |
| 3045 |
"""Read all remaining pages from file.""" |
| 3046 |
fh = self.parent.filehandle |
| 3047 |
keyframe = self._keyframe |
| 3048 |
pages = self.pages |
| 3049 |
if not self.complete: |
| 3050 |
self._seek(-1) |
| 3051 |
for i, page in enumerate(pages): |
| 3052 |
if isinstance(page, inttypes): |
| 3053 |
fh.seek(page) |
| 3054 |
page = self._tiffpage(self.parent, index=i, keyframe=keyframe) |
| 3055 |
pages[i] = page |
| 3056 |
|
| 3057 |
def clear(self, fully=True): |
| 3058 |
"""Delete all but first page from cache. Set keyframe to first page.""" |
| 3059 |
pages = self.pages |
| 3060 |
if not self._cache or len(pages) < 1: |
| 3061 |
return |
| 3062 |
self._keyframe = pages[0] |
| 3063 |
if fully: |
| 3064 |
|
| 3065 |
for i, page in enumerate(pages[1:]): |
| 3066 |
if not isinstance(page, inttypes): |
| 3067 |
pages[i + 1] = page.offset |
| 3068 |
elif TiffFrame is not TiffPage: |
| 3069 |
|
| 3070 |
for i, page in enumerate(pages): |
| 3071 |
if isinstance(page, TiffFrame): |
| 3072 |
pages[i] = page.offset |
| 3073 |
|
| 3074 |
def _seek(self, index, maxpages=2**22): |
| 3075 |
"""Seek file to offset of specified page.""" |
| 3076 |
pages = self.pages |
| 3077 |
if not pages: |
| 3078 |
return |
| 3079 |
|
| 3080 |
fh = self.parent.filehandle |
| 3081 |
if fh.closed: |
| 3082 |
raise RuntimeError("FileHandle is closed") |
| 3083 |
|
| 3084 |
if self.complete or 0 <= index < len(pages): |
| 3085 |
page = pages[index] |
| 3086 |
offset = page if isinstance(page, inttypes) else page.offset |
| 3087 |
fh.seek(offset) |
| 3088 |
return |
| 3089 |
|
| 3090 |
offsetformat = self.parent.offsetformat |
| 3091 |
offsetsize = self.parent.offsetsize |
| 3092 |
tagnoformat = self.parent.tagnoformat |
| 3093 |
tagnosize = self.parent.tagnosize |
| 3094 |
tagsize = self.parent.tagsize |
| 3095 |
unpack = struct.unpack |
| 3096 |
|
| 3097 |
page = pages[-1] |
| 3098 |
offset = page if isinstance(page, inttypes) else page.offset |
| 3099 |
|
| 3100 |
while len(pages) < maxpages: |
| 3101 |
|
| 3102 |
fh.seek(offset) |
| 3103 |
|
| 3104 |
try: |
| 3105 |
tagno = unpack(tagnoformat, fh.read(tagnosize))[0] |
| 3106 |
if tagno > 4096: |
| 3107 |
raise ValueError("suspicious number of tags") |
| 3108 |
except Exception: |
| 3109 |
warnings.warn("corrupted tag list at offset %i" % offset) |
| 3110 |
del pages[-1] |
| 3111 |
self.complete = True |
| 3112 |
break |
| 3113 |
self._nextpageoffset = offset + tagnosize + tagno * tagsize |
| 3114 |
fh.seek(self._nextpageoffset) |
| 3115 |
|
| 3116 |
|
| 3117 |
offset = unpack(offsetformat, fh.read(offsetsize))[0] |
| 3118 |
if offset == 0: |
| 3119 |
self.complete = True |
| 3120 |
break |
| 3121 |
if offset >= fh.size: |
| 3122 |
warnings.warn("invalid page offset (%i)" % offset) |
| 3123 |
self.complete = True |
| 3124 |
break |
| 3125 |
|
| 3126 |
pages.append(offset) |
| 3127 |
if 0 <= index < len(pages): |
| 3128 |
break |
| 3129 |
|
| 3130 |
if index >= len(pages): |
| 3131 |
raise IndexError("list index out of range") |
| 3132 |
|
| 3133 |
page = pages[index] |
| 3134 |
fh.seek(page if isinstance(page, inttypes) else page.offset) |
| 3135 |
|
| 3136 |
def __bool__(self): |
| 3137 |
"""Return True if file contains any pages.""" |
| 3138 |
return len(self.pages) > 0 |
| 3139 |
|
| 3140 |
def __len__(self): |
| 3141 |
"""Return number of pages in file.""" |
| 3142 |
if not self.complete: |
| 3143 |
self._seek(-1) |
| 3144 |
return len(self.pages) |
| 3145 |
|
| 3146 |
def __getitem__(self, key): |
| 3147 |
"""Return specified page(s) from cache or file.""" |
| 3148 |
pages = self.pages |
| 3149 |
if not pages: |
| 3150 |
raise IndexError("list index out of range") |
| 3151 |
if key == 0: |
| 3152 |
return pages[key] |
| 3153 |
|
| 3154 |
if isinstance(key, slice): |
| 3155 |
start, stop, _ = key.indices(2**31 - 1) |
| 3156 |
if not self.complete and max(stop, start) > len(pages): |
| 3157 |
self._seek(-1) |
| 3158 |
return [self[i] for i in range(*key.indices(len(pages)))] |
| 3159 |
|
| 3160 |
if self.complete and key >= len(pages): |
| 3161 |
raise IndexError("list index out of range") |
| 3162 |
|
| 3163 |
try: |
| 3164 |
page = pages[key] |
| 3165 |
except IndexError: |
| 3166 |
page = 0 |
| 3167 |
if not isinstance(page, inttypes): |
| 3168 |
return page |
| 3169 |
|
| 3170 |
self._seek(key) |
| 3171 |
page = self._tiffpage(self.parent, index=key, keyframe=self._keyframe) |
| 3172 |
if self._cache: |
| 3173 |
pages[key] = page |
| 3174 |
return page |
| 3175 |
|
| 3176 |
def __iter__(self): |
| 3177 |
"""Return iterator over all pages.""" |
| 3178 |
i = 0 |
| 3179 |
while True: |
| 3180 |
try: |
| 3181 |
yield self[i] |
| 3182 |
i += 1 |
| 3183 |
except IndexError: |
| 3184 |
break |
| 3185 |
|
| 3186 |
|
| 3187 |
class TiffPage(object): |
| 3188 |
"""TIFF image file directory (IFD). |
| 3189 |
|
| 3190 |
Attributes |
| 3191 |
---------- |
| 3192 |
index : int |
| 3193 |
Index of page in file. |
| 3194 |
dtype : numpy.dtype or None |
| 3195 |
Data type (native byte order) of the image in IFD. |
| 3196 |
shape : tuple |
| 3197 |
Dimensions of the image in IFD. |
| 3198 |
axes : str |
| 3199 |
Axes label codes: |
| 3200 |
'X' width, 'Y' height, 'S' sample, 'I' image series|page|plane, |
| 3201 |
'Z' depth, 'C' color|em-wavelength|channel, 'E' ex-wavelength|lambda, |
| 3202 |
'T' time, 'R' region|tile, 'A' angle, 'P' phase, 'H' lifetime, |
| 3203 |
'L' exposure, 'V' event, 'Q' unknown, '_' missing |
| 3204 |
tags : dict |
| 3205 |
Dictionary of tags in IFD. {tag.name: TiffTag} |
| 3206 |
colormap : numpy.ndarray |
| 3207 |
Color look up table, if exists. |
| 3208 |
|
| 3209 |
All attributes are read-only. |
| 3210 |
|
| 3211 |
Notes |
| 3212 |
----- |
| 3213 |
The internal, normalized '_shape' attribute is 6 dimensional: |
| 3214 |
|
| 3215 |
0 : number planes/images (stk, ij). |
| 3216 |
1 : planar samplesperpixel. |
| 3217 |
2 : imagedepth Z (sgi). |
| 3218 |
3 : imagelength Y. |
| 3219 |
4 : imagewidth X. |
| 3220 |
5 : contig samplesperpixel. |
| 3221 |
|
| 3222 |
""" |
| 3223 |
|
| 3224 |
|
| 3225 |
imagewidth = 0 |
| 3226 |
imagelength = 0 |
| 3227 |
imagedepth = 1 |
| 3228 |
tilewidth = 0 |
| 3229 |
tilelength = 0 |
| 3230 |
tiledepth = 1 |
| 3231 |
bitspersample = 1 |
| 3232 |
samplesperpixel = 1 |
| 3233 |
sampleformat = 1 |
| 3234 |
rowsperstrip = 2**32 - 1 |
| 3235 |
compression = 1 |
| 3236 |
planarconfig = 1 |
| 3237 |
fillorder = 1 |
| 3238 |
photometric = 0 |
| 3239 |
predictor = 1 |
| 3240 |
extrasamples = 1 |
| 3241 |
colormap = None |
| 3242 |
software = "" |
| 3243 |
description = "" |
| 3244 |
description1 = "" |
| 3245 |
|
| 3246 |
def __init__(self, parent, index, keyframe=None): |
| 3247 |
"""Initialize instance from file. |
| 3248 |
|
| 3249 |
The file handle position must be at offset to a valid IFD. |
| 3250 |
|
| 3251 |
""" |
| 3252 |
self.parent = parent |
| 3253 |
self.index = index |
| 3254 |
self.shape = () |
| 3255 |
self._shape = () |
| 3256 |
self.dtype = None |
| 3257 |
self._dtype = None |
| 3258 |
self.axes = "" |
| 3259 |
self.tags = {} |
| 3260 |
|
| 3261 |
self.dataoffsets = () |
| 3262 |
self.databytecounts = () |
| 3263 |
|
| 3264 |
|
| 3265 |
fh = parent.filehandle |
| 3266 |
self.offset = fh.tell() |
| 3267 |
try: |
| 3268 |
tagno = struct.unpack(parent.tagnoformat, fh.read(parent.tagnosize))[0] |
| 3269 |
if tagno > 4096: |
| 3270 |
raise ValueError("suspicious number of tags") |
| 3271 |
except Exception: |
| 3272 |
raise ValueError("corrupted tag list at offset %i" % self.offset) |
| 3273 |
|
| 3274 |
tagsize = parent.tagsize |
| 3275 |
data = fh.read(tagsize * tagno) |
| 3276 |
tags = self.tags |
| 3277 |
index = -tagsize |
| 3278 |
for _ in range(tagno): |
| 3279 |
index += tagsize |
| 3280 |
try: |
| 3281 |
tag = TiffTag(self.parent, data[index : index + tagsize]) |
| 3282 |
except TiffTag.Error as e: |
| 3283 |
warnings.warn(str(e)) |
| 3284 |
continue |
| 3285 |
tagname = tag.name |
| 3286 |
if tagname not in tags: |
| 3287 |
name = tagname |
| 3288 |
tags[name] = tag |
| 3289 |
else: |
| 3290 |
|
| 3291 |
|
| 3292 |
i = 1 |
| 3293 |
while True: |
| 3294 |
name = "%s%i" % (tagname, i) |
| 3295 |
if name not in tags: |
| 3296 |
tags[name] = tag |
| 3297 |
break |
| 3298 |
name = TIFF.TAG_ATTRIBUTES.get(name, "") |
| 3299 |
if name: |
| 3300 |
if name[:3] in "sof des" and not isinstance(tag.value, str): |
| 3301 |
pass |
| 3302 |
else: |
| 3303 |
setattr(self, name, tag.value) |
| 3304 |
|
| 3305 |
if not tags: |
| 3306 |
return |
| 3307 |
|
| 3308 |
|
| 3309 |
if self.is_andor: |
| 3310 |
self.andor_tags |
| 3311 |
elif self.is_epics: |
| 3312 |
self.epics_tags |
| 3313 |
|
| 3314 |
if self.is_lsm or (self.index and self.parent.is_lsm): |
| 3315 |
|
| 3316 |
self.tags["BitsPerSample"]._fix_lsm_bitspersample(self) |
| 3317 |
|
| 3318 |
if self.is_vista or (self.index and self.parent.is_vista): |
| 3319 |
|
| 3320 |
self.imagedepth = 1 |
| 3321 |
|
| 3322 |
if self.is_stk and "UIC1tag" in tags and not tags["UIC1tag"].value: |
| 3323 |
|
| 3324 |
uic1tag = tags["UIC1tag"] |
| 3325 |
fh.seek(uic1tag.valueoffset) |
| 3326 |
tags["UIC1tag"].value = read_uic1tag( |
| 3327 |
fh, |
| 3328 |
self.parent.byteorder, |
| 3329 |
uic1tag.dtype, |
| 3330 |
uic1tag.count, |
| 3331 |
None, |
| 3332 |
tags["UIC2tag"].count, |
| 3333 |
) |
| 3334 |
|
| 3335 |
if "IJMetadata" in tags: |
| 3336 |
|
| 3337 |
try: |
| 3338 |
tags["IJMetadata"].value = imagej_metadata( |
| 3339 |
tags["IJMetadata"].value, |
| 3340 |
tags["IJMetadataByteCounts"].value, |
| 3341 |
self.parent.byteorder, |
| 3342 |
) |
| 3343 |
except Exception as e: |
| 3344 |
warnings.warn(str(e)) |
| 3345 |
|
| 3346 |
if "BitsPerSample" in tags: |
| 3347 |
tag = tags["BitsPerSample"] |
| 3348 |
if tag.count == 1: |
| 3349 |
self.bitspersample = tag.value |
| 3350 |
else: |
| 3351 |
|
| 3352 |
value = tag.value[: self.samplesperpixel] |
| 3353 |
if any((v - value[0] for v in value)): |
| 3354 |
self.bitspersample = value |
| 3355 |
else: |
| 3356 |
self.bitspersample = value[0] |
| 3357 |
|
| 3358 |
if "SampleFormat" in tags: |
| 3359 |
tag = tags["SampleFormat"] |
| 3360 |
if tag.count == 1: |
| 3361 |
self.sampleformat = tag.value |
| 3362 |
else: |
| 3363 |
value = tag.value[: self.samplesperpixel] |
| 3364 |
if any((v - value[0] for v in value)): |
| 3365 |
self.sampleformat = value |
| 3366 |
else: |
| 3367 |
self.sampleformat = value[0] |
| 3368 |
|
| 3369 |
if "ImageLength" in tags: |
| 3370 |
if "RowsPerStrip" not in tags or tags["RowsPerStrip"].count > 1: |
| 3371 |
self.rowsperstrip = self.imagelength |
| 3372 |
|
| 3373 |
|
| 3374 |
|
| 3375 |
|
| 3376 |
|
| 3377 |
dtype = self.sampleformat, self.bitspersample |
| 3378 |
dtype = TIFF.SAMPLE_DTYPES.get(dtype, None) |
| 3379 |
if dtype is not None: |
| 3380 |
dtype = numpy.dtype(dtype) |
| 3381 |
self.dtype = self._dtype = dtype |
| 3382 |
|
| 3383 |
|
| 3384 |
imagelength = self.imagelength |
| 3385 |
imagewidth = self.imagewidth |
| 3386 |
imagedepth = self.imagedepth |
| 3387 |
samplesperpixel = self.samplesperpixel |
| 3388 |
|
| 3389 |
if self.is_stk: |
| 3390 |
assert self.imagedepth == 1 |
| 3391 |
uictag = tags["UIC2tag"].value |
| 3392 |
planes = tags["UIC2tag"].count |
| 3393 |
if self.planarconfig == 1: |
| 3394 |
self._shape = (planes, 1, 1, imagelength, imagewidth, samplesperpixel) |
| 3395 |
if samplesperpixel == 1: |
| 3396 |
self.shape = (planes, imagelength, imagewidth) |
| 3397 |
self.axes = "YX" |
| 3398 |
else: |
| 3399 |
self.shape = (planes, imagelength, imagewidth, samplesperpixel) |
| 3400 |
self.axes = "YXS" |
| 3401 |
else: |
| 3402 |
self._shape = (planes, samplesperpixel, 1, imagelength, imagewidth, 1) |
| 3403 |
if samplesperpixel == 1: |
| 3404 |
self.shape = (planes, imagelength, imagewidth) |
| 3405 |
self.axes = "YX" |
| 3406 |
else: |
| 3407 |
self.shape = (planes, samplesperpixel, imagelength, imagewidth) |
| 3408 |
self.axes = "SYX" |
| 3409 |
|
| 3410 |
if planes == 1: |
| 3411 |
self.shape = self.shape[1:] |
| 3412 |
elif numpy.all(uictag["ZDistance"] != 0): |
| 3413 |
self.axes = "Z" + self.axes |
| 3414 |
elif numpy.all(numpy.diff(uictag["TimeCreated"]) != 0): |
| 3415 |
self.axes = "T" + self.axes |
| 3416 |
else: |
| 3417 |
self.axes = "I" + self.axes |
| 3418 |
elif self.photometric == 2 or samplesperpixel > 1: |
| 3419 |
if self.planarconfig == 1: |
| 3420 |
self._shape = ( |
| 3421 |
1, |
| 3422 |
1, |
| 3423 |
imagedepth, |
| 3424 |
imagelength, |
| 3425 |
imagewidth, |
| 3426 |
samplesperpixel, |
| 3427 |
) |
| 3428 |
if imagedepth == 1: |
| 3429 |
self.shape = (imagelength, imagewidth, samplesperpixel) |
| 3430 |
self.axes = "YXS" |
| 3431 |
else: |
| 3432 |
self.shape = (imagedepth, imagelength, imagewidth, samplesperpixel) |
| 3433 |
self.axes = "ZYXS" |
| 3434 |
else: |
| 3435 |
self._shape = ( |
| 3436 |
1, |
| 3437 |
samplesperpixel, |
| 3438 |
imagedepth, |
| 3439 |
imagelength, |
| 3440 |
imagewidth, |
| 3441 |
1, |
| 3442 |
) |
| 3443 |
if imagedepth == 1: |
| 3444 |
self.shape = (samplesperpixel, imagelength, imagewidth) |
| 3445 |
self.axes = "SYX" |
| 3446 |
else: |
| 3447 |
self.shape = (samplesperpixel, imagedepth, imagelength, imagewidth) |
| 3448 |
self.axes = "SZYX" |
| 3449 |
else: |
| 3450 |
self._shape = (1, 1, imagedepth, imagelength, imagewidth, 1) |
| 3451 |
if imagedepth == 1: |
| 3452 |
self.shape = (imagelength, imagewidth) |
| 3453 |
self.axes = "YX" |
| 3454 |
else: |
| 3455 |
self.shape = (imagedepth, imagelength, imagewidth) |
| 3456 |
self.axes = "ZYX" |
| 3457 |
|
| 3458 |
|
| 3459 |
if "TileOffsets" in tags: |
| 3460 |
self.dataoffsets = tags["TileOffsets"].value |
| 3461 |
elif "StripOffsets" in tags: |
| 3462 |
self.dataoffsets = tags["StripOffsets"].value |
| 3463 |
else: |
| 3464 |
self.dataoffsets = (0,) |
| 3465 |
|
| 3466 |
if "TileByteCounts" in tags: |
| 3467 |
self.databytecounts = tags["TileByteCounts"].value |
| 3468 |
elif "StripByteCounts" in tags: |
| 3469 |
self.databytecounts = tags["StripByteCounts"].value |
| 3470 |
else: |
| 3471 |
self.databytecounts = (product(self.shape) * (self.bitspersample // 8),) |
| 3472 |
if self.compression != 1: |
| 3473 |
warnings.warn("required ByteCounts tag is missing") |
| 3474 |
|
| 3475 |
assert len(self.shape) == len(self.axes) |
| 3476 |
|
| 3477 |
def asarray( |
| 3478 |
self, |
| 3479 |
out=None, |
| 3480 |
squeeze=True, |
| 3481 |
lock=None, |
| 3482 |
reopen=True, |
| 3483 |
maxsize=2**44, |
| 3484 |
validate=True, |
| 3485 |
): |
| 3486 |
"""Read image data from file and return as numpy array. |
| 3487 |
|
| 3488 |
Raise ValueError if format is unsupported. |
| 3489 |
|
| 3490 |
Parameters |
| 3491 |
---------- |
| 3492 |
out : numpy.ndarray, str, or file-like object; optional |
| 3493 |
Buffer where image data will be saved. |
| 3494 |
If None (default), a new array will be created. |
| 3495 |
If numpy.ndarray, a writable array of compatible dtype and shape. |
| 3496 |
If 'memmap', directly memory-map the image data in the TIFF file |
| 3497 |
if possible; else create a memory-mapped array in a temporary file. |
| 3498 |
If str or open file, the file name or file object used to |
| 3499 |
create a memory-map to an array stored in a binary file on disk. |
| 3500 |
squeeze : bool |
| 3501 |
If True, all length-1 dimensions (except X and Y) are |
| 3502 |
squeezed out from the array. |
| 3503 |
If False, the shape of the returned array might be different from |
| 3504 |
the page.shape. |
| 3505 |
lock : {RLock, NullContext} |
| 3506 |
A reentrant lock used to synchronize reads from file. |
| 3507 |
If None (default), the lock of the parent's filehandle is used. |
| 3508 |
reopen : bool |
| 3509 |
If True (default) and the parent file handle is closed, the file |
| 3510 |
is temporarily re-opened and closed if no exception occurs. |
| 3511 |
maxsize: int or None |
| 3512 |
Maximum size of data before a ValueError is raised. |
| 3513 |
Can be used to catch DOS. Default: 16 TB. |
| 3514 |
validate : bool |
| 3515 |
If True (default), validate various parameters. |
| 3516 |
If None, only validate parameters and return None. |
| 3517 |
|
| 3518 |
""" |
| 3519 |
self_ = self |
| 3520 |
self = self.keyframe |
| 3521 |
|
| 3522 |
if not self._shape or product(self._shape) == 0: |
| 3523 |
return |
| 3524 |
|
| 3525 |
tags = self.tags |
| 3526 |
|
| 3527 |
if validate or validate is None: |
| 3528 |
if maxsize and product(self._shape) > maxsize: |
| 3529 |
raise ValueError("data are too large %s" % str(self._shape)) |
| 3530 |
if self.dtype is None: |
| 3531 |
raise ValueError( |
| 3532 |
"data type not supported: %s%i" |
| 3533 |
% (self.sampleformat, self.bitspersample) |
| 3534 |
) |
| 3535 |
if self.compression not in TIFF.DECOMPESSORS: |
| 3536 |
raise ValueError("cannot decompress %s" % self.compression.name) |
| 3537 |
if "SampleFormat" in tags: |
| 3538 |
tag = tags["SampleFormat"] |
| 3539 |
if tag.count != 1 and any((i - tag.value[0] for i in tag.value)): |
| 3540 |
raise ValueError("sample formats do not match %s" % tag.value) |
| 3541 |
if self.is_chroma_subsampled and ( |
| 3542 |
self.compression != 7 or self.planarconfig == 2 |
| 3543 |
): |
| 3544 |
raise NotImplementedError("chroma subsampling not supported") |
| 3545 |
if validate is None: |
| 3546 |
return |
| 3547 |
|
| 3548 |
fh = self_.parent.filehandle |
| 3549 |
lock = fh.lock if lock is None else lock |
| 3550 |
with lock: |
| 3551 |
closed = fh.closed |
| 3552 |
if closed: |
| 3553 |
if reopen: |
| 3554 |
fh.open() |
| 3555 |
else: |
| 3556 |
raise IOError("file handle is closed") |
| 3557 |
|
| 3558 |
dtype = self._dtype |
| 3559 |
shape = self._shape |
| 3560 |
imagewidth = self.imagewidth |
| 3561 |
imagelength = self.imagelength |
| 3562 |
imagedepth = self.imagedepth |
| 3563 |
bitspersample = self.bitspersample |
| 3564 |
typecode = self.parent.byteorder + dtype.char |
| 3565 |
lsb2msb = self.fillorder == 2 |
| 3566 |
offsets, bytecounts = self_.offsets_bytecounts |
| 3567 |
istiled = self.is_tiled |
| 3568 |
|
| 3569 |
if istiled: |
| 3570 |
tilewidth = self.tilewidth |
| 3571 |
tilelength = self.tilelength |
| 3572 |
tiledepth = self.tiledepth |
| 3573 |
tw = (imagewidth + tilewidth - 1) // tilewidth |
| 3574 |
tl = (imagelength + tilelength - 1) // tilelength |
| 3575 |
td = (imagedepth + tiledepth - 1) // tiledepth |
| 3576 |
shape = ( |
| 3577 |
shape[0], |
| 3578 |
shape[1], |
| 3579 |
td * tiledepth, |
| 3580 |
tl * tilelength, |
| 3581 |
tw * tilewidth, |
| 3582 |
shape[-1], |
| 3583 |
) |
| 3584 |
tileshape = (tiledepth, tilelength, tilewidth, shape[-1]) |
| 3585 |
runlen = tilewidth |
| 3586 |
else: |
| 3587 |
runlen = imagewidth |
| 3588 |
|
| 3589 |
if self.planarconfig == 1: |
| 3590 |
runlen *= self.samplesperpixel |
| 3591 |
|
| 3592 |
if out == "memmap" and self.is_memmappable: |
| 3593 |
with lock: |
| 3594 |
result = fh.memmap_array(typecode, shape, offset=offsets[0]) |
| 3595 |
elif self.is_contiguous: |
| 3596 |
if out is not None: |
| 3597 |
out = create_output(out, shape, dtype) |
| 3598 |
with lock: |
| 3599 |
fh.seek(offsets[0]) |
| 3600 |
result = fh.read_array(typecode, product(shape), out=out) |
| 3601 |
if out is None and not result.dtype.isnative: |
| 3602 |
|
| 3603 |
result.byteswap(True) |
| 3604 |
result = result.view(result.dtype.newbyteorder()) |
| 3605 |
if lsb2msb: |
| 3606 |
reverse_bitorder(result) |
| 3607 |
else: |
| 3608 |
result = create_output(out, shape, dtype) |
| 3609 |
|
| 3610 |
decompress = TIFF.DECOMPESSORS[self.compression] |
| 3611 |
|
| 3612 |
if self.compression == 7: |
| 3613 |
if bitspersample not in (8, 12): |
| 3614 |
raise ValueError("unsupported JPEG precision %i" % bitspersample) |
| 3615 |
if "JPEGTables" in tags: |
| 3616 |
table = tags["JPEGTables"].value |
| 3617 |
else: |
| 3618 |
table = b"" |
| 3619 |
unpack = identityfunc |
| 3620 |
colorspace = TIFF.PHOTOMETRIC(self.photometric).name |
| 3621 |
|
| 3622 |
def decompress( |
| 3623 |
x, |
| 3624 |
func=decompress, |
| 3625 |
table=table, |
| 3626 |
bitspersample=bitspersample, |
| 3627 |
colorspace=colorspace, |
| 3628 |
): |
| 3629 |
return func(x, table, bitspersample, colorspace).reshape(-1) |
| 3630 |
|
| 3631 |
elif bitspersample in (8, 16, 32, 64, 128): |
| 3632 |
if (bitspersample * runlen) % 8: |
| 3633 |
raise ValueError("data and sample size mismatch") |
| 3634 |
|
| 3635 |
def unpack(x, typecode=typecode): |
| 3636 |
if self.predictor == 3: |
| 3637 |
|
| 3638 |
|
| 3639 |
typecode = dtype.char |
| 3640 |
try: |
| 3641 |
|
| 3642 |
return numpy.frombuffer(x, typecode) |
| 3643 |
except ValueError: |
| 3644 |
|
| 3645 |
|
| 3646 |
xlen = (len(x) // (bitspersample // 8)) * (bitspersample // 8) |
| 3647 |
return numpy.frombuffer(x[:xlen], typecode) |
| 3648 |
|
| 3649 |
elif isinstance(bitspersample, tuple): |
| 3650 |
|
| 3651 |
def unpack(x, typecode=typecode, bitspersample=bitspersample): |
| 3652 |
return unpack_rgb(x, typecode, bitspersample) |
| 3653 |
|
| 3654 |
else: |
| 3655 |
|
| 3656 |
def unpack( |
| 3657 |
x, typecode=typecode, bitspersample=bitspersample, runlen=runlen |
| 3658 |
): |
| 3659 |
return unpack_ints(x, typecode, bitspersample, runlen) |
| 3660 |
|
| 3661 |
if istiled: |
| 3662 |
writable = None |
| 3663 |
tw, tl, td, pl = 0, 0, 0, 0 |
| 3664 |
for tile in buffered_read(fh, lock, offsets, bytecounts): |
| 3665 |
if lsb2msb: |
| 3666 |
tile = reverse_bitorder(tile) |
| 3667 |
tile = decompress(tile) |
| 3668 |
tile = unpack(tile) |
| 3669 |
try: |
| 3670 |
tile.shape = tileshape |
| 3671 |
except ValueError: |
| 3672 |
|
| 3673 |
warnings.warn("invalid tile data") |
| 3674 |
t = numpy.zeros(tileshape, dtype).reshape(-1) |
| 3675 |
s = min(tile.size, t.size) |
| 3676 |
t[:s] = tile[:s] |
| 3677 |
tile = t.reshape(tileshape) |
| 3678 |
if self.predictor == 2: |
| 3679 |
if writable is None: |
| 3680 |
writable = tile.flags["WRITEABLE"] |
| 3681 |
if writable: |
| 3682 |
numpy.cumsum(tile, axis=-2, dtype=dtype, out=tile) |
| 3683 |
else: |
| 3684 |
tile = numpy.cumsum(tile, axis=-2, dtype=dtype) |
| 3685 |
elif self.predictor == 3: |
| 3686 |
raise NotImplementedError() |
| 3687 |
result[ |
| 3688 |
0, |
| 3689 |
pl, |
| 3690 |
td : td + tiledepth, |
| 3691 |
tl : tl + tilelength, |
| 3692 |
tw : tw + tilewidth, |
| 3693 |
:, |
| 3694 |
] = tile |
| 3695 |
del tile |
| 3696 |
tw += tilewidth |
| 3697 |
if tw >= shape[4]: |
| 3698 |
tw, tl = 0, tl + tilelength |
| 3699 |
if tl >= shape[3]: |
| 3700 |
tl, td = 0, td + tiledepth |
| 3701 |
if td >= shape[2]: |
| 3702 |
td, pl = 0, pl + 1 |
| 3703 |
result = result[..., :imagedepth, :imagelength, :imagewidth, :] |
| 3704 |
else: |
| 3705 |
strip_size = self.rowsperstrip * self.imagewidth |
| 3706 |
if self.planarconfig == 1: |
| 3707 |
strip_size *= self.samplesperpixel |
| 3708 |
result = result.reshape(-1) |
| 3709 |
index = 0 |
| 3710 |
for strip in buffered_read(fh, lock, offsets, bytecounts): |
| 3711 |
if lsb2msb: |
| 3712 |
strip = reverse_bitorder(strip) |
| 3713 |
strip = decompress(strip) |
| 3714 |
strip = unpack(strip) |
| 3715 |
size = min(result.size, strip.size, strip_size, result.size - index) |
| 3716 |
result[index : index + size] = strip[:size] |
| 3717 |
del strip |
| 3718 |
index += size |
| 3719 |
|
| 3720 |
result.shape = self._shape |
| 3721 |
|
| 3722 |
if self.predictor != 1 and not (istiled and not self.is_contiguous): |
| 3723 |
if self.parent.is_lsm and self.compression == 1: |
| 3724 |
pass |
| 3725 |
elif self.predictor == 2: |
| 3726 |
numpy.cumsum(result, axis=-2, dtype=dtype, out=result) |
| 3727 |
elif self.predictor == 3: |
| 3728 |
result = decode_floats(result) |
| 3729 |
|
| 3730 |
if squeeze: |
| 3731 |
try: |
| 3732 |
result.shape = self.shape |
| 3733 |
except ValueError: |
| 3734 |
warnings.warn( |
| 3735 |
"failed to reshape from %s to %s" |
| 3736 |
% (str(result.shape), str(self.shape)) |
| 3737 |
) |
| 3738 |
|
| 3739 |
if closed: |
| 3740 |
|
| 3741 |
fh.close() |
| 3742 |
return result |
| 3743 |
|
| 3744 |
def asrgb( |
| 3745 |
self, |
| 3746 |
uint8=False, |
| 3747 |
alpha=None, |
| 3748 |
colormap=None, |
| 3749 |
dmin=None, |
| 3750 |
dmax=None, |
| 3751 |
*args, |
| 3752 |
**kwargs, |
| 3753 |
): |
| 3754 |
"""Return image data as RGB(A). |
| 3755 |
|
| 3756 |
Work in progress. |
| 3757 |
|
| 3758 |
""" |
| 3759 |
data = self.asarray(*args, **kwargs) |
| 3760 |
self = self.keyframe |
| 3761 |
photometric = self.photometric |
| 3762 |
PHOTOMETRIC = TIFF.PHOTOMETRIC |
| 3763 |
|
| 3764 |
if photometric == PHOTOMETRIC.PALETTE: |
| 3765 |
colormap = self.colormap |
| 3766 |
if colormap.shape[1] < 2**self.bitspersample or self.dtype.char not in "BH": |
| 3767 |
raise ValueError("cannot apply colormap") |
| 3768 |
if uint8: |
| 3769 |
if colormap.max() > 255: |
| 3770 |
colormap >>= 8 |
| 3771 |
colormap = colormap.astype("uint8") |
| 3772 |
if "S" in self.axes: |
| 3773 |
data = data[..., 0] if self.planarconfig == 1 else data[0] |
| 3774 |
data = apply_colormap(data, colormap) |
| 3775 |
|
| 3776 |
elif photometric == PHOTOMETRIC.RGB: |
| 3777 |
if "ExtraSamples" in self.tags: |
| 3778 |
if alpha is None: |
| 3779 |
alpha = TIFF.EXTRASAMPLE |
| 3780 |
extrasamples = self.extrasamples |
| 3781 |
if self.tags["ExtraSamples"].count == 1: |
| 3782 |
extrasamples = (extrasamples,) |
| 3783 |
for i, exs in enumerate(extrasamples): |
| 3784 |
if exs in alpha: |
| 3785 |
if self.planarconfig == 1: |
| 3786 |
data = data[..., [0, 1, 2, 3 + i]] |
| 3787 |
else: |
| 3788 |
data = data[:, [0, 1, 2, 3 + i]] |
| 3789 |
break |
| 3790 |
else: |
| 3791 |
if self.planarconfig == 1: |
| 3792 |
data = data[..., :3] |
| 3793 |
else: |
| 3794 |
data = data[:, :3] |
| 3795 |
|
| 3796 |
|
| 3797 |
elif photometric == PHOTOMETRIC.MINISBLACK: |
| 3798 |
raise NotImplementedError() |
| 3799 |
elif photometric == PHOTOMETRIC.MINISWHITE: |
| 3800 |
raise NotImplementedError() |
| 3801 |
elif photometric == PHOTOMETRIC.SEPARATED: |
| 3802 |
raise NotImplementedError() |
| 3803 |
else: |
| 3804 |
raise NotImplementedError() |
| 3805 |
return data |
| 3806 |
|
| 3807 |
def aspage(self): |
| 3808 |
return self |
| 3809 |
|
| 3810 |
@property |
| 3811 |
def keyframe(self): |
| 3812 |
return self |
| 3813 |
|
| 3814 |
@keyframe.setter |
| 3815 |
def keyframe(self, index): |
| 3816 |
return |
| 3817 |
|
| 3818 |
@lazyattr |
| 3819 |
def offsets_bytecounts(self): |
| 3820 |
"""Return simplified offsets and bytecounts.""" |
| 3821 |
if self.is_contiguous: |
| 3822 |
offset, byte_count = self.is_contiguous |
| 3823 |
return [offset], [byte_count] |
| 3824 |
return clean_offsets_counts(self.dataoffsets, self.databytecounts) |
| 3825 |
|
| 3826 |
@lazyattr |
| 3827 |
def is_contiguous(self): |
| 3828 |
"""Return offset and size of contiguous data, else None. |
| 3829 |
|
| 3830 |
Excludes prediction and fill_order. |
| 3831 |
|
| 3832 |
""" |
| 3833 |
if self.compression != 1 or self.bitspersample not in (8, 16, 32, 64): |
| 3834 |
return |
| 3835 |
if "TileWidth" in self.tags: |
| 3836 |
if ( |
| 3837 |
self.imagewidth != self.tilewidth |
| 3838 |
or self.imagelength % self.tilelength |
| 3839 |
or self.tilewidth % 16 |
| 3840 |
or self.tilelength % 16 |
| 3841 |
): |
| 3842 |
return |
| 3843 |
if ( |
| 3844 |
"ImageDepth" in self.tags |
| 3845 |
and "TileDepth" in self.tags |
| 3846 |
and ( |
| 3847 |
self.imagelength != self.tilelength |
| 3848 |
or self.imagedepth % self.tiledepth |
| 3849 |
) |
| 3850 |
): |
| 3851 |
return |
| 3852 |
|
| 3853 |
offsets = self.dataoffsets |
| 3854 |
bytecounts = self.databytecounts |
| 3855 |
if len(offsets) == 1: |
| 3856 |
return offsets[0], bytecounts[0] |
| 3857 |
if self.is_stk or all( |
| 3858 |
( |
| 3859 |
offsets[i] + bytecounts[i] == offsets[i + 1] or bytecounts[i + 1] == 0 |
| 3860 |
) |
| 3861 |
for i in range(len(offsets) - 1) |
| 3862 |
): |
| 3863 |
return offsets[0], sum(bytecounts) |
| 3864 |
|
| 3865 |
@lazyattr |
| 3866 |
def is_final(self): |
| 3867 |
"""Return if page's image data are stored in final form. |
| 3868 |
|
| 3869 |
Excludes byte-swapping. |
| 3870 |
|
| 3871 |
""" |
| 3872 |
return ( |
| 3873 |
self.is_contiguous |
| 3874 |
and self.fillorder == 1 |
| 3875 |
and self.predictor == 1 |
| 3876 |
and not self.is_chroma_subsampled |
| 3877 |
) |
| 3878 |
|
| 3879 |
@lazyattr |
| 3880 |
def is_memmappable(self): |
| 3881 |
"""Return if page's image data in file can be memory-mapped.""" |
| 3882 |
return ( |
| 3883 |
self.parent.filehandle.is_file |
| 3884 |
and self.is_final |
| 3885 |
and |
| 3886 |
|
| 3887 |
self.is_contiguous[0] % self.dtype.itemsize == 0 |
| 3888 |
) |
| 3889 |
|
| 3890 |
def __str__(self, detail=0, width=79): |
| 3891 |
"""Return string containing information about page.""" |
| 3892 |
if self.keyframe != self: |
| 3893 |
return TiffFrame.__str__(self, detail) |
| 3894 |
attr = "" |
| 3895 |
for name in ("memmappable", "final", "contiguous"): |
| 3896 |
attr = getattr(self, "is_" + name) |
| 3897 |
if attr: |
| 3898 |
attr = name.upper() |
| 3899 |
break |
| 3900 |
info = " ".join( |
| 3901 |
s |
| 3902 |
for s in ( |
| 3903 |
"x".join(str(i) for i in self.shape), |
| 3904 |
"%s%s" |
| 3905 |
% (TIFF.SAMPLEFORMAT(self.sampleformat).name, self.bitspersample), |
| 3906 |
"|".join( |
| 3907 |
i |
| 3908 |
for i in ( |
| 3909 |
TIFF.PHOTOMETRIC(self.photometric).name, |
| 3910 |
"TILED" if self.is_tiled else "", |
| 3911 |
self.compression.name if self.compression != 1 else "", |
| 3912 |
self.planarconfig.name if self.planarconfig != 1 else "", |
| 3913 |
self.predictor.name if self.predictor != 1 else "", |
| 3914 |
self.fillorder.name if self.fillorder != 1 else "", |
| 3915 |
) |
| 3916 |
if i |
| 3917 |
), |
| 3918 |
attr, |
| 3919 |
"|".join((f.upper() for f in self.flags)), |
| 3920 |
) |
| 3921 |
if s |
| 3922 |
) |
| 3923 |
info = "TiffPage %i @%i %s" % (self.index, self.offset, info) |
| 3924 |
if detail <= 0: |
| 3925 |
return info |
| 3926 |
info = [info] |
| 3927 |
tags = self.tags |
| 3928 |
tlines = [] |
| 3929 |
vlines = [] |
| 3930 |
for tag in sorted(tags.values(), key=lambda x: x.code): |
| 3931 |
value = tag.__str__(width=width + 1) |
| 3932 |
tlines.append(value[:width].strip()) |
| 3933 |
if detail > 1 and len(value) > width: |
| 3934 |
name = tag.name.upper() |
| 3935 |
if detail <= 2 and ("COUNTS" in name or "OFFSETS" in name): |
| 3936 |
value = pformat(tag.value, width=width, height=detail * 4) |
| 3937 |
else: |
| 3938 |
value = pformat(tag.value, width=width, height=detail * 12) |
| 3939 |
vlines.append("%s\n%s" % (tag.name, value)) |
| 3940 |
info.append("\n".join(tlines)) |
| 3941 |
if detail > 1: |
| 3942 |
info.append("\n\n".join(vlines)) |
| 3943 |
if detail > 3: |
| 3944 |
try: |
| 3945 |
info.append( |
| 3946 |
"DATA\n%s" % pformat(self.asarray(), width=width, height=detail * 8) |
| 3947 |
) |
| 3948 |
except Exception: |
| 3949 |
pass |
| 3950 |
return "\n\n".join(info) |
| 3951 |
|
| 3952 |
@lazyattr |
| 3953 |
def flags(self): |
| 3954 |
"""Return set of flags.""" |
| 3955 |
return set( |
| 3956 |
( |
| 3957 |
name.lower() |
| 3958 |
for name in sorted(TIFF.FILE_FLAGS) |
| 3959 |
if getattr(self, "is_" + name) |
| 3960 |
) |
| 3961 |
) |
| 3962 |
|
| 3963 |
@property |
| 3964 |
def ndim(self): |
| 3965 |
"""Return number of array dimensions.""" |
| 3966 |
return len(self.shape) |
| 3967 |
|
| 3968 |
@property |
| 3969 |
def size(self): |
| 3970 |
"""Return number of elements in array.""" |
| 3971 |
return product(self.shape) |
| 3972 |
|
| 3973 |
@lazyattr |
| 3974 |
def andor_tags(self): |
| 3975 |
"""Return consolidated metadata from Andor tags as dict. |
| 3976 |
|
| 3977 |
Remove Andor tags from self.tags. |
| 3978 |
|
| 3979 |
""" |
| 3980 |
if not self.is_andor: |
| 3981 |
return |
| 3982 |
tags = self.tags |
| 3983 |
result = {"Id": tags["AndorId"].value} |
| 3984 |
for tag in list(self.tags.values()): |
| 3985 |
code = tag.code |
| 3986 |
if not 4864 < code < 5031: |
| 3987 |
continue |
| 3988 |
value = tag.value |
| 3989 |
name = tag.name[5:] if len(tag.name) > 5 else tag.name |
| 3990 |
result[name] = value |
| 3991 |
del tags[tag.name] |
| 3992 |
return result |
| 3993 |
|
| 3994 |
@lazyattr |
| 3995 |
def epics_tags(self): |
| 3996 |
"""Return consolidated metadata from EPICS areaDetector tags as dict. |
| 3997 |
|
| 3998 |
Remove areaDetector tags from self.tags. |
| 3999 |
|
| 4000 |
""" |
| 4001 |
if not self.is_epics: |
| 4002 |
return |
| 4003 |
result = {} |
| 4004 |
tags = self.tags |
| 4005 |
for tag in list(self.tags.values()): |
| 4006 |
code = tag.code |
| 4007 |
if not 65000 <= code < 65500: |
| 4008 |
continue |
| 4009 |
value = tag.value |
| 4010 |
if code == 65000: |
| 4011 |
result["timeStamp"] = datetime.datetime.fromtimestamp(float(value)) |
| 4012 |
elif code == 65001: |
| 4013 |
result["uniqueID"] = int(value) |
| 4014 |
elif code == 65002: |
| 4015 |
result["epicsTSSec"] = int(value) |
| 4016 |
elif code == 65003: |
| 4017 |
result["epicsTSNsec"] = int(value) |
| 4018 |
else: |
| 4019 |
key, value = value.split(":", 1) |
| 4020 |
result[key] = astype(value) |
| 4021 |
del tags[tag.name] |
| 4022 |
return result |
| 4023 |
|
| 4024 |
@lazyattr |
| 4025 |
def geotiff_tags(self): |
| 4026 |
"""Return consolidated metadata from GeoTIFF tags as dict.""" |
| 4027 |
if not self.is_geotiff: |
| 4028 |
return |
| 4029 |
tags = self.tags |
| 4030 |
|
| 4031 |
gkd = tags["GeoKeyDirectoryTag"].value |
| 4032 |
if gkd[0] != 1: |
| 4033 |
warnings.warn("invalid GeoKeyDirectoryTag") |
| 4034 |
return {} |
| 4035 |
|
| 4036 |
result = { |
| 4037 |
"KeyDirectoryVersion": gkd[0], |
| 4038 |
"KeyRevision": gkd[1], |
| 4039 |
"KeyRevisionMinor": gkd[2], |
| 4040 |
|
| 4041 |
} |
| 4042 |
|
| 4043 |
geokeys = TIFF.GEO_KEYS |
| 4044 |
geocodes = TIFF.GEO_CODES |
| 4045 |
for index in range(gkd[3]): |
| 4046 |
keyid, tagid, count, offset = gkd[4 + index * 4 : index * 4 + 8] |
| 4047 |
keyid = geokeys.get(keyid, keyid) |
| 4048 |
if tagid == 0: |
| 4049 |
value = offset |
| 4050 |
else: |
| 4051 |
tagname = TIFF.TAGS[tagid] |
| 4052 |
|
| 4053 |
value = tags[tagname].value[offset : offset + count] |
| 4054 |
if tagid == 34737 and count > 1 and value[-1] == "|": |
| 4055 |
value = value[:-1] |
| 4056 |
value = value if count > 1 else value[0] |
| 4057 |
if keyid in geocodes: |
| 4058 |
try: |
| 4059 |
value = geocodes[keyid](value) |
| 4060 |
except Exception: |
| 4061 |
pass |
| 4062 |
result[keyid] = value |
| 4063 |
|
| 4064 |
if "IntergraphMatrixTag" in tags: |
| 4065 |
value = tags["IntergraphMatrixTag"].value |
| 4066 |
value = numpy.array(value) |
| 4067 |
if len(value) == 16: |
| 4068 |
value = value.reshape((4, 4)).tolist() |
| 4069 |
result["IntergraphMatrix"] = value |
| 4070 |
if "ModelPixelScaleTag" in tags: |
| 4071 |
value = numpy.array(tags["ModelPixelScaleTag"].value).tolist() |
| 4072 |
result["ModelPixelScale"] = value |
| 4073 |
if "ModelTiepointTag" in tags: |
| 4074 |
value = tags["ModelTiepointTag"].value |
| 4075 |
value = numpy.array(value).reshape((-1, 6)).squeeze().tolist() |
| 4076 |
result["ModelTiepoint"] = value |
| 4077 |
if "ModelTransformationTag" in tags: |
| 4078 |
value = tags["ModelTransformationTag"].value |
| 4079 |
value = numpy.array(value).reshape((4, 4)).tolist() |
| 4080 |
result["ModelTransformation"] = value |
| 4081 |
elif False: |
| 4082 |
|
| 4083 |
sx, sy, sz = tags["ModelPixelScaleTag"].value |
| 4084 |
tiepoints = tags["ModelTiepointTag"].value |
| 4085 |
transforms = [] |
| 4086 |
for tp in range(0, len(tiepoints), 6): |
| 4087 |
i, j, k, x, y, z = tiepoints[tp : tp + 6] |
| 4088 |
transforms.append( |
| 4089 |
[ |
| 4090 |
[sx, 0.0, 0.0, x - i * sx], |
| 4091 |
[0.0, -sy, 0.0, y + j * sy], |
| 4092 |
[0.0, 0.0, sz, z - k * sz], |
| 4093 |
[0.0, 0.0, 0.0, 1.0], |
| 4094 |
] |
| 4095 |
) |
| 4096 |
if len(tiepoints) == 6: |
| 4097 |
transforms = transforms[0] |
| 4098 |
result["ModelTransformation"] = transforms |
| 4099 |
|
| 4100 |
if "RPCCoefficientTag" in tags: |
| 4101 |
rpcc = tags["RPCCoefficientTag"].value |
| 4102 |
result["RPCCoefficient"] = { |
| 4103 |
"ERR_BIAS": rpcc[0], |
| 4104 |
"ERR_RAND": rpcc[1], |
| 4105 |
"LINE_OFF": rpcc[2], |
| 4106 |
"SAMP_OFF": rpcc[3], |
| 4107 |
"LAT_OFF": rpcc[4], |
| 4108 |
"LONG_OFF": rpcc[5], |
| 4109 |
"HEIGHT_OFF": rpcc[6], |
| 4110 |
"LINE_SCALE": rpcc[7], |
| 4111 |
"SAMP_SCALE": rpcc[8], |
| 4112 |
"LAT_SCALE": rpcc[9], |
| 4113 |
"LONG_SCALE": rpcc[10], |
| 4114 |
"HEIGHT_SCALE": rpcc[11], |
| 4115 |
"LINE_NUM_COEFF": rpcc[12:33], |
| 4116 |
"LINE_DEN_COEFF ": rpcc[33:53], |
| 4117 |
"SAMP_NUM_COEFF": rpcc[53:73], |
| 4118 |
"SAMP_DEN_COEFF": rpcc[73:], |
| 4119 |
} |
| 4120 |
|
| 4121 |
return result |
| 4122 |
|
| 4123 |
@property |
| 4124 |
def is_tiled(self): |
| 4125 |
"""Page contains tiled image.""" |
| 4126 |
return "TileWidth" in self.tags |
| 4127 |
|
| 4128 |
@property |
| 4129 |
def is_reduced(self): |
| 4130 |
"""Page is reduced image of another image.""" |
| 4131 |
return "NewSubfileType" in self.tags and self.tags["NewSubfileType"].value & 1 |
| 4132 |
|
| 4133 |
@property |
| 4134 |
def is_chroma_subsampled(self): |
| 4135 |
"""Page contains chroma subsampled image.""" |
| 4136 |
return "YCbCrSubSampling" in self.tags and self.tags[ |
| 4137 |
"YCbCrSubSampling" |
| 4138 |
].value != (1, 1) |
| 4139 |
|
| 4140 |
@lazyattr |
| 4141 |
def is_imagej(self): |
| 4142 |
"""Return ImageJ description if exists, else None.""" |
| 4143 |
for description in (self.description, self.description1): |
| 4144 |
if not description: |
| 4145 |
return |
| 4146 |
if description[:7] == "ImageJ=": |
| 4147 |
return description |
| 4148 |
|
| 4149 |
@lazyattr |
| 4150 |
def is_shaped(self): |
| 4151 |
"""Return description containing array shape if exists, else None.""" |
| 4152 |
for description in (self.description, self.description1): |
| 4153 |
if not description: |
| 4154 |
return |
| 4155 |
if description[:1] == "{" and '"shape":' in description: |
| 4156 |
return description |
| 4157 |
if description[:6] == "shape=": |
| 4158 |
return description |
| 4159 |
|
| 4160 |
@property |
| 4161 |
def is_mdgel(self): |
| 4162 |
"""Page contains MDFileTag tag.""" |
| 4163 |
return "MDFileTag" in self.tags |
| 4164 |
|
| 4165 |
@property |
| 4166 |
def is_mediacy(self): |
| 4167 |
"""Page contains Media Cybernetics Id tag.""" |
| 4168 |
return "MC_Id" in self.tags and self.tags["MC_Id"].value[:7] == b"MC TIFF" |
| 4169 |
|
| 4170 |
@property |
| 4171 |
def is_stk(self): |
| 4172 |
"""Page contains UIC2Tag tag.""" |
| 4173 |
return "UIC2tag" in self.tags |
| 4174 |
|
| 4175 |
@property |
| 4176 |
def is_lsm(self): |
| 4177 |
"""Page contains CZ_LSMINFO tag.""" |
| 4178 |
return "CZ_LSMINFO" in self.tags |
| 4179 |
|
| 4180 |
@property |
| 4181 |
def is_fluoview(self): |
| 4182 |
"""Page contains FluoView MM_STAMP tag.""" |
| 4183 |
return "MM_Stamp" in self.tags |
| 4184 |
|
| 4185 |
@property |
| 4186 |
def is_nih(self): |
| 4187 |
"""Page contains NIH image header.""" |
| 4188 |
return "NIHImageHeader" in self.tags |
| 4189 |
|
| 4190 |
@property |
| 4191 |
def is_sgi(self): |
| 4192 |
"""Page contains SGI image and tile depth tags.""" |
| 4193 |
return "ImageDepth" in self.tags and "TileDepth" in self.tags |
| 4194 |
|
| 4195 |
@property |
| 4196 |
def is_vista(self): |
| 4197 |
"""Software tag is 'ISS Vista'.""" |
| 4198 |
return self.software == "ISS Vista" |
| 4199 |
|
| 4200 |
@property |
| 4201 |
def is_metaseries(self): |
| 4202 |
"""Page contains MDS MetaSeries metadata in ImageDescription tag.""" |
| 4203 |
if self.index > 1 or self.software != "MetaSeries": |
| 4204 |
return False |
| 4205 |
d = self.description |
| 4206 |
return d.startswith("<MetaData>") and d.endswith("</MetaData>") |
| 4207 |
|
| 4208 |
@property |
| 4209 |
def is_ome(self): |
| 4210 |
"""Page contains OME-XML in ImageDescription tag.""" |
| 4211 |
if self.index > 1 or not self.description: |
| 4212 |
return False |
| 4213 |
d = self.description |
| 4214 |
return d[:14] == "<?xml version=" and d[-6:] == "</OME>" |
| 4215 |
|
| 4216 |
@property |
| 4217 |
def is_scn(self): |
| 4218 |
"""Page contains Leica SCN XML in ImageDescription tag.""" |
| 4219 |
if self.index > 1 or not self.description: |
| 4220 |
return False |
| 4221 |
d = self.description |
| 4222 |
return d[:14] == "<?xml version=" and d[-6:] == "</scn>" |
| 4223 |
|
| 4224 |
@property |
| 4225 |
def is_micromanager(self): |
| 4226 |
"""Page contains Micro-Manager metadata.""" |
| 4227 |
return "MicroManagerMetadata" in self.tags |
| 4228 |
|
| 4229 |
@property |
| 4230 |
def is_andor(self): |
| 4231 |
"""Page contains Andor Technology tags.""" |
| 4232 |
return "AndorId" in self.tags |
| 4233 |
|
| 4234 |
@property |
| 4235 |
def is_pilatus(self): |
| 4236 |
"""Page contains Pilatus tags.""" |
| 4237 |
return self.software[:8] == "TVX TIFF" and self.description[:2] == "# " |
| 4238 |
|
| 4239 |
@property |
| 4240 |
def is_epics(self): |
| 4241 |
"""Page contains EPICS areaDetector tags.""" |
| 4242 |
return ( |
| 4243 |
self.description == "EPICS areaDetector" |
| 4244 |
or self.software == "EPICS areaDetector" |
| 4245 |
) |
| 4246 |
|
| 4247 |
@property |
| 4248 |
def is_tvips(self): |
| 4249 |
"""Page contains TVIPS metadata.""" |
| 4250 |
return "TVIPS" in self.tags |
| 4251 |
|
| 4252 |
@property |
| 4253 |
def is_fei(self): |
| 4254 |
"""Page contains SFEG or HELIOS metadata.""" |
| 4255 |
return "FEI_SFEG" in self.tags or "FEI_HELIOS" in self.tags |
| 4256 |
|
| 4257 |
@property |
| 4258 |
def is_sem(self): |
| 4259 |
"""Page contains Zeiss SEM metadata.""" |
| 4260 |
return "CZ_SEM" in self.tags |
| 4261 |
|
| 4262 |
@property |
| 4263 |
def is_svs(self): |
| 4264 |
"""Page contains Aperio metadata.""" |
| 4265 |
return self.description[:20] == "Aperio Image Library" |
| 4266 |
|
| 4267 |
@property |
| 4268 |
def is_scanimage(self): |
| 4269 |
"""Page contains ScanImage metadata.""" |
| 4270 |
return ( |
| 4271 |
self.description[:12] == "state.config" |
| 4272 |
or self.software[:22] == "SI.LINE_FORMAT_VERSION" |
| 4273 |
or "scanimage.SI." in self.description[-256:] |
| 4274 |
) |
| 4275 |
|
| 4276 |
@property |
| 4277 |
def is_qptiff(self): |
| 4278 |
"""Page contains PerkinElmer tissue images metadata.""" |
| 4279 |
|
| 4280 |
|
| 4281 |
return self.software[:15] == "PerkinElmer-QPI" |
| 4282 |
|
| 4283 |
@property |
| 4284 |
def is_geotiff(self): |
| 4285 |
"""Page contains GeoTIFF metadata.""" |
| 4286 |
return "GeoKeyDirectoryTag" in self.tags |
| 4287 |
|
| 4288 |
|
| 4289 |
class TiffFrame(object): |
| 4290 |
"""Lightweight TIFF image file directory (IFD). |
| 4291 |
|
| 4292 |
Only a limited number of tag values are read from file, e.g. StripOffsets, |
| 4293 |
and StripByteCounts. Other tag values are assumed to be identical with a |
| 4294 |
specified TiffPage instance, the keyframe. |
| 4295 |
|
| 4296 |
TiffFrame is intended to reduce resource usage and speed up reading data |
| 4297 |
from file, not for introspection of metadata. |
| 4298 |
|
| 4299 |
Not compatible with Python 2. |
| 4300 |
|
| 4301 |
""" |
| 4302 |
|
| 4303 |
__slots__ = ( |
| 4304 |
"keyframe", |
| 4305 |
"parent", |
| 4306 |
"index", |
| 4307 |
"offset", |
| 4308 |
"dataoffsets", |
| 4309 |
"databytecounts", |
| 4310 |
) |
| 4311 |
|
| 4312 |
is_mdgel = False |
| 4313 |
tags = {} |
| 4314 |
|
| 4315 |
def __init__(self, parent, index, keyframe): |
| 4316 |
"""Read specified tags from file. |
| 4317 |
|
| 4318 |
The file handle position must be at the offset to a valid IFD. |
| 4319 |
|
| 4320 |
""" |
| 4321 |
self.keyframe = keyframe |
| 4322 |
self.parent = parent |
| 4323 |
self.index = index |
| 4324 |
self.dataoffsets = None |
| 4325 |
self.databytecounts = None |
| 4326 |
|
| 4327 |
unpack = struct.unpack |
| 4328 |
fh = parent.filehandle |
| 4329 |
self.offset = fh.tell() |
| 4330 |
try: |
| 4331 |
tagno = unpack(parent.tagnoformat, fh.read(parent.tagnosize))[0] |
| 4332 |
if tagno > 4096: |
| 4333 |
raise ValueError("suspicious number of tags") |
| 4334 |
except Exception: |
| 4335 |
raise ValueError("corrupted page list at offset %i" % self.offset) |
| 4336 |
|
| 4337 |
|
| 4338 |
tagcodes = {273, 279, 324, 325} |
| 4339 |
tagsize = parent.tagsize |
| 4340 |
codeformat = parent.tagformat1[:2] |
| 4341 |
|
| 4342 |
data = fh.read(tagsize * tagno) |
| 4343 |
index = -tagsize |
| 4344 |
for _ in range(tagno): |
| 4345 |
index += tagsize |
| 4346 |
code = unpack(codeformat, data[index : index + 2])[0] |
| 4347 |
if code not in tagcodes: |
| 4348 |
continue |
| 4349 |
try: |
| 4350 |
tag = TiffTag(parent, data[index : index + tagsize]) |
| 4351 |
except TiffTag.Error as e: |
| 4352 |
warnings.warn(str(e)) |
| 4353 |
continue |
| 4354 |
if code == 273 or code == 324: |
| 4355 |
setattr(self, "dataoffsets", tag.value) |
| 4356 |
elif code == 279 or code == 325: |
| 4357 |
setattr(self, "databytecounts", tag.value) |
| 4358 |
|
| 4359 |
|
| 4360 |
|
| 4361 |
|
| 4362 |
|
| 4363 |
|
| 4364 |
|
| 4365 |
|
| 4366 |
|
| 4367 |
def aspage(self): |
| 4368 |
"""Return TiffPage from file.""" |
| 4369 |
self.parent.filehandle.seek(self.offset) |
| 4370 |
return TiffPage(self.parent, index=self.index, keyframe=None) |
| 4371 |
|
| 4372 |
def asarray(self, *args, **kwargs): |
| 4373 |
"""Read image data from file and return as numpy array.""" |
| 4374 |
|
| 4375 |
|
| 4376 |
|
| 4377 |
kwargs["validate"] = False |
| 4378 |
return TiffPage.asarray(self, *args, **kwargs) |
| 4379 |
|
| 4380 |
def asrgb(self, *args, **kwargs): |
| 4381 |
"""Read image data from file and return RGB image as numpy array.""" |
| 4382 |
kwargs["validate"] = False |
| 4383 |
return TiffPage.asrgb(self, *args, **kwargs) |
| 4384 |
|
| 4385 |
@property |
| 4386 |
def offsets_bytecounts(self): |
| 4387 |
"""Return simplified offsets and bytecounts.""" |
| 4388 |
if self.keyframe.is_contiguous: |
| 4389 |
return self.dataoffsets[:1], self.keyframe.is_contiguous[1:] |
| 4390 |
return clean_offsets_counts(self.dataoffsets, self.databytecounts) |
| 4391 |
|
| 4392 |
@property |
| 4393 |
def is_contiguous(self): |
| 4394 |
"""Return offset and size of contiguous data, else None.""" |
| 4395 |
if self.keyframe.is_contiguous: |
| 4396 |
return self.dataoffsets[0], self.keyframe.is_contiguous[1] |
| 4397 |
|
| 4398 |
@property |
| 4399 |
def is_memmappable(self): |
| 4400 |
"""Return if page's image data in file can be memory-mapped.""" |
| 4401 |
return self.keyframe.is_memmappable |
| 4402 |
|
| 4403 |
def __getattr__(self, name): |
| 4404 |
"""Return attribute from keyframe.""" |
| 4405 |
if name in TIFF.FRAME_ATTRS: |
| 4406 |
return getattr(self.keyframe, name) |
| 4407 |
|
| 4408 |
|
| 4409 |
raise AttributeError( |
| 4410 |
"'%s' object has no attribute '%s'" % (self.__class__.__name__, name) |
| 4411 |
) |
| 4412 |
|
| 4413 |
def __str__(self, detail=0): |
| 4414 |
"""Return string containing information about frame.""" |
| 4415 |
info = " ".join( |
| 4416 |
s for s in ("x".join(str(i) for i in self.shape), str(self.dtype)) |
| 4417 |
) |
| 4418 |
return "TiffFrame %i @%i %s" % (self.index, self.offset, info) |
| 4419 |
|
| 4420 |
|
| 4421 |
class TiffTag(object): |
| 4422 |
"""TIFF tag structure. |
| 4423 |
|
| 4424 |
Attributes |
| 4425 |
---------- |
| 4426 |
name : string |
| 4427 |
Name of tag. |
| 4428 |
code : int |
| 4429 |
Decimal code of tag. |
| 4430 |
dtype : str |
| 4431 |
Datatype of tag data. One of TIFF DATA_FORMATS. |
| 4432 |
count : int |
| 4433 |
Number of values. |
| 4434 |
value : various types |
| 4435 |
Tag data as Python object. |
| 4436 |
ImageSourceData : int |
| 4437 |
Location of value in file. |
| 4438 |
|
| 4439 |
All attributes are read-only. |
| 4440 |
|
| 4441 |
""" |
| 4442 |
|
| 4443 |
__slots__ = ("code", "count", "dtype", "value", "valueoffset") |
| 4444 |
|
| 4445 |
class Error(Exception): |
| 4446 |
pass |
| 4447 |
|
| 4448 |
def __init__(self, parent, tagheader, **kwargs): |
| 4449 |
"""Initialize instance from tag header.""" |
| 4450 |
fh = parent.filehandle |
| 4451 |
byteorder = parent.byteorder |
| 4452 |
unpack = struct.unpack |
| 4453 |
offsetsize = parent.offsetsize |
| 4454 |
|
| 4455 |
self.valueoffset = fh.tell() + offsetsize + 4 |
| 4456 |
code, type_ = unpack(parent.tagformat1, tagheader[:4]) |
| 4457 |
count, value = unpack(parent.tagformat2, tagheader[4:]) |
| 4458 |
|
| 4459 |
try: |
| 4460 |
dtype = TIFF.DATA_FORMATS[type_] |
| 4461 |
except KeyError: |
| 4462 |
raise TiffTag.Error("unknown tag data type %i" % type_) |
| 4463 |
|
| 4464 |
fmt = "%s%i%s" % (byteorder, count * int(dtype[0]), dtype[1]) |
| 4465 |
size = struct.calcsize(fmt) |
| 4466 |
if size > offsetsize or code in TIFF.TAG_READERS: |
| 4467 |
self.valueoffset = offset = unpack(parent.offsetformat, value)[0] |
| 4468 |
if offset < 8 or offset > fh.size - size: |
| 4469 |
raise TiffTag.Error("invalid tag value offset") |
| 4470 |
|
| 4471 |
|
| 4472 |
fh.seek(offset) |
| 4473 |
if code in TIFF.TAG_READERS: |
| 4474 |
readfunc = TIFF.TAG_READERS[code] |
| 4475 |
value = readfunc(fh, byteorder, dtype, count, offsetsize) |
| 4476 |
elif type_ == 7 or (count > 1 and dtype[-1] == "B"): |
| 4477 |
value = read_bytes(fh, byteorder, dtype, count, offsetsize) |
| 4478 |
elif code in TIFF.TAGS or dtype[-1] == "s": |
| 4479 |
value = unpack(fmt, fh.read(size)) |
| 4480 |
else: |
| 4481 |
value = read_numpy(fh, byteorder, dtype, count, offsetsize) |
| 4482 |
elif dtype[-1] == "B" or type_ == 7: |
| 4483 |
value = value[:size] |
| 4484 |
else: |
| 4485 |
value = unpack(fmt, value[:size]) |
| 4486 |
|
| 4487 |
process = ( |
| 4488 |
code not in TIFF.TAG_READERS and code not in TIFF.TAG_TUPLE and type_ != 7 |
| 4489 |
) |
| 4490 |
if process and dtype[-1] == "s" and isinstance(value[0], bytes): |
| 4491 |
|
| 4492 |
|
| 4493 |
value = value[0] |
| 4494 |
try: |
| 4495 |
value = bytes2str(stripascii(value).strip()) |
| 4496 |
except UnicodeDecodeError: |
| 4497 |
warnings.warn("tag %i: coercing invalid ASCII to bytes" % code) |
| 4498 |
dtype = "1B" |
| 4499 |
else: |
| 4500 |
if code in TIFF.TAG_ENUM: |
| 4501 |
t = TIFF.TAG_ENUM[code] |
| 4502 |
try: |
| 4503 |
value = tuple(t(v) for v in value) |
| 4504 |
except ValueError as e: |
| 4505 |
warnings.warn(str(e)) |
| 4506 |
if process: |
| 4507 |
if len(value) == 1: |
| 4508 |
value = value[0] |
| 4509 |
|
| 4510 |
self.code = code |
| 4511 |
self.dtype = dtype |
| 4512 |
self.count = count |
| 4513 |
self.value = value |
| 4514 |
|
| 4515 |
@property |
| 4516 |
def name(self): |
| 4517 |
return TIFF.TAGS.get(self.code, str(self.code)) |
| 4518 |
|
| 4519 |
def _fix_lsm_bitspersample(self, parent): |
| 4520 |
"""Correct LSM bitspersample tag. |
| 4521 |
|
| 4522 |
Old LSM writers may use a separate region for two 16-bit values, |
| 4523 |
although they fit into the tag value element of the tag. |
| 4524 |
|
| 4525 |
""" |
| 4526 |
if self.code == 258 and self.count == 2: |
| 4527 |
|
| 4528 |
warnings.warn("correcting LSM bitspersample tag") |
| 4529 |
tof = parent.offsetformat[parent.offsetsize] |
| 4530 |
self.valueoffset = struct.unpack(tof, self._value)[0] |
| 4531 |
parent.filehandle.seek(self.valueoffset) |
| 4532 |
self.value = struct.unpack("<HH", parent.filehandle.read(4)) |
| 4533 |
|
| 4534 |
def __str__(self, detail=0, width=79): |
| 4535 |
"""Return string containing information about tag.""" |
| 4536 |
height = 1 if detail <= 0 else 8 * detail |
| 4537 |
tcode = "%i%s" % (self.count * int(self.dtype[0]), self.dtype[1]) |
| 4538 |
line = ( |
| 4539 |
"TiffTag %i %s %s @%i " |
| 4540 |
% (self.code, self.name, tcode, self.valueoffset)[:width] |
| 4541 |
) |
| 4542 |
|
| 4543 |
if self.code in TIFF.TAG_ENUM: |
| 4544 |
if self.count == 1: |
| 4545 |
value = TIFF.TAG_ENUM[self.code](self.value).name |
| 4546 |
else: |
| 4547 |
value = pformat(tuple(v.name for v in self.value)) |
| 4548 |
else: |
| 4549 |
value = pformat(self.value, width=width, height=height) |
| 4550 |
|
| 4551 |
if detail <= 0: |
| 4552 |
line += value |
| 4553 |
line = line[:width] |
| 4554 |
else: |
| 4555 |
line += "\n" + value |
| 4556 |
return line |
| 4557 |
|
| 4558 |
|
| 4559 |
|
| 4560 |
|
| 4561 |
|
| 4562 |
class TiffFileError(ValueError): |
| 4563 |
pass |
| 4564 |
|
| 4565 |
|
| 4566 |
class TiffPageSeries(object): |
| 4567 |
"""Series of TIFF pages with compatible shape and data type. |
| 4568 |
|
| 4569 |
Attributes |
| 4570 |
---------- |
| 4571 |
pages : list of TiffPage |
| 4572 |
Sequence of TiffPages in series. |
| 4573 |
dtype : numpy.dtype |
| 4574 |
Data type (native byte order) of the image array in series. |
| 4575 |
shape : tuple |
| 4576 |
Dimensions of the image array in series. |
| 4577 |
axes : str |
| 4578 |
Labels of axes in shape. See TiffPage.axes. |
| 4579 |
offset : int or None |
| 4580 |
Position of image data in file if memory-mappable, else None. |
| 4581 |
|
| 4582 |
""" |
| 4583 |
|
| 4584 |
def __init__( |
| 4585 |
self, |
| 4586 |
pages, |
| 4587 |
shape, |
| 4588 |
dtype, |
| 4589 |
axes, |
| 4590 |
parent=None, |
| 4591 |
name=None, |
| 4592 |
transform=None, |
| 4593 |
stype=None, |
| 4594 |
truncated=False, |
| 4595 |
): |
| 4596 |
"""Initialize instance.""" |
| 4597 |
self.index = 0 |
| 4598 |
self._pages = pages |
| 4599 |
self.shape = tuple(shape) |
| 4600 |
self.axes = "".join(axes) |
| 4601 |
self.dtype = numpy.dtype(dtype) |
| 4602 |
self.stype = stype if stype else "" |
| 4603 |
self.name = name if name else "" |
| 4604 |
self.transform = transform |
| 4605 |
if parent: |
| 4606 |
self.parent = parent |
| 4607 |
elif pages: |
| 4608 |
self.parent = pages[0].parent |
| 4609 |
else: |
| 4610 |
self.parent = None |
| 4611 |
if len(pages) == 1 and not truncated: |
| 4612 |
self._len = int(product(self.shape) // product(pages[0].shape)) |
| 4613 |
else: |
| 4614 |
self._len = len(pages) |
| 4615 |
|
| 4616 |
def asarray(self, out=None): |
| 4617 |
"""Return image data from series of TIFF pages as numpy array.""" |
| 4618 |
if self.parent: |
| 4619 |
result = self.parent.asarray(series=self, out=out) |
| 4620 |
if self.transform is not None: |
| 4621 |
result = self.transform(result) |
| 4622 |
return result |
| 4623 |
|
| 4624 |
@lazyattr |
| 4625 |
def offset(self): |
| 4626 |
"""Return offset to series data in file, if any.""" |
| 4627 |
if not self._pages: |
| 4628 |
return |
| 4629 |
|
| 4630 |
pos = 0 |
| 4631 |
for page in self._pages: |
| 4632 |
if page is None: |
| 4633 |
return |
| 4634 |
if not page.is_final: |
| 4635 |
return |
| 4636 |
if not pos: |
| 4637 |
pos = page.is_contiguous[0] + page.is_contiguous[1] |
| 4638 |
continue |
| 4639 |
if pos != page.is_contiguous[0]: |
| 4640 |
return |
| 4641 |
pos += page.is_contiguous[1] |
| 4642 |
|
| 4643 |
page = self._pages[0] |
| 4644 |
offset = page.is_contiguous[0] |
| 4645 |
if (page.is_imagej or page.is_shaped) and len(self._pages) == 1: |
| 4646 |
|
| 4647 |
return offset |
| 4648 |
if pos == offset + product(self.shape) * self.dtype.itemsize: |
| 4649 |
return offset |
| 4650 |
|
| 4651 |
@property |
| 4652 |
def ndim(self): |
| 4653 |
"""Return number of array dimensions.""" |
| 4654 |
return len(self.shape) |
| 4655 |
|
| 4656 |
@property |
| 4657 |
def size(self): |
| 4658 |
"""Return number of elements in array.""" |
| 4659 |
return int(product(self.shape)) |
| 4660 |
|
| 4661 |
@property |
| 4662 |
def pages(self): |
| 4663 |
"""Return sequence of all pages in series.""" |
| 4664 |
|
| 4665 |
return self |
| 4666 |
|
| 4667 |
def __len__(self): |
| 4668 |
"""Return number of TiffPages in series.""" |
| 4669 |
return self._len |
| 4670 |
|
| 4671 |
def __getitem__(self, key): |
| 4672 |
"""Return specified TiffPage.""" |
| 4673 |
if len(self._pages) == 1 and 0 < key < self._len: |
| 4674 |
index = self._pages[0].index |
| 4675 |
return self.parent.pages[index + key] |
| 4676 |
return self._pages[key] |
| 4677 |
|
| 4678 |
def __iter__(self): |
| 4679 |
"""Return iterator over TiffPages in series.""" |
| 4680 |
if len(self._pages) == self._len: |
| 4681 |
for page in self._pages: |
| 4682 |
yield page |
| 4683 |
else: |
| 4684 |
pages = self.parent.pages |
| 4685 |
index = self._pages[0].index |
| 4686 |
for i in range(self._len): |
| 4687 |
yield pages[index + i] |
| 4688 |
|
| 4689 |
def __str__(self): |
| 4690 |
"""Return string with information about series.""" |
| 4691 |
s = " ".join( |
| 4692 |
s |
| 4693 |
for s in ( |
| 4694 |
snipstr("'%s'" % self.name, 20) if self.name else "", |
| 4695 |
"x".join(str(i) for i in self.shape), |
| 4696 |
str(self.dtype), |
| 4697 |
self.axes, |
| 4698 |
self.stype, |
| 4699 |
"%i Pages" % len(self.pages), |
| 4700 |
("Offset=%i" % self.offset) if self.offset else "", |
| 4701 |
) |
| 4702 |
if s |
| 4703 |
) |
| 4704 |
return "TiffPageSeries %i %s" % (self.index, s) |
| 4705 |
|
| 4706 |
|
| 4707 |
class TiffSequence(object): |
| 4708 |
"""Sequence of TIFF files. |
| 4709 |
|
| 4710 |
The image data in all files must match shape, dtype, etc. |
| 4711 |
|
| 4712 |
Attributes |
| 4713 |
---------- |
| 4714 |
files : list |
| 4715 |
List of file names. |
| 4716 |
shape : tuple |
| 4717 |
Shape of image sequence. Excludes shape of image array. |
| 4718 |
axes : str |
| 4719 |
Labels of axes in shape. |
| 4720 |
|
| 4721 |
Examples |
| 4722 |
-------- |
| 4723 |
>>> # read image stack from sequence of TIFF files |
| 4724 |
>>> imsave('temp_C001T001.tif', numpy.random.rand(64, 64)) |
| 4725 |
>>> imsave('temp_C001T002.tif', numpy.random.rand(64, 64)) |
| 4726 |
>>> tifs = TiffSequence('temp_C001*.tif') |
| 4727 |
>>> tifs.shape |
| 4728 |
(1, 2) |
| 4729 |
>>> tifs.axes |
| 4730 |
'CT' |
| 4731 |
>>> data = tifs.asarray() |
| 4732 |
>>> data.shape |
| 4733 |
(1, 2, 64, 64) |
| 4734 |
|
| 4735 |
""" |
| 4736 |
|
| 4737 |
_patterns = {"axes": r""" |
| 4738 |
# matches Olympus OIF and Leica TIFF series |
| 4739 |
_?(?:(q|l|p|a|c|t|x|y|z|ch|tp)(\d{1,4})) |
| 4740 |
_?(?:(q|l|p|a|c|t|x|y|z|ch|tp)(\d{1,4}))? |
| 4741 |
_?(?:(q|l|p|a|c|t|x|y|z|ch|tp)(\d{1,4}))? |
| 4742 |
_?(?:(q|l|p|a|c|t|x|y|z|ch|tp)(\d{1,4}))? |
| 4743 |
_?(?:(q|l|p|a|c|t|x|y|z|ch|tp)(\d{1,4}))? |
| 4744 |
_?(?:(q|l|p|a|c|t|x|y|z|ch|tp)(\d{1,4}))? |
| 4745 |
_?(?:(q|l|p|a|c|t|x|y|z|ch|tp)(\d{1,4}))? |
| 4746 |
"""} |
| 4747 |
|
| 4748 |
class ParseError(Exception): |
| 4749 |
pass |
| 4750 |
|
| 4751 |
def __init__(self, files, imread=TiffFile, pattern="axes", *args, **kwargs): |
| 4752 |
"""Initialize instance from multiple files. |
| 4753 |
|
| 4754 |
Parameters |
| 4755 |
---------- |
| 4756 |
files : str, pathlib.Path, or sequence thereof |
| 4757 |
Glob pattern or sequence of file names. |
| 4758 |
Binary streams are not supported. |
| 4759 |
imread : function or class |
| 4760 |
Image read function or class with asarray function returning numpy |
| 4761 |
array from single file. |
| 4762 |
pattern : str |
| 4763 |
Regular expression pattern that matches axes names and sequence |
| 4764 |
indices in file names. |
| 4765 |
By default, the pattern matches Olympus OIF and Leica TIFF series. |
| 4766 |
|
| 4767 |
""" |
| 4768 |
if isinstance(files, pathlib.Path): |
| 4769 |
files = str(files) |
| 4770 |
if isinstance(files, basestring): |
| 4771 |
files = natural_sorted(glob.glob(files)) |
| 4772 |
files = list(files) |
| 4773 |
if not files: |
| 4774 |
raise ValueError("no files found") |
| 4775 |
if isinstance(files[0], pathlib.Path): |
| 4776 |
files = [str(pathlib.Path(f)) for f in files] |
| 4777 |
elif not isinstance(files[0], basestring): |
| 4778 |
raise ValueError("not a file name") |
| 4779 |
self.files = files |
| 4780 |
|
| 4781 |
if hasattr(imread, "asarray"): |
| 4782 |
|
| 4783 |
_imread = imread |
| 4784 |
|
| 4785 |
def imread(fname, *args, **kwargs): |
| 4786 |
with _imread(fname) as im: |
| 4787 |
return im.asarray(*args, **kwargs) |
| 4788 |
|
| 4789 |
self.imread = imread |
| 4790 |
|
| 4791 |
self.pattern = self._patterns.get(pattern, pattern) |
| 4792 |
try: |
| 4793 |
self._parse() |
| 4794 |
if not self.axes: |
| 4795 |
self.axes = "I" |
| 4796 |
except self.ParseError: |
| 4797 |
self.axes = "I" |
| 4798 |
self.shape = (len(files),) |
| 4799 |
self._startindex = (0,) |
| 4800 |
self._indices = tuple((i,) for i in range(len(files))) |
| 4801 |
|
| 4802 |
def __str__(self): |
| 4803 |
"""Return string with information about image sequence.""" |
| 4804 |
return "\n".join( |
| 4805 |
[ |
| 4806 |
self.files[0], |
| 4807 |
" size: %i" % len(self.files), |
| 4808 |
" axes: %s" % self.axes, |
| 4809 |
" shape: %s" % str(self.shape), |
| 4810 |
] |
| 4811 |
) |
| 4812 |
|
| 4813 |
def __len__(self): |
| 4814 |
return len(self.files) |
| 4815 |
|
| 4816 |
def __enter__(self): |
| 4817 |
return self |
| 4818 |
|
| 4819 |
def __exit__(self, exc_type, exc_value, traceback): |
| 4820 |
self.close() |
| 4821 |
|
| 4822 |
def close(self): |
| 4823 |
pass |
| 4824 |
|
| 4825 |
def asarray(self, out=None, *args, **kwargs): |
| 4826 |
"""Read image data from all files and return as numpy array. |
| 4827 |
|
| 4828 |
The args and kwargs parameters are passed to the imread function. |
| 4829 |
|
| 4830 |
Raise IndexError or ValueError if image shapes do not match. |
| 4831 |
|
| 4832 |
""" |
| 4833 |
im = self.imread(self.files[0], *args, **kwargs) |
| 4834 |
shape = self.shape + im.shape |
| 4835 |
result = create_output(out, shape, dtype=im.dtype) |
| 4836 |
result = result.reshape(-1, *im.shape) |
| 4837 |
for index, fname in zip(self._indices, self.files): |
| 4838 |
index = [i - j for i, j in zip(index, self._startindex)] |
| 4839 |
index = numpy.ravel_multi_index(index, self.shape) |
| 4840 |
im = self.imread(fname, *args, **kwargs) |
| 4841 |
result[index] = im |
| 4842 |
result.shape = shape |
| 4843 |
return result |
| 4844 |
|
| 4845 |
def _parse(self): |
| 4846 |
"""Get axes and shape from file names.""" |
| 4847 |
if not self.pattern: |
| 4848 |
raise self.ParseError("invalid pattern") |
| 4849 |
pattern = re.compile(self.pattern, re.IGNORECASE | re.VERBOSE) |
| 4850 |
matches = pattern.findall(self.files[0]) |
| 4851 |
if not matches: |
| 4852 |
raise self.ParseError("pattern does not match file names") |
| 4853 |
matches = matches[-1] |
| 4854 |
if len(matches) % 2: |
| 4855 |
raise self.ParseError("pattern does not match axis name and index") |
| 4856 |
axes = "".join(m for m in matches[::2] if m) |
| 4857 |
if not axes: |
| 4858 |
raise self.ParseError("pattern does not match file names") |
| 4859 |
|
| 4860 |
indices = [] |
| 4861 |
for fname in self.files: |
| 4862 |
matches = pattern.findall(fname)[-1] |
| 4863 |
if axes != "".join(m for m in matches[::2] if m): |
| 4864 |
raise ValueError("axes do not match within the image sequence") |
| 4865 |
indices.append([int(m) for m in matches[1::2] if m]) |
| 4866 |
shape = tuple(numpy.max(indices, axis=0)) |
| 4867 |
startindex = tuple(numpy.min(indices, axis=0)) |
| 4868 |
shape = tuple(i - j + 1 for i, j in zip(shape, startindex)) |
| 4869 |
if product(shape) != len(self.files): |
| 4870 |
warnings.warn("files are missing. Missing data are zeroed") |
| 4871 |
|
| 4872 |
self.axes = axes.upper() |
| 4873 |
self.shape = shape |
| 4874 |
self._indices = indices |
| 4875 |
self._startindex = startindex |
| 4876 |
|
| 4877 |
|
| 4878 |
class FileHandle(object): |
| 4879 |
"""Binary file handle. |
| 4880 |
|
| 4881 |
A limited, special purpose file handler that can: |
| 4882 |
|
| 4883 |
* handle embedded files (for CZI within CZI files) |
| 4884 |
* re-open closed files (for multi-file formats, such as OME-TIFF) |
| 4885 |
* read and write numpy arrays and records from file like objects |
| 4886 |
|
| 4887 |
Only 'rb' and 'wb' modes are supported. Concurrently reading and writing |
| 4888 |
of the same stream is untested. |
| 4889 |
|
| 4890 |
When initialized from another file handle, do not use it unless this |
| 4891 |
FileHandle is closed. |
| 4892 |
|
| 4893 |
Attributes |
| 4894 |
---------- |
| 4895 |
name : str |
| 4896 |
Name of the file. |
| 4897 |
path : str |
| 4898 |
Absolute path to file. |
| 4899 |
size : int |
| 4900 |
Size of file in bytes. |
| 4901 |
is_file : bool |
| 4902 |
If True, file has a filno and can be memory-mapped. |
| 4903 |
|
| 4904 |
All attributes are read-only. |
| 4905 |
|
| 4906 |
""" |
| 4907 |
|
| 4908 |
__slots__ = ( |
| 4909 |
"_fh", |
| 4910 |
"_file", |
| 4911 |
"_mode", |
| 4912 |
"_name", |
| 4913 |
"_dir", |
| 4914 |
"_lock", |
| 4915 |
"_offset", |
| 4916 |
"_size", |
| 4917 |
"_close", |
| 4918 |
"is_file", |
| 4919 |
) |
| 4920 |
|
| 4921 |
def __init__(self, file, mode="rb", name=None, offset=None, size=None): |
| 4922 |
"""Initialize file handle from file name or another file handle. |
| 4923 |
|
| 4924 |
Parameters |
| 4925 |
---------- |
| 4926 |
file : str, pathlib.Path, binary stream, or FileHandle |
| 4927 |
File name or seekable binary stream, such as an open file |
| 4928 |
or BytesIO. |
| 4929 |
mode : str |
| 4930 |
File open mode in case 'file' is a file name. Must be 'rb' or 'wb'. |
| 4931 |
name : str |
| 4932 |
Optional name of file in case 'file' is a binary stream. |
| 4933 |
offset : int |
| 4934 |
Optional start position of embedded file. By default, this is |
| 4935 |
the current file position. |
| 4936 |
size : int |
| 4937 |
Optional size of embedded file. By default, this is the number |
| 4938 |
of bytes from the 'offset' to the end of the file. |
| 4939 |
|
| 4940 |
""" |
| 4941 |
self._file = file |
| 4942 |
self._fh = None |
| 4943 |
self._mode = mode |
| 4944 |
self._name = name |
| 4945 |
self._dir = "" |
| 4946 |
self._offset = offset |
| 4947 |
self._size = size |
| 4948 |
self._close = True |
| 4949 |
self.is_file = False |
| 4950 |
self._lock = NullContext() |
| 4951 |
self.open() |
| 4952 |
|
| 4953 |
def open(self): |
| 4954 |
"""Open or re-open file.""" |
| 4955 |
if self._fh: |
| 4956 |
return |
| 4957 |
|
| 4958 |
if isinstance(self._file, pathlib.Path): |
| 4959 |
self._file = str(self._file) |
| 4960 |
if isinstance(self._file, basestring): |
| 4961 |
|
| 4962 |
self._file = os.path.realpath(self._file) |
| 4963 |
self._dir, self._name = os.path.split(self._file) |
| 4964 |
self._fh = open(self._file, self._mode) |
| 4965 |
self._close = True |
| 4966 |
if self._offset is None: |
| 4967 |
self._offset = 0 |
| 4968 |
elif isinstance(self._file, FileHandle): |
| 4969 |
|
| 4970 |
self._fh = self._file._fh |
| 4971 |
if self._offset is None: |
| 4972 |
self._offset = 0 |
| 4973 |
self._offset += self._file._offset |
| 4974 |
self._close = False |
| 4975 |
if not self._name: |
| 4976 |
if self._offset: |
| 4977 |
name, ext = os.path.splitext(self._file._name) |
| 4978 |
self._name = "%s@%i%s" % (name, self._offset, ext) |
| 4979 |
else: |
| 4980 |
self._name = self._file._name |
| 4981 |
if self._mode and self._mode != self._file._mode: |
| 4982 |
raise ValueError("FileHandle has wrong mode") |
| 4983 |
self._mode = self._file._mode |
| 4984 |
self._dir = self._file._dir |
| 4985 |
elif hasattr(self._file, "seek"): |
| 4986 |
|
| 4987 |
try: |
| 4988 |
self._file.tell() |
| 4989 |
except Exception: |
| 4990 |
raise ValueError("binary stream is not seekable") |
| 4991 |
self._fh = self._file |
| 4992 |
if self._offset is None: |
| 4993 |
self._offset = self._file.tell() |
| 4994 |
self._close = False |
| 4995 |
if not self._name: |
| 4996 |
try: |
| 4997 |
self._dir, self._name = os.path.split(self._fh.name) |
| 4998 |
except AttributeError: |
| 4999 |
self._name = "Unnamed binary stream" |
| 5000 |
try: |
| 5001 |
self._mode = self._fh.mode |
| 5002 |
except AttributeError: |
| 5003 |
pass |
| 5004 |
else: |
| 5005 |
raise ValueError( |
| 5006 |
"The first parameter must be a file name, " |
| 5007 |
"seekable binary stream, or FileHandle" |
| 5008 |
) |
| 5009 |
|
| 5010 |
if self._offset: |
| 5011 |
self._fh.seek(self._offset) |
| 5012 |
|
| 5013 |
if self._size is None: |
| 5014 |
pos = self._fh.tell() |
| 5015 |
self._fh.seek(self._offset, 2) |
| 5016 |
self._size = self._fh.tell() |
| 5017 |
self._fh.seek(pos) |
| 5018 |
|
| 5019 |
try: |
| 5020 |
self._fh.fileno() |
| 5021 |
self.is_file = True |
| 5022 |
except Exception: |
| 5023 |
self.is_file = False |
| 5024 |
|
| 5025 |
def read(self, size=-1): |
| 5026 |
"""Read 'size' bytes from file, or until EOF is reached.""" |
| 5027 |
if size < 0 and self._offset: |
| 5028 |
size = self._size |
| 5029 |
return self._fh.read(size) |
| 5030 |
|
| 5031 |
def write(self, bytestring): |
| 5032 |
"""Write bytestring to file.""" |
| 5033 |
return self._fh.write(bytestring) |
| 5034 |
|
| 5035 |
def flush(self): |
| 5036 |
"""Flush write buffers if applicable.""" |
| 5037 |
return self._fh.flush() |
| 5038 |
|
| 5039 |
def memmap_array(self, dtype, shape, offset=0, mode="r", order="C"): |
| 5040 |
"""Return numpy.memmap of data stored in file.""" |
| 5041 |
if not self.is_file: |
| 5042 |
raise ValueError("Cannot memory-map file without fileno") |
| 5043 |
return numpy.memmap( |
| 5044 |
self._fh, |
| 5045 |
dtype=dtype, |
| 5046 |
mode=mode, |
| 5047 |
offset=self._offset + offset, |
| 5048 |
shape=shape, |
| 5049 |
order=order, |
| 5050 |
) |
| 5051 |
|
| 5052 |
def read_array( |
| 5053 |
self, dtype, count=-1, sep="", chunksize=2**25, out=None, native=False |
| 5054 |
): |
| 5055 |
"""Return numpy array from file. |
| 5056 |
|
| 5057 |
Work around numpy issue #2230, "numpy.fromfile does not accept |
| 5058 |
StringIO object" https://github.com/numpy/numpy/issues/2230. |
| 5059 |
|
| 5060 |
""" |
| 5061 |
fh = self._fh |
| 5062 |
dtype = numpy.dtype(dtype) |
| 5063 |
size = self._size if count < 0 else count * dtype.itemsize |
| 5064 |
|
| 5065 |
if out is None: |
| 5066 |
try: |
| 5067 |
result = numpy.fromfile(fh, dtype, count, sep) |
| 5068 |
except IOError: |
| 5069 |
|
| 5070 |
data = fh.read(size) |
| 5071 |
result = numpy.frombuffer(data, dtype, count).copy() |
| 5072 |
if native and not result.dtype.isnative: |
| 5073 |
|
| 5074 |
result.byteswap(True) |
| 5075 |
result = result.view(result.dtype.newbyteorder()) |
| 5076 |
return result |
| 5077 |
|
| 5078 |
|
| 5079 |
shape = out.shape |
| 5080 |
size = min(out.nbytes, size) |
| 5081 |
out = out.reshape(-1) |
| 5082 |
index = 0 |
| 5083 |
while size > 0: |
| 5084 |
data = fh.read(min(chunksize, size)) |
| 5085 |
datasize = len(data) |
| 5086 |
if datasize == 0: |
| 5087 |
break |
| 5088 |
size -= datasize |
| 5089 |
data = numpy.frombuffer(data, dtype) |
| 5090 |
out[index : index + data.size] = data |
| 5091 |
index += data.size |
| 5092 |
|
| 5093 |
if hasattr(out, "flush"): |
| 5094 |
out.flush() |
| 5095 |
return out.reshape(shape) |
| 5096 |
|
| 5097 |
def read_record(self, dtype, shape=1, byteorder=None): |
| 5098 |
"""Return numpy record from file.""" |
| 5099 |
rec = numpy.rec |
| 5100 |
try: |
| 5101 |
record = rec.fromfile(self._fh, dtype, shape, byteorder=byteorder) |
| 5102 |
except Exception: |
| 5103 |
dtype = numpy.dtype(dtype) |
| 5104 |
if shape is None: |
| 5105 |
shape = self._size // dtype.itemsize |
| 5106 |
size = product(sequence(shape)) * dtype.itemsize |
| 5107 |
data = self._fh.read(size) |
| 5108 |
record = rec.fromstring(data, dtype, shape, byteorder=byteorder) |
| 5109 |
return record[0] if shape == 1 else record |
| 5110 |
|
| 5111 |
def write_empty(self, size): |
| 5112 |
"""Append size bytes to file. Position must be at end of file.""" |
| 5113 |
if size < 1: |
| 5114 |
return |
| 5115 |
self._fh.seek(size - 1, 1) |
| 5116 |
self._fh.write(b"\x00") |
| 5117 |
|
| 5118 |
def write_array(self, data): |
| 5119 |
"""Write numpy array to binary file.""" |
| 5120 |
try: |
| 5121 |
data.tofile(self._fh) |
| 5122 |
except Exception: |
| 5123 |
|
| 5124 |
self._fh.write(data.tostring()) |
| 5125 |
|
| 5126 |
def tell(self): |
| 5127 |
"""Return file's current position.""" |
| 5128 |
return self._fh.tell() - self._offset |
| 5129 |
|
| 5130 |
def seek(self, offset, whence=0): |
| 5131 |
"""Set file's current position.""" |
| 5132 |
if self._offset: |
| 5133 |
if whence == 0: |
| 5134 |
self._fh.seek(self._offset + offset, whence) |
| 5135 |
return |
| 5136 |
elif whence == 2 and self._size > 0: |
| 5137 |
self._fh.seek(self._offset + self._size + offset, 0) |
| 5138 |
return |
| 5139 |
self._fh.seek(offset, whence) |
| 5140 |
|
| 5141 |
def close(self): |
| 5142 |
"""Close file.""" |
| 5143 |
if self._close and self._fh: |
| 5144 |
self._fh.close() |
| 5145 |
self._fh = None |
| 5146 |
|
| 5147 |
def __enter__(self): |
| 5148 |
return self |
| 5149 |
|
| 5150 |
def __exit__(self, exc_type, exc_value, traceback): |
| 5151 |
self.close() |
| 5152 |
|
| 5153 |
def __getattr__(self, name): |
| 5154 |
"""Return attribute from underlying file object.""" |
| 5155 |
if self._offset: |
| 5156 |
warnings.warn("FileHandle: '%s' not implemented for embedded files" % name) |
| 5157 |
return getattr(self._fh, name) |
| 5158 |
|
| 5159 |
@property |
| 5160 |
def name(self): |
| 5161 |
return self._name |
| 5162 |
|
| 5163 |
@property |
| 5164 |
def dirname(self): |
| 5165 |
return self._dir |
| 5166 |
|
| 5167 |
@property |
| 5168 |
def path(self): |
| 5169 |
return os.path.join(self._dir, self._name) |
| 5170 |
|
| 5171 |
@property |
| 5172 |
def size(self): |
| 5173 |
return self._size |
| 5174 |
|
| 5175 |
@property |
| 5176 |
def closed(self): |
| 5177 |
return self._fh is None |
| 5178 |
|
| 5179 |
@property |
| 5180 |
def lock(self): |
| 5181 |
return self._lock |
| 5182 |
|
| 5183 |
@lock.setter |
| 5184 |
def lock(self, value): |
| 5185 |
self._lock = threading.RLock() if value else NullContext() |
| 5186 |
|
| 5187 |
|
| 5188 |
class NullContext(object): |
| 5189 |
"""Null context manager. |
| 5190 |
|
| 5191 |
>>> with NullContext(): |
| 5192 |
... pass |
| 5193 |
|
| 5194 |
""" |
| 5195 |
|
| 5196 |
def __enter__(self): |
| 5197 |
return self |
| 5198 |
|
| 5199 |
def __exit__(self, exc_type, exc_value, traceback): |
| 5200 |
pass |
| 5201 |
|
| 5202 |
|
| 5203 |
class OpenFileCache(object): |
| 5204 |
"""Keep files open.""" |
| 5205 |
|
| 5206 |
__slots__ = ("files", "past", "lock", "size") |
| 5207 |
|
| 5208 |
def __init__(self, size, lock=None): |
| 5209 |
"""Initialize open file cache.""" |
| 5210 |
self.past = [] |
| 5211 |
self.files = {} |
| 5212 |
self.lock = NullContext() if lock is None else lock |
| 5213 |
self.size = int(size) |
| 5214 |
|
| 5215 |
def open(self, filehandle): |
| 5216 |
"""Re-open file if necessary.""" |
| 5217 |
with self.lock: |
| 5218 |
if filehandle in self.files: |
| 5219 |
self.files[filehandle] += 1 |
| 5220 |
elif filehandle.closed: |
| 5221 |
filehandle.open() |
| 5222 |
self.files[filehandle] = 1 |
| 5223 |
self.past.append(filehandle) |
| 5224 |
|
| 5225 |
def close(self, filehandle): |
| 5226 |
"""Close opened file if no longer used.""" |
| 5227 |
with self.lock: |
| 5228 |
if filehandle in self.files: |
| 5229 |
self.files[filehandle] -= 1 |
| 5230 |
|
| 5231 |
index = 0 |
| 5232 |
size = len(self.past) |
| 5233 |
while size > self.size and index < size: |
| 5234 |
filehandle = self.past[index] |
| 5235 |
if self.files[filehandle] == 0: |
| 5236 |
filehandle.close() |
| 5237 |
del self.files[filehandle] |
| 5238 |
del self.past[index] |
| 5239 |
size -= 1 |
| 5240 |
else: |
| 5241 |
index += 1 |
| 5242 |
|
| 5243 |
def clear(self): |
| 5244 |
"""Close all opened files if not in use.""" |
| 5245 |
with self.lock: |
| 5246 |
for filehandle, refcount in list(self.files.items()): |
| 5247 |
if refcount == 0: |
| 5248 |
filehandle.close() |
| 5249 |
del self.files[filehandle] |
| 5250 |
del self.past[self.past.index(filehandle)] |
| 5251 |
|
| 5252 |
|
| 5253 |
class LazyConst(object): |
| 5254 |
"""Class whose attributes are computed on first access from its methods.""" |
| 5255 |
|
| 5256 |
def __init__(self, cls): |
| 5257 |
self._cls = cls |
| 5258 |
self.__doc__ = getattr(cls, "__doc__") |
| 5259 |
|
| 5260 |
def __getattr__(self, name): |
| 5261 |
func = getattr(self._cls, name) |
| 5262 |
if not callable(func): |
| 5263 |
return func |
| 5264 |
try: |
| 5265 |
value = func() |
| 5266 |
except TypeError: |
| 5267 |
|
| 5268 |
value = func.__func__() |
| 5269 |
setattr(self, name, value) |
| 5270 |
return value |
| 5271 |
|
| 5272 |
|
| 5273 |
@LazyConst |
| 5274 |
class TIFF(object): |
| 5275 |
"""Namespace for module constants.""" |
| 5276 |
|
| 5277 |
def TAGS(): |
| 5278 |
|
| 5279 |
return { |
| 5280 |
11: "ProcessingSoftware", |
| 5281 |
254: "NewSubfileType", |
| 5282 |
255: "SubfileType", |
| 5283 |
256: "ImageWidth", |
| 5284 |
257: "ImageLength", |
| 5285 |
258: "BitsPerSample", |
| 5286 |
259: "Compression", |
| 5287 |
262: "PhotometricInterpretation", |
| 5288 |
263: "Thresholding", |
| 5289 |
264: "CellWidth", |
| 5290 |
265: "CellLength", |
| 5291 |
266: "FillOrder", |
| 5292 |
269: "DocumentName", |
| 5293 |
270: "ImageDescription", |
| 5294 |
271: "Make", |
| 5295 |
272: "Model", |
| 5296 |
273: "StripOffsets", |
| 5297 |
274: "Orientation", |
| 5298 |
277: "SamplesPerPixel", |
| 5299 |
278: "RowsPerStrip", |
| 5300 |
279: "StripByteCounts", |
| 5301 |
280: "MinSampleValue", |
| 5302 |
281: "MaxSampleValue", |
| 5303 |
282: "XResolution", |
| 5304 |
283: "YResolution", |
| 5305 |
284: "PlanarConfiguration", |
| 5306 |
285: "PageName", |
| 5307 |
286: "XPosition", |
| 5308 |
287: "YPosition", |
| 5309 |
288: "FreeOffsets", |
| 5310 |
289: "FreeByteCounts", |
| 5311 |
290: "GrayResponseUnit", |
| 5312 |
291: "GrayResponseCurve", |
| 5313 |
292: "T4Options", |
| 5314 |
293: "T6Options", |
| 5315 |
296: "ResolutionUnit", |
| 5316 |
297: "PageNumber", |
| 5317 |
300: "ColorResponseUnit", |
| 5318 |
301: "TransferFunction", |
| 5319 |
305: "Software", |
| 5320 |
306: "DateTime", |
| 5321 |
315: "Artist", |
| 5322 |
316: "HostComputer", |
| 5323 |
317: "Predictor", |
| 5324 |
318: "WhitePoint", |
| 5325 |
319: "PrimaryChromaticities", |
| 5326 |
320: "ColorMap", |
| 5327 |
321: "HalftoneHints", |
| 5328 |
322: "TileWidth", |
| 5329 |
323: "TileLength", |
| 5330 |
324: "TileOffsets", |
| 5331 |
325: "TileByteCounts", |
| 5332 |
326: "BadFaxLines", |
| 5333 |
327: "CleanFaxData", |
| 5334 |
328: "ConsecutiveBadFaxLines", |
| 5335 |
330: "SubIFDs", |
| 5336 |
332: "InkSet", |
| 5337 |
333: "InkNames", |
| 5338 |
334: "NumberOfInks", |
| 5339 |
336: "DotRange", |
| 5340 |
337: "TargetPrinter", |
| 5341 |
338: "ExtraSamples", |
| 5342 |
339: "SampleFormat", |
| 5343 |
340: "SMinSampleValue", |
| 5344 |
341: "SMaxSampleValue", |
| 5345 |
342: "TransferRange", |
| 5346 |
343: "ClipPath", |
| 5347 |
344: "XClipPathUnits", |
| 5348 |
345: "YClipPathUnits", |
| 5349 |
346: "Indexed", |
| 5350 |
347: "JPEGTables", |
| 5351 |
351: "OPIProxy", |
| 5352 |
400: "GlobalParametersIFD", |
| 5353 |
401: "ProfileType", |
| 5354 |
402: "FaxProfile", |
| 5355 |
403: "CodingMethods", |
| 5356 |
404: "VersionYear", |
| 5357 |
405: "ModeNumber", |
| 5358 |
433: "Decode", |
| 5359 |
434: "DefaultImageColor", |
| 5360 |
435: "T82Options", |
| 5361 |
437: "JPEGTables_", |
| 5362 |
512: "JPEGProc", |
| 5363 |
513: "JPEGInterchangeFormat", |
| 5364 |
514: "JPEGInterchangeFormatLength", |
| 5365 |
515: "JPEGRestartInterval", |
| 5366 |
517: "JPEGLosslessPredictors", |
| 5367 |
518: "JPEGPointTransforms", |
| 5368 |
519: "JPEGQTables", |
| 5369 |
520: "JPEGDCTables", |
| 5370 |
521: "JPEGACTables", |
| 5371 |
529: "YCbCrCoefficients", |
| 5372 |
530: "YCbCrSubSampling", |
| 5373 |
531: "YCbCrPositioning", |
| 5374 |
532: "ReferenceBlackWhite", |
| 5375 |
559: "StripRowCounts", |
| 5376 |
700: "XMP", |
| 5377 |
769: "GDIGamma", |
| 5378 |
770: "ICCProfileDescriptor", |
| 5379 |
771: "SRGBRenderingIntent", |
| 5380 |
800: "ImageTitle", |
| 5381 |
999: "USPTO_Miscellaneous", |
| 5382 |
4864: "AndorId", |
| 5383 |
4869: "AndorTemperature", |
| 5384 |
4876: "AndorExposureTime", |
| 5385 |
4878: "AndorKineticCycleTime", |
| 5386 |
4879: "AndorAccumulations", |
| 5387 |
4881: "AndorAcquisitionCycleTime", |
| 5388 |
4882: "AndorReadoutTime", |
| 5389 |
4884: "AndorPhotonCounting", |
| 5390 |
4885: "AndorEmDacLevel", |
| 5391 |
4890: "AndorFrames", |
| 5392 |
4896: "AndorHorizontalFlip", |
| 5393 |
4897: "AndorVerticalFlip", |
| 5394 |
4898: "AndorClockwise", |
| 5395 |
4899: "AndorCounterClockwise", |
| 5396 |
4904: "AndorVerticalClockVoltage", |
| 5397 |
4905: "AndorVerticalShiftSpeed", |
| 5398 |
4907: "AndorPreAmpSetting", |
| 5399 |
4908: "AndorCameraSerial", |
| 5400 |
4911: "AndorActualTemperature", |
| 5401 |
4912: "AndorBaselineClamp", |
| 5402 |
4913: "AndorPrescans", |
| 5403 |
4914: "AndorModel", |
| 5404 |
4915: "AndorChipSizeX", |
| 5405 |
4916: "AndorChipSizeY", |
| 5406 |
4944: "AndorBaselineOffset", |
| 5407 |
4966: "AndorSoftwareVersion", |
| 5408 |
18246: "Rating", |
| 5409 |
18247: "XP_DIP_XML", |
| 5410 |
18248: "StitchInfo", |
| 5411 |
18249: "RatingPercent", |
| 5412 |
20481: "ResolutionXUnit", |
| 5413 |
20482: "ResolutionYUnit", |
| 5414 |
20483: "ResolutionXLengthUnit", |
| 5415 |
20484: "ResolutionYLengthUnit", |
| 5416 |
20485: "PrintFlags", |
| 5417 |
20486: "PrintFlagsVersion", |
| 5418 |
20487: "PrintFlagsCrop", |
| 5419 |
20488: "PrintFlagsBleedWidth", |
| 5420 |
20489: "PrintFlagsBleedWidthScale", |
| 5421 |
20490: "HalftoneLPI", |
| 5422 |
20491: "HalftoneLPIUnit", |
| 5423 |
20492: "HalftoneDegree", |
| 5424 |
20493: "HalftoneShape", |
| 5425 |
20494: "HalftoneMisc", |
| 5426 |
20495: "HalftoneScreen", |
| 5427 |
20496: "JPEGQuality", |
| 5428 |
20497: "GridSize", |
| 5429 |
20498: "ThumbnailFormat", |
| 5430 |
20499: "ThumbnailWidth", |
| 5431 |
20500: "ThumbnailHeight", |
| 5432 |
20501: "ThumbnailColorDepth", |
| 5433 |
20502: "ThumbnailPlanes", |
| 5434 |
20503: "ThumbnailRawBytes", |
| 5435 |
20504: "ThumbnailSize", |
| 5436 |
20505: "ThumbnailCompressedSize", |
| 5437 |
20506: "ColorTransferFunction", |
| 5438 |
20507: "ThumbnailData", |
| 5439 |
20512: "ThumbnailImageWidth", |
| 5440 |
20513: "ThumbnailImageHeight", |
| 5441 |
20514: "ThumbnailBitsPerSample", |
| 5442 |
20515: "ThumbnailCompression", |
| 5443 |
20516: "ThumbnailPhotometricInterp", |
| 5444 |
20517: "ThumbnailImageDescription", |
| 5445 |
20518: "ThumbnailEquipMake", |
| 5446 |
20519: "ThumbnailEquipModel", |
| 5447 |
20520: "ThumbnailStripOffsets", |
| 5448 |
20521: "ThumbnailOrientation", |
| 5449 |
20522: "ThumbnailSamplesPerPixel", |
| 5450 |
20523: "ThumbnailRowsPerStrip", |
| 5451 |
20524: "ThumbnailStripBytesCount", |
| 5452 |
20525: "ThumbnailResolutionX", |
| 5453 |
20526: "ThumbnailResolutionY", |
| 5454 |
20527: "ThumbnailPlanarConfig", |
| 5455 |
20528: "ThumbnailResolutionUnit", |
| 5456 |
20529: "ThumbnailTransferFunction", |
| 5457 |
20530: "ThumbnailSoftwareUsed", |
| 5458 |
20531: "ThumbnailDateTime", |
| 5459 |
20532: "ThumbnailArtist", |
| 5460 |
20533: "ThumbnailWhitePoint", |
| 5461 |
20534: "ThumbnailPrimaryChromaticities", |
| 5462 |
20535: "ThumbnailYCbCrCoefficients", |
| 5463 |
20536: "ThumbnailYCbCrSubsampling", |
| 5464 |
20537: "ThumbnailYCbCrPositioning", |
| 5465 |
20538: "ThumbnailRefBlackWhite", |
| 5466 |
20539: "ThumbnailCopyRight", |
| 5467 |
20545: "InteroperabilityIndex", |
| 5468 |
20546: "InteroperabilityVersion", |
| 5469 |
20624: "LuminanceTable", |
| 5470 |
20625: "ChrominanceTable", |
| 5471 |
20736: "FrameDelay", |
| 5472 |
20737: "LoopCount", |
| 5473 |
20738: "GlobalPalette", |
| 5474 |
20739: "IndexBackground", |
| 5475 |
20740: "IndexTransparent", |
| 5476 |
20752: "PixelUnit", |
| 5477 |
20753: "PixelPerUnitX", |
| 5478 |
20754: "PixelPerUnitY", |
| 5479 |
20755: "PaletteHistogram", |
| 5480 |
28672: "SonyRawFileType", |
| 5481 |
28722: "VignettingCorrParams", |
| 5482 |
28725: "ChromaticAberrationCorrParams", |
| 5483 |
28727: "DistortionCorrParams", |
| 5484 |
|
| 5485 |
32781: "ImageID", |
| 5486 |
32931: "WangTag1", |
| 5487 |
32932: "WangAnnotation", |
| 5488 |
32933: "WangTag3", |
| 5489 |
32934: "WangTag4", |
| 5490 |
32953: "ImageReferencePoints", |
| 5491 |
32954: "RegionXformTackPoint", |
| 5492 |
32955: "WarpQuadrilateral", |
| 5493 |
32956: "AffineTransformMat", |
| 5494 |
32995: "Matteing", |
| 5495 |
32996: "DataType", |
| 5496 |
32997: "ImageDepth", |
| 5497 |
32998: "TileDepth", |
| 5498 |
33300: "ImageFullWidth", |
| 5499 |
33301: "ImageFullLength", |
| 5500 |
33302: "TextureFormat", |
| 5501 |
33303: "TextureWrapModes", |
| 5502 |
33304: "FieldOfViewCotangent", |
| 5503 |
33305: "MatrixWorldToScreen", |
| 5504 |
33306: "MatrixWorldToCamera", |
| 5505 |
33405: "Model2", |
| 5506 |
33421: "CFARepeatPatternDim", |
| 5507 |
33422: "CFAPattern", |
| 5508 |
33423: "BatteryLevel", |
| 5509 |
33424: "KodakIFD", |
| 5510 |
33434: "ExposureTime", |
| 5511 |
33437: "FNumber", |
| 5512 |
33432: "Copyright", |
| 5513 |
33445: "MDFileTag", |
| 5514 |
33446: "MDScalePixel", |
| 5515 |
33447: "MDColorTable", |
| 5516 |
33448: "MDLabName", |
| 5517 |
33449: "MDSampleInfo", |
| 5518 |
33450: "MDPrepDate", |
| 5519 |
33451: "MDPrepTime", |
| 5520 |
33452: "MDFileUnits", |
| 5521 |
33550: "ModelPixelScaleTag", |
| 5522 |
33589: "AdventScale", |
| 5523 |
33590: "AdventRevision", |
| 5524 |
33628: "UIC1tag", |
| 5525 |
33629: "UIC2tag", |
| 5526 |
33630: "UIC3tag", |
| 5527 |
33631: "UIC4tag", |
| 5528 |
33723: "IPTCNAA", |
| 5529 |
33858: "ExtendedTagsOffset", |
| 5530 |
33918: "IntergraphPacketData", |
| 5531 |
33919: "IntergraphFlagRegisters", |
| 5532 |
33920: "IntergraphMatrixTag", |
| 5533 |
33921: "INGRReserved", |
| 5534 |
33922: "ModelTiepointTag", |
| 5535 |
33923: "LeicaMagic", |
| 5536 |
34016: "Site", |
| 5537 |
34017: "ColorSequence", |
| 5538 |
34018: "IT8Header", |
| 5539 |
34019: "RasterPadding", |
| 5540 |
34020: "BitsPerRunLength", |
| 5541 |
34021: "BitsPerExtendedRunLength", |
| 5542 |
34022: "ColorTable", |
| 5543 |
34023: "ImageColorIndicator", |
| 5544 |
34024: "BackgroundColorIndicator", |
| 5545 |
34025: "ImageColorValue", |
| 5546 |
34026: "BackgroundColorValue", |
| 5547 |
34027: "PixelIntensityRange", |
| 5548 |
34028: "TransparencyIndicator", |
| 5549 |
34029: "ColorCharacterization", |
| 5550 |
34030: "HCUsage", |
| 5551 |
34031: "TrapIndicator", |
| 5552 |
34032: "CMYKEquivalent", |
| 5553 |
34118: "CZ_SEM", |
| 5554 |
34152: "AFCP_IPTC", |
| 5555 |
34232: "PixelMagicJBIGOptions", |
| 5556 |
34263: "JPLCartoIFD", |
| 5557 |
34122: "IPLAB", |
| 5558 |
34264: "ModelTransformationTag", |
| 5559 |
34306: "WB_GRGBLevels", |
| 5560 |
34310: "LeafData", |
| 5561 |
34361: "MM_Header", |
| 5562 |
34362: "MM_Stamp", |
| 5563 |
34363: "MM_Unknown", |
| 5564 |
34377: "ImageResources", |
| 5565 |
34386: "MM_UserBlock", |
| 5566 |
34412: "CZ_LSMINFO", |
| 5567 |
34665: "ExifTag", |
| 5568 |
34675: "InterColorProfile", |
| 5569 |
34680: "FEI_SFEG", |
| 5570 |
34682: "FEI_HELIOS", |
| 5571 |
34683: "FEI_TITAN", |
| 5572 |
34687: "FXExtensions", |
| 5573 |
34688: "MultiProfiles", |
| 5574 |
34689: "SharedData", |
| 5575 |
34690: "T88Options", |
| 5576 |
34710: "MarCCD", |
| 5577 |
34732: "ImageLayer", |
| 5578 |
34735: "GeoKeyDirectoryTag", |
| 5579 |
34736: "GeoDoubleParamsTag", |
| 5580 |
34737: "GeoAsciiParamsTag", |
| 5581 |
34750: "JBIGOptions", |
| 5582 |
34821: "PIXTIFF", |
| 5583 |
34850: "ExposureProgram", |
| 5584 |
34852: "SpectralSensitivity", |
| 5585 |
34853: "GPSTag", |
| 5586 |
34855: "ISOSpeedRatings", |
| 5587 |
34856: "OECF", |
| 5588 |
34857: "Interlace", |
| 5589 |
34858: "TimeZoneOffset", |
| 5590 |
34859: "SelfTimerMode", |
| 5591 |
34864: "SensitivityType", |
| 5592 |
34865: "StandardOutputSensitivity", |
| 5593 |
34866: "RecommendedExposureIndex", |
| 5594 |
34867: "ISOSpeed", |
| 5595 |
34868: "ISOSpeedLatitudeyyy", |
| 5596 |
34869: "ISOSpeedLatitudezzz", |
| 5597 |
34908: "HylaFAXFaxRecvParams", |
| 5598 |
34909: "HylaFAXFaxSubAddress", |
| 5599 |
34910: "HylaFAXFaxRecvTime", |
| 5600 |
34911: "FaxDcs", |
| 5601 |
34929: "FedexEDR", |
| 5602 |
34954: "LeafSubIFD", |
| 5603 |
34959: "Aphelion1", |
| 5604 |
34960: "Aphelion2", |
| 5605 |
34961: "AphelionInternal", |
| 5606 |
36864: "ExifVersion", |
| 5607 |
36867: "DateTimeOriginal", |
| 5608 |
36868: "DateTimeDigitized", |
| 5609 |
36873: "GooglePlusUploadCode", |
| 5610 |
36880: "OffsetTime", |
| 5611 |
36881: "OffsetTimeOriginal", |
| 5612 |
36882: "OffsetTimeDigitized", |
| 5613 |
|
| 5614 |
|
| 5615 |
|
| 5616 |
|
| 5617 |
|
| 5618 |
|
| 5619 |
|
| 5620 |
|
| 5621 |
|
| 5622 |
|
| 5623 |
|
| 5624 |
|
| 5625 |
|
| 5626 |
|
| 5627 |
|
| 5628 |
|
| 5629 |
37121: "ComponentsConfiguration", |
| 5630 |
37122: "CompressedBitsPerPixel", |
| 5631 |
37377: "ShutterSpeedValue", |
| 5632 |
37378: "ApertureValue", |
| 5633 |
37379: "BrightnessValue", |
| 5634 |
37380: "ExposureBiasValue", |
| 5635 |
37381: "MaxApertureValue", |
| 5636 |
37382: "SubjectDistance", |
| 5637 |
37383: "MeteringMode", |
| 5638 |
37384: "LightSource", |
| 5639 |
37385: "Flash", |
| 5640 |
37386: "FocalLength", |
| 5641 |
37387: "FlashEnergy_", |
| 5642 |
37388: "SpatialFrequencyResponse_", |
| 5643 |
37389: "Noise", |
| 5644 |
37390: "FocalPlaneXResolution", |
| 5645 |
37391: "FocalPlaneYResolution", |
| 5646 |
37392: "FocalPlaneResolutionUnit", |
| 5647 |
37393: "ImageNumber", |
| 5648 |
37394: "SecurityClassification", |
| 5649 |
37395: "ImageHistory", |
| 5650 |
37396: "SubjectLocation", |
| 5651 |
37397: "ExposureIndex", |
| 5652 |
37398: "TIFFEPStandardID", |
| 5653 |
37399: "SensingMethod", |
| 5654 |
37434: "CIP3DataFile", |
| 5655 |
37435: "CIP3Sheet", |
| 5656 |
37436: "CIP3Side", |
| 5657 |
37439: "StoNits", |
| 5658 |
37500: "MakerNote", |
| 5659 |
37510: "UserComment", |
| 5660 |
37520: "SubsecTime", |
| 5661 |
37521: "SubsecTimeOriginal", |
| 5662 |
37522: "SubsecTimeDigitized", |
| 5663 |
37679: "MODIText", |
| 5664 |
37680: "MODIOLEPropertySetStorage", |
| 5665 |
37681: "MODIPositioning", |
| 5666 |
37706: "TVIPS", |
| 5667 |
37707: "TVIPS1", |
| 5668 |
37708: "TVIPS2", |
| 5669 |
37724: "ImageSourceData", |
| 5670 |
37888: "Temperature", |
| 5671 |
37889: "Humidity", |
| 5672 |
37890: "Pressure", |
| 5673 |
37891: "WaterDepth", |
| 5674 |
37892: "Acceleration", |
| 5675 |
37893: "CameraElevationAngle", |
| 5676 |
40001: "MC_IpWinScal", |
| 5677 |
40100: "MC_IdOld", |
| 5678 |
40965: "InteroperabilityTag", |
| 5679 |
40091: "XPTitle", |
| 5680 |
40092: "XPComment", |
| 5681 |
40093: "XPAuthor", |
| 5682 |
40094: "XPKeywords", |
| 5683 |
40095: "XPSubject", |
| 5684 |
40960: "FlashpixVersion", |
| 5685 |
40961: "ColorSpace", |
| 5686 |
40962: "PixelXDimension", |
| 5687 |
40963: "PixelYDimension", |
| 5688 |
40964: "RelatedSoundFile", |
| 5689 |
40976: "SamsungRawPointersOffset", |
| 5690 |
40977: "SamsungRawPointersLength", |
| 5691 |
41217: "SamsungRawByteOrder", |
| 5692 |
41218: "SamsungRawUnknown", |
| 5693 |
41483: "FlashEnergy", |
| 5694 |
41484: "SpatialFrequencyResponse", |
| 5695 |
41485: "Noise_", |
| 5696 |
41486: "FocalPlaneXResolution_", |
| 5697 |
41487: "FocalPlaneYResolution_", |
| 5698 |
41488: "FocalPlaneResolutionUnit_", |
| 5699 |
41489: "ImageNumber_", |
| 5700 |
41490: "SecurityClassification_", |
| 5701 |
41491: "ImageHistory_", |
| 5702 |
41492: "SubjectLocation_", |
| 5703 |
41493: "ExposureIndex_ ", |
| 5704 |
41494: "TIFF-EPStandardID", |
| 5705 |
41495: "SensingMethod_", |
| 5706 |
41728: "FileSource", |
| 5707 |
41729: "SceneType", |
| 5708 |
41730: "CFAPattern_", |
| 5709 |
41985: "CustomRendered", |
| 5710 |
41986: "ExposureMode", |
| 5711 |
41987: "WhiteBalance", |
| 5712 |
41988: "DigitalZoomRatio", |
| 5713 |
41989: "FocalLengthIn35mmFilm", |
| 5714 |
41990: "SceneCaptureType", |
| 5715 |
41991: "GainControl", |
| 5716 |
41992: "Contrast", |
| 5717 |
41993: "Saturation", |
| 5718 |
41994: "Sharpness", |
| 5719 |
41995: "DeviceSettingDescription", |
| 5720 |
41996: "SubjectDistanceRange", |
| 5721 |
42016: "ImageUniqueID", |
| 5722 |
42032: "CameraOwnerName", |
| 5723 |
42033: "BodySerialNumber", |
| 5724 |
42034: "LensSpecification", |
| 5725 |
42035: "LensMake", |
| 5726 |
42036: "LensModel", |
| 5727 |
42037: "LensSerialNumber", |
| 5728 |
42112: "GDAL_METADATA", |
| 5729 |
42113: "GDAL_NODATA", |
| 5730 |
42240: "Gamma", |
| 5731 |
43314: "NIHImageHeader", |
| 5732 |
44992: "ExpandSoftware", |
| 5733 |
44993: "ExpandLens", |
| 5734 |
44994: "ExpandFilm", |
| 5735 |
44995: "ExpandFilterLens", |
| 5736 |
44996: "ExpandScanner", |
| 5737 |
44997: "ExpandFlashLamp", |
| 5738 |
48129: "PixelFormat", |
| 5739 |
48130: "Transformation", |
| 5740 |
48131: "Uncompressed", |
| 5741 |
48132: "ImageType", |
| 5742 |
48256: "ImageWidth_", |
| 5743 |
48257: "ImageHeight_", |
| 5744 |
48258: "WidthResolution", |
| 5745 |
48259: "HeightResolution", |
| 5746 |
48320: "ImageOffset", |
| 5747 |
48321: "ImageByteCount", |
| 5748 |
48322: "AlphaOffset", |
| 5749 |
48323: "AlphaByteCount", |
| 5750 |
48324: "ImageDataDiscard", |
| 5751 |
48325: "AlphaDataDiscard", |
| 5752 |
50215: "OceScanjobDescription", |
| 5753 |
50216: "OceApplicationSelector", |
| 5754 |
50217: "OceIdentificationNumber", |
| 5755 |
50218: "OceImageLogicCharacteristics", |
| 5756 |
50255: "Annotations", |
| 5757 |
50288: "MC_Id", |
| 5758 |
50289: "MC_XYPosition", |
| 5759 |
50290: "MC_ZPosition", |
| 5760 |
50291: "MC_XYCalibration", |
| 5761 |
50292: "MC_LensCharacteristics", |
| 5762 |
50293: "MC_ChannelName", |
| 5763 |
50294: "MC_ExcitationWavelength", |
| 5764 |
50295: "MC_TimeStamp", |
| 5765 |
50296: "MC_FrameProperties", |
| 5766 |
50341: "PrintImageMatching", |
| 5767 |
50495: "PCO_RAW", |
| 5768 |
50547: "OriginalFileName", |
| 5769 |
50560: "USPTO_OriginalContentType", |
| 5770 |
50561: "USPTO_RotationCode", |
| 5771 |
50656: "CR2CFAPattern", |
| 5772 |
50706: "DNGVersion", |
| 5773 |
50707: "DNGBackwardVersion", |
| 5774 |
50708: "UniqueCameraModel", |
| 5775 |
50709: "LocalizedCameraModel", |
| 5776 |
50710: "CFAPlaneColor", |
| 5777 |
50711: "CFALayout", |
| 5778 |
50712: "LinearizationTable", |
| 5779 |
50713: "BlackLevelRepeatDim", |
| 5780 |
50714: "BlackLevel", |
| 5781 |
50715: "BlackLevelDeltaH", |
| 5782 |
50716: "BlackLevelDeltaV", |
| 5783 |
50717: "WhiteLevel", |
| 5784 |
50718: "DefaultScale", |
| 5785 |
50719: "DefaultCropOrigin", |
| 5786 |
50720: "DefaultCropSize", |
| 5787 |
50721: "ColorMatrix1", |
| 5788 |
50722: "ColorMatrix2", |
| 5789 |
50723: "CameraCalibration1", |
| 5790 |
50724: "CameraCalibration2", |
| 5791 |
50725: "ReductionMatrix1", |
| 5792 |
50726: "ReductionMatrix2", |
| 5793 |
50727: "AnalogBalance", |
| 5794 |
50728: "AsShotNeutral", |
| 5795 |
50729: "AsShotWhiteXY", |
| 5796 |
50730: "BaselineExposure", |
| 5797 |
50731: "BaselineNoise", |
| 5798 |
50732: "BaselineSharpness", |
| 5799 |
50733: "BayerGreenSplit", |
| 5800 |
50734: "LinearResponseLimit", |
| 5801 |
50735: "CameraSerialNumber", |
| 5802 |
50736: "LensInfo", |
| 5803 |
50737: "ChromaBlurRadius", |
| 5804 |
50738: "AntiAliasStrength", |
| 5805 |
50739: "ShadowScale", |
| 5806 |
50740: "DNGPrivateData", |
| 5807 |
50741: "MakerNoteSafety", |
| 5808 |
50752: "RawImageSegmentation", |
| 5809 |
50778: "CalibrationIlluminant1", |
| 5810 |
50779: "CalibrationIlluminant2", |
| 5811 |
50780: "BestQualityScale", |
| 5812 |
50781: "RawDataUniqueID", |
| 5813 |
50784: "AliasLayerMetadata", |
| 5814 |
50827: "OriginalRawFileName", |
| 5815 |
50828: "OriginalRawFileData", |
| 5816 |
50829: "ActiveArea", |
| 5817 |
50830: "MaskedAreas", |
| 5818 |
50831: "AsShotICCProfile", |
| 5819 |
50832: "AsShotPreProfileMatrix", |
| 5820 |
50833: "CurrentICCProfile", |
| 5821 |
50834: "CurrentPreProfileMatrix", |
| 5822 |
50838: "IJMetadataByteCounts", |
| 5823 |
50839: "IJMetadata", |
| 5824 |
50844: "RPCCoefficientTag", |
| 5825 |
50879: "ColorimetricReference", |
| 5826 |
50885: "SRawType", |
| 5827 |
50898: "PanasonicTitle", |
| 5828 |
50899: "PanasonicTitle2", |
| 5829 |
50931: "CameraCalibrationSignature", |
| 5830 |
50932: "ProfileCalibrationSignature", |
| 5831 |
50933: "ProfileIFD", |
| 5832 |
50934: "AsShotProfileName", |
| 5833 |
50935: "NoiseReductionApplied", |
| 5834 |
50936: "ProfileName", |
| 5835 |
50937: "ProfileHueSatMapDims", |
| 5836 |
50938: "ProfileHueSatMapData1", |
| 5837 |
50939: "ProfileHueSatMapData2", |
| 5838 |
50940: "ProfileToneCurve", |
| 5839 |
50941: "ProfileEmbedPolicy", |
| 5840 |
50942: "ProfileCopyright", |
| 5841 |
50964: "ForwardMatrix1", |
| 5842 |
50965: "ForwardMatrix2", |
| 5843 |
50966: "PreviewApplicationName", |
| 5844 |
50967: "PreviewApplicationVersion", |
| 5845 |
50968: "PreviewSettingsName", |
| 5846 |
50969: "PreviewSettingsDigest", |
| 5847 |
50970: "PreviewColorSpace", |
| 5848 |
50971: "PreviewDateTime", |
| 5849 |
50972: "RawImageDigest", |
| 5850 |
50973: "OriginalRawFileDigest", |
| 5851 |
50974: "SubTileBlockSize", |
| 5852 |
50975: "RowInterleaveFactor", |
| 5853 |
50981: "ProfileLookTableDims", |
| 5854 |
50982: "ProfileLookTableData", |
| 5855 |
51008: "OpcodeList1", |
| 5856 |
51009: "OpcodeList2", |
| 5857 |
51022: "OpcodeList3", |
| 5858 |
51023: "FibicsXML", |
| 5859 |
51041: "NoiseProfile", |
| 5860 |
51043: "TimeCodes", |
| 5861 |
51044: "FrameRate", |
| 5862 |
51058: "TStop", |
| 5863 |
51081: "ReelName", |
| 5864 |
51089: "OriginalDefaultFinalSize", |
| 5865 |
51090: "OriginalBestQualitySize", |
| 5866 |
51091: "OriginalDefaultCropSize", |
| 5867 |
51105: "CameraLabel", |
| 5868 |
51107: "ProfileHueSatMapEncoding", |
| 5869 |
51108: "ProfileLookTableEncoding", |
| 5870 |
51109: "BaselineExposureOffset", |
| 5871 |
51110: "DefaultBlackRender", |
| 5872 |
51111: "NewRawImageDigest", |
| 5873 |
51112: "RawToPreviewGain", |
| 5874 |
51125: "DefaultUserCrop", |
| 5875 |
51123: "MicroManagerMetadata", |
| 5876 |
59932: "Padding", |
| 5877 |
59933: "OffsetSchema", |
| 5878 |
|
| 5879 |
|
| 5880 |
|
| 5881 |
|
| 5882 |
|
| 5883 |
|
| 5884 |
|
| 5885 |
|
| 5886 |
|
| 5887 |
|
| 5888 |
|
| 5889 |
|
| 5890 |
|
| 5891 |
|
| 5892 |
|
| 5893 |
|
| 5894 |
|
| 5895 |
|
| 5896 |
65200: "FlexXML", |
| 5897 |
65563: "PerSample", |
| 5898 |
} |
| 5899 |
|
| 5900 |
def TAG_NAMES(): |
| 5901 |
return {v: c for c, v in TIFF.TAGS.items()} |
| 5902 |
|
| 5903 |
def TAG_READERS(): |
| 5904 |
|
| 5905 |
return { |
| 5906 |
320: read_colormap, |
| 5907 |
|
| 5908 |
|
| 5909 |
33723: read_bytes, |
| 5910 |
|
| 5911 |
33628: read_uic1tag, |
| 5912 |
33629: read_uic2tag, |
| 5913 |
33630: read_uic3tag, |
| 5914 |
33631: read_uic4tag, |
| 5915 |
34118: read_cz_sem, |
| 5916 |
34361: read_mm_header, |
| 5917 |
34362: read_mm_stamp, |
| 5918 |
34363: read_numpy, |
| 5919 |
34386: read_numpy, |
| 5920 |
34412: read_cz_lsminfo, |
| 5921 |
34680: read_fei_metadata, |
| 5922 |
34682: read_fei_metadata, |
| 5923 |
37706: read_tvips_header, |
| 5924 |
37724: read_bytes, |
| 5925 |
33923: read_bytes, |
| 5926 |
43314: read_nih_image_header, |
| 5927 |
|
| 5928 |
40100: read_bytes, |
| 5929 |
50288: read_bytes, |
| 5930 |
50296: read_bytes, |
| 5931 |
50839: read_bytes, |
| 5932 |
51123: read_json, |
| 5933 |
34665: read_exif_ifd, |
| 5934 |
34853: read_gps_ifd, |
| 5935 |
40965: read_interoperability_ifd, |
| 5936 |
} |
| 5937 |
|
| 5938 |
def TAG_TUPLE(): |
| 5939 |
|
| 5940 |
return frozenset((273, 279, 324, 325, 530, 531, 34736)) |
| 5941 |
|
| 5942 |
def TAG_ATTRIBUTES(): |
| 5943 |
|
| 5944 |
return { |
| 5945 |
"ImageWidth": "imagewidth", |
| 5946 |
"ImageLength": "imagelength", |
| 5947 |
"BitsPerSample": "bitspersample", |
| 5948 |
"Compression": "compression", |
| 5949 |
"PlanarConfiguration": "planarconfig", |
| 5950 |
"FillOrder": "fillorder", |
| 5951 |
"PhotometricInterpretation": "photometric", |
| 5952 |
"ColorMap": "colormap", |
| 5953 |
"ImageDescription": "description", |
| 5954 |
"ImageDescription1": "description1", |
| 5955 |
"SamplesPerPixel": "samplesperpixel", |
| 5956 |
"RowsPerStrip": "rowsperstrip", |
| 5957 |
"Software": "software", |
| 5958 |
"Predictor": "predictor", |
| 5959 |
"TileWidth": "tilewidth", |
| 5960 |
"TileLength": "tilelength", |
| 5961 |
"ExtraSamples": "extrasamples", |
| 5962 |
"SampleFormat": "sampleformat", |
| 5963 |
"ImageDepth": "imagedepth", |
| 5964 |
"TileDepth": "tiledepth", |
| 5965 |
} |
| 5966 |
|
| 5967 |
def TAG_ENUM(): |
| 5968 |
return { |
| 5969 |
|
| 5970 |
255: TIFF.OFILETYPE, |
| 5971 |
259: TIFF.COMPRESSION, |
| 5972 |
262: TIFF.PHOTOMETRIC, |
| 5973 |
263: TIFF.THRESHHOLD, |
| 5974 |
266: TIFF.FILLORDER, |
| 5975 |
274: TIFF.ORIENTATION, |
| 5976 |
284: TIFF.PLANARCONFIG, |
| 5977 |
290: TIFF.GRAYRESPONSEUNIT, |
| 5978 |
|
| 5979 |
|
| 5980 |
296: TIFF.RESUNIT, |
| 5981 |
300: TIFF.COLORRESPONSEUNIT, |
| 5982 |
317: TIFF.PREDICTOR, |
| 5983 |
338: TIFF.EXTRASAMPLE, |
| 5984 |
339: TIFF.SAMPLEFORMAT, |
| 5985 |
|
| 5986 |
|
| 5987 |
} |
| 5988 |
|
| 5989 |
def FILETYPE(): |
| 5990 |
class FILETYPE(enum.IntFlag): |
| 5991 |
|
| 5992 |
UNDEFINED = 0 |
| 5993 |
REDUCEDIMAGE = 1 |
| 5994 |
PAGE = 2 |
| 5995 |
MASK = 4 |
| 5996 |
|
| 5997 |
return FILETYPE |
| 5998 |
|
| 5999 |
def OFILETYPE(): |
| 6000 |
class OFILETYPE(enum.IntEnum): |
| 6001 |
UNDEFINED = 0 |
| 6002 |
IMAGE = 1 |
| 6003 |
REDUCEDIMAGE = 2 |
| 6004 |
PAGE = 3 |
| 6005 |
|
| 6006 |
return OFILETYPE |
| 6007 |
|
| 6008 |
def COMPRESSION(): |
| 6009 |
class COMPRESSION(enum.IntEnum): |
| 6010 |
NONE = 1 |
| 6011 |
CCITTRLE = 2 |
| 6012 |
CCITT_T4 = 3 |
| 6013 |
CCITT_T6 = 4 |
| 6014 |
LZW = 5 |
| 6015 |
OJPEG = 6 |
| 6016 |
JPEG = 7 |
| 6017 |
ADOBE_DEFLATE = 8 |
| 6018 |
JBIG_BW = 9 |
| 6019 |
JBIG_COLOR = 10 |
| 6020 |
JPEG_99 = 99 |
| 6021 |
KODAK_262 = 262 |
| 6022 |
NEXT = 32766 |
| 6023 |
SONY_ARW = 32767 |
| 6024 |
PACKED_RAW = 32769 |
| 6025 |
SAMSUNG_SRW = 32770 |
| 6026 |
CCIRLEW = 32771 |
| 6027 |
SAMSUNG_SRW2 = 32772 |
| 6028 |
PACKBITS = 32773 |
| 6029 |
THUNDERSCAN = 32809 |
| 6030 |
IT8CTPAD = 32895 |
| 6031 |
IT8LW = 32896 |
| 6032 |
IT8MP = 32897 |
| 6033 |
IT8BL = 32898 |
| 6034 |
PIXARFILM = 32908 |
| 6035 |
PIXARLOG = 32909 |
| 6036 |
DEFLATE = 32946 |
| 6037 |
DCS = 32947 |
| 6038 |
APERIO_JP2000_YCBC = 33003 |
| 6039 |
APERIO_JP2000_RGB = 33005 |
| 6040 |
JBIG = 34661 |
| 6041 |
SGILOG = 34676 |
| 6042 |
SGILOG24 = 34677 |
| 6043 |
JPEG2000 = 34712 |
| 6044 |
NIKON_NEF = 34713 |
| 6045 |
JBIG2 = 34715 |
| 6046 |
MDI_BINARY = 34718 |
| 6047 |
MDI_PROGRESSIVE = 34719 |
| 6048 |
MDI_VECTOR = 34720 |
| 6049 |
JPEG_LOSSY = 34892 |
| 6050 |
LZMA = 34925 |
| 6051 |
ZSTD = 34926 |
| 6052 |
OPS_PNG = 34933 |
| 6053 |
OPS_JPEGXR = 34934 |
| 6054 |
PIXTIFF = 50013 |
| 6055 |
KODAK_DCR = 65000 |
| 6056 |
PENTAX_PEF = 65535 |
| 6057 |
|
| 6058 |
|
| 6059 |
return COMPRESSION |
| 6060 |
|
| 6061 |
def PHOTOMETRIC(): |
| 6062 |
class PHOTOMETRIC(enum.IntEnum): |
| 6063 |
MINISWHITE = 0 |
| 6064 |
MINISBLACK = 1 |
| 6065 |
RGB = 2 |
| 6066 |
PALETTE = 3 |
| 6067 |
MASK = 4 |
| 6068 |
SEPARATED = 5 |
| 6069 |
YCBCR = 6 |
| 6070 |
CIELAB = 8 |
| 6071 |
ICCLAB = 9 |
| 6072 |
ITULAB = 10 |
| 6073 |
CFA = 32803 |
| 6074 |
LOGL = 32844 |
| 6075 |
LOGLUV = 32845 |
| 6076 |
LINEAR_RAW = 34892 |
| 6077 |
|
| 6078 |
return PHOTOMETRIC |
| 6079 |
|
| 6080 |
def THRESHHOLD(): |
| 6081 |
class THRESHHOLD(enum.IntEnum): |
| 6082 |
BILEVEL = 1 |
| 6083 |
HALFTONE = 2 |
| 6084 |
ERRORDIFFUSE = 3 |
| 6085 |
|
| 6086 |
return THRESHHOLD |
| 6087 |
|
| 6088 |
def FILLORDER(): |
| 6089 |
class FILLORDER(enum.IntEnum): |
| 6090 |
MSB2LSB = 1 |
| 6091 |
LSB2MSB = 2 |
| 6092 |
|
| 6093 |
return FILLORDER |
| 6094 |
|
| 6095 |
def ORIENTATION(): |
| 6096 |
class ORIENTATION(enum.IntEnum): |
| 6097 |
TOPLEFT = 1 |
| 6098 |
TOPRIGHT = 2 |
| 6099 |
BOTRIGHT = 3 |
| 6100 |
BOTLEFT = 4 |
| 6101 |
LEFTTOP = 5 |
| 6102 |
RIGHTTOP = 6 |
| 6103 |
RIGHTBOT = 7 |
| 6104 |
LEFTBOT = 8 |
| 6105 |
|
| 6106 |
return ORIENTATION |
| 6107 |
|
| 6108 |
def PLANARCONFIG(): |
| 6109 |
class PLANARCONFIG(enum.IntEnum): |
| 6110 |
CONTIG = 1 |
| 6111 |
SEPARATE = 2 |
| 6112 |
|
| 6113 |
return PLANARCONFIG |
| 6114 |
|
| 6115 |
def GRAYRESPONSEUNIT(): |
| 6116 |
class GRAYRESPONSEUNIT(enum.IntEnum): |
| 6117 |
_10S = 1 |
| 6118 |
_100S = 2 |
| 6119 |
_1000S = 3 |
| 6120 |
_10000S = 4 |
| 6121 |
_100000S = 5 |
| 6122 |
|
| 6123 |
return GRAYRESPONSEUNIT |
| 6124 |
|
| 6125 |
def GROUP4OPT(): |
| 6126 |
class GROUP4OPT(enum.IntEnum): |
| 6127 |
UNCOMPRESSED = 2 |
| 6128 |
|
| 6129 |
return GROUP4OPT |
| 6130 |
|
| 6131 |
def RESUNIT(): |
| 6132 |
class RESUNIT(enum.IntEnum): |
| 6133 |
NONE = 1 |
| 6134 |
INCH = 2 |
| 6135 |
CENTIMETER = 3 |
| 6136 |
|
| 6137 |
|
| 6138 |
return RESUNIT |
| 6139 |
|
| 6140 |
def COLORRESPONSEUNIT(): |
| 6141 |
class COLORRESPONSEUNIT(enum.IntEnum): |
| 6142 |
_10S = 1 |
| 6143 |
_100S = 2 |
| 6144 |
_1000S = 3 |
| 6145 |
_10000S = 4 |
| 6146 |
_100000S = 5 |
| 6147 |
|
| 6148 |
return COLORRESPONSEUNIT |
| 6149 |
|
| 6150 |
def PREDICTOR(): |
| 6151 |
class PREDICTOR(enum.IntEnum): |
| 6152 |
NONE = 1 |
| 6153 |
HORIZONTAL = 2 |
| 6154 |
FLOATINGPOINT = 3 |
| 6155 |
|
| 6156 |
|
| 6157 |
return PREDICTOR |
| 6158 |
|
| 6159 |
def EXTRASAMPLE(): |
| 6160 |
class EXTRASAMPLE(enum.IntEnum): |
| 6161 |
UNSPECIFIED = 0 |
| 6162 |
ASSOCALPHA = 1 |
| 6163 |
UNASSALPHA = 2 |
| 6164 |
|
| 6165 |
return EXTRASAMPLE |
| 6166 |
|
| 6167 |
def SAMPLEFORMAT(): |
| 6168 |
class SAMPLEFORMAT(enum.IntEnum): |
| 6169 |
UINT = 1 |
| 6170 |
INT = 2 |
| 6171 |
IEEEFP = 3 |
| 6172 |
VOID = 4 |
| 6173 |
COMPLEXINT = 5 |
| 6174 |
COMPLEXIEEEFP = 6 |
| 6175 |
|
| 6176 |
return SAMPLEFORMAT |
| 6177 |
|
| 6178 |
def DATATYPES(): |
| 6179 |
class DATATYPES(enum.IntEnum): |
| 6180 |
NOTYPE = 0 |
| 6181 |
BYTE = 1 |
| 6182 |
ASCII = 2 |
| 6183 |
SHORT = 3 |
| 6184 |
LONG = 4 |
| 6185 |
RATIONAL = 5 |
| 6186 |
SBYTE = 6 |
| 6187 |
UNDEFINED = 7 |
| 6188 |
SSHORT = 8 |
| 6189 |
SLONG = 9 |
| 6190 |
SRATIONAL = 10 |
| 6191 |
FLOAT = 11 |
| 6192 |
DOUBLE = 12 |
| 6193 |
IFD = 13 |
| 6194 |
UNICODE = 14 |
| 6195 |
COMPLEX = 15 |
| 6196 |
LONG8 = 16 |
| 6197 |
SLONG8 = 17 |
| 6198 |
IFD8 = 18 |
| 6199 |
|
| 6200 |
return DATATYPES |
| 6201 |
|
| 6202 |
def DATA_FORMATS(): |
| 6203 |
|
| 6204 |
return { |
| 6205 |
1: "1B", |
| 6206 |
2: "1s", |
| 6207 |
|
| 6208 |
3: "1H", |
| 6209 |
4: "1I", |
| 6210 |
5: "2I", |
| 6211 |
|
| 6212 |
6: "1b", |
| 6213 |
7: "1B", |
| 6214 |
|
| 6215 |
8: "1h", |
| 6216 |
|
| 6217 |
9: "1i", |
| 6218 |
|
| 6219 |
10: "2i", |
| 6220 |
|
| 6221 |
11: "1f", |
| 6222 |
12: "1d", |
| 6223 |
13: "1I", |
| 6224 |
|
| 6225 |
|
| 6226 |
16: "1Q", |
| 6227 |
17: "1q", |
| 6228 |
18: "1Q", |
| 6229 |
} |
| 6230 |
|
| 6231 |
def DATA_DTYPES(): |
| 6232 |
|
| 6233 |
return { |
| 6234 |
"B": 1, |
| 6235 |
"s": 2, |
| 6236 |
"H": 3, |
| 6237 |
"I": 4, |
| 6238 |
"2I": 5, |
| 6239 |
"b": 6, |
| 6240 |
"h": 8, |
| 6241 |
"i": 9, |
| 6242 |
"2i": 10, |
| 6243 |
"f": 11, |
| 6244 |
"d": 12, |
| 6245 |
"Q": 16, |
| 6246 |
"q": 17, |
| 6247 |
} |
| 6248 |
|
| 6249 |
def SAMPLE_DTYPES(): |
| 6250 |
|
| 6251 |
return { |
| 6252 |
(1, 1): "?", |
| 6253 |
(1, 2): "B", |
| 6254 |
(1, 3): "B", |
| 6255 |
(1, 4): "B", |
| 6256 |
(1, 5): "B", |
| 6257 |
(1, 6): "B", |
| 6258 |
(1, 7): "B", |
| 6259 |
(1, 8): "B", |
| 6260 |
(1, 9): "H", |
| 6261 |
(1, 10): "H", |
| 6262 |
(1, 11): "H", |
| 6263 |
(1, 12): "H", |
| 6264 |
(1, 13): "H", |
| 6265 |
(1, 14): "H", |
| 6266 |
(1, 15): "H", |
| 6267 |
(1, 16): "H", |
| 6268 |
(1, 17): "I", |
| 6269 |
(1, 18): "I", |
| 6270 |
(1, 19): "I", |
| 6271 |
(1, 20): "I", |
| 6272 |
(1, 21): "I", |
| 6273 |
(1, 22): "I", |
| 6274 |
(1, 23): "I", |
| 6275 |
(1, 24): "I", |
| 6276 |
(1, 25): "I", |
| 6277 |
(1, 26): "I", |
| 6278 |
(1, 27): "I", |
| 6279 |
(1, 28): "I", |
| 6280 |
(1, 29): "I", |
| 6281 |
(1, 30): "I", |
| 6282 |
(1, 31): "I", |
| 6283 |
(1, 32): "I", |
| 6284 |
(1, 64): "Q", |
| 6285 |
(2, 8): "b", |
| 6286 |
(2, 16): "h", |
| 6287 |
(2, 32): "i", |
| 6288 |
(2, 64): "q", |
| 6289 |
(3, 16): "e", |
| 6290 |
(3, 32): "f", |
| 6291 |
(3, 64): "d", |
| 6292 |
(6, 64): "F", |
| 6293 |
(6, 128): "D", |
| 6294 |
(1, (5, 6, 5)): "B", |
| 6295 |
} |
| 6296 |
|
| 6297 |
def COMPESSORS(): |
| 6298 |
|
| 6299 |
|
| 6300 |
class Compressors(object): |
| 6301 |
"""Delay import compressor functions.""" |
| 6302 |
|
| 6303 |
def __init__(self): |
| 6304 |
self._compressors = {8: (zlib.compress, 6), 32946: (zlib.compress, 6)} |
| 6305 |
|
| 6306 |
def __getitem__(self, key): |
| 6307 |
if key in self._compressors: |
| 6308 |
return self._compressors[key] |
| 6309 |
|
| 6310 |
if key == 34925: |
| 6311 |
try: |
| 6312 |
import lzma |
| 6313 |
except ImportError: |
| 6314 |
try: |
| 6315 |
import backports.lzma as lzma |
| 6316 |
except ImportError: |
| 6317 |
raise KeyError |
| 6318 |
|
| 6319 |
def lzma_compress(x, level): |
| 6320 |
return lzma.compress(x) |
| 6321 |
|
| 6322 |
self._compressors[key] = lzma_compress, 0 |
| 6323 |
return lzma_compress, 0 |
| 6324 |
|
| 6325 |
if key == 34926: |
| 6326 |
try: |
| 6327 |
import zstd |
| 6328 |
except ImportError: |
| 6329 |
raise KeyError |
| 6330 |
self._compressors[key] = zstd.compress, 9 |
| 6331 |
return zstd.compress, 9 |
| 6332 |
|
| 6333 |
raise KeyError |
| 6334 |
|
| 6335 |
def __contains__(self, key): |
| 6336 |
try: |
| 6337 |
self[key] |
| 6338 |
return True |
| 6339 |
except KeyError: |
| 6340 |
return False |
| 6341 |
|
| 6342 |
return Compressors() |
| 6343 |
|
| 6344 |
def DECOMPESSORS(): |
| 6345 |
|
| 6346 |
|
| 6347 |
class Decompressors(object): |
| 6348 |
"""Delay import decompressor functions.""" |
| 6349 |
|
| 6350 |
def __init__(self): |
| 6351 |
self._decompressors = { |
| 6352 |
None: identityfunc, |
| 6353 |
1: identityfunc, |
| 6354 |
5: decode_lzw, |
| 6355 |
8: zlib.decompress, |
| 6356 |
32773: decode_packbits, |
| 6357 |
32946: zlib.decompress, |
| 6358 |
} |
| 6359 |
|
| 6360 |
def __getitem__(self, key): |
| 6361 |
if key in self._decompressors: |
| 6362 |
return self._decompressors[key] |
| 6363 |
|
| 6364 |
if key == 7: |
| 6365 |
try: |
| 6366 |
from imagecodecs import jpeg, jpeg_12 |
| 6367 |
except ImportError: |
| 6368 |
raise KeyError |
| 6369 |
|
| 6370 |
def decode_jpeg(x, table, bps, colorspace=None): |
| 6371 |
if bps == 8: |
| 6372 |
return jpeg.decode_jpeg(x, table, colorspace) |
| 6373 |
elif bps == 12: |
| 6374 |
return jpeg_12.decode_jpeg_12(x, table, colorspace) |
| 6375 |
else: |
| 6376 |
raise ValueError("bitspersample not supported") |
| 6377 |
|
| 6378 |
self._decompressors[key] = decode_jpeg |
| 6379 |
return decode_jpeg |
| 6380 |
|
| 6381 |
if key == 34925: |
| 6382 |
try: |
| 6383 |
import lzma |
| 6384 |
except ImportError: |
| 6385 |
try: |
| 6386 |
import backports.lzma as lzma |
| 6387 |
except ImportError: |
| 6388 |
raise KeyError |
| 6389 |
self._decompressors[key] = lzma.decompress |
| 6390 |
return lzma.decompress |
| 6391 |
|
| 6392 |
if key == 34926: |
| 6393 |
try: |
| 6394 |
import zstd |
| 6395 |
except ImportError: |
| 6396 |
raise KeyError |
| 6397 |
self._decompressors[key] = zstd.decompress |
| 6398 |
return zstd.decompress |
| 6399 |
raise KeyError |
| 6400 |
|
| 6401 |
def __contains__(self, item): |
| 6402 |
try: |
| 6403 |
self[item] |
| 6404 |
return True |
| 6405 |
except KeyError: |
| 6406 |
return False |
| 6407 |
|
| 6408 |
return Decompressors() |
| 6409 |
|
| 6410 |
def FRAME_ATTRS(): |
| 6411 |
|
| 6412 |
return set("shape ndim size dtype axes is_final".split()) |
| 6413 |
|
| 6414 |
def FILE_FLAGS(): |
| 6415 |
|
| 6416 |
exclude = set( |
| 6417 |
"reduced final memmappable contiguous tiled " "chroma_subsampled".split() |
| 6418 |
) |
| 6419 |
return set( |
| 6420 |
a[3:] for a in dir(TiffPage) if a[:3] == "is_" and a[3:] not in exclude |
| 6421 |
) |
| 6422 |
|
| 6423 |
def FILE_EXTENSIONS(): |
| 6424 |
|
| 6425 |
return tuple( |
| 6426 |
"tif tiff ome.tif lsm stk qptiff pcoraw " |
| 6427 |
"gel seq svs bif tf8 tf2 btf".split() |
| 6428 |
) |
| 6429 |
|
| 6430 |
def FILEOPEN_FILTER(): |
| 6431 |
|
| 6432 |
return [ |
| 6433 |
("%s files" % ext.upper(), "*.%s" % ext) for ext in TIFF.FILE_EXTENSIONS |
| 6434 |
] + [("allfiles", "*")] |
| 6435 |
|
| 6436 |
def AXES_LABELS(): |
| 6437 |
|
| 6438 |
axes = { |
| 6439 |
"X": "width", |
| 6440 |
"Y": "height", |
| 6441 |
"Z": "depth", |
| 6442 |
"S": "sample", |
| 6443 |
"I": "series", |
| 6444 |
"T": "time", |
| 6445 |
"C": "channel", |
| 6446 |
"A": "angle", |
| 6447 |
"P": "phase", |
| 6448 |
"R": "tile", |
| 6449 |
"H": "lifetime", |
| 6450 |
"E": "lambda", |
| 6451 |
"L": "exposure", |
| 6452 |
"V": "event", |
| 6453 |
"Q": "other", |
| 6454 |
"M": "mosaic", |
| 6455 |
} |
| 6456 |
axes.update(dict((v, k) for k, v in axes.items())) |
| 6457 |
return axes |
| 6458 |
|
| 6459 |
def ANDOR_TAGS(): |
| 6460 |
|
| 6461 |
return set(range(4864, 5030)) |
| 6462 |
|
| 6463 |
def EXIF_TAGS(): |
| 6464 |
tags = { |
| 6465 |
|
| 6466 |
65000: "OwnerName", |
| 6467 |
65001: "SerialNumber", |
| 6468 |
65002: "Lens", |
| 6469 |
65100: "RawFile", |
| 6470 |
65101: "Converter", |
| 6471 |
65102: "WhiteBalance", |
| 6472 |
65105: "Exposure", |
| 6473 |
65106: "Shadows", |
| 6474 |
65107: "Brightness", |
| 6475 |
65108: "Contrast", |
| 6476 |
65109: "Saturation", |
| 6477 |
65110: "Sharpness", |
| 6478 |
65111: "Smoothness", |
| 6479 |
65112: "MoireFilter", |
| 6480 |
} |
| 6481 |
tags.update(TIFF.TAGS) |
| 6482 |
return tags |
| 6483 |
|
| 6484 |
def GPS_TAGS(): |
| 6485 |
return { |
| 6486 |
0: "GPSVersionID", |
| 6487 |
1: "GPSLatitudeRef", |
| 6488 |
2: "GPSLatitude", |
| 6489 |
3: "GPSLongitudeRef", |
| 6490 |
4: "GPSLongitude", |
| 6491 |
5: "GPSAltitudeRef", |
| 6492 |
6: "GPSAltitude", |
| 6493 |
7: "GPSTimeStamp", |
| 6494 |
8: "GPSSatellites", |
| 6495 |
9: "GPSStatus", |
| 6496 |
10: "GPSMeasureMode", |
| 6497 |
11: "GPSDOP", |
| 6498 |
12: "GPSSpeedRef", |
| 6499 |
13: "GPSSpeed", |
| 6500 |
14: "GPSTrackRef", |
| 6501 |
15: "GPSTrack", |
| 6502 |
16: "GPSImgDirectionRef", |
| 6503 |
17: "GPSImgDirection", |
| 6504 |
18: "GPSMapDatum", |
| 6505 |
19: "GPSDestLatitudeRef", |
| 6506 |
20: "GPSDestLatitude", |
| 6507 |
21: "GPSDestLongitudeRef", |
| 6508 |
22: "GPSDestLongitude", |
| 6509 |
23: "GPSDestBearingRef", |
| 6510 |
24: "GPSDestBearing", |
| 6511 |
25: "GPSDestDistanceRef", |
| 6512 |
26: "GPSDestDistance", |
| 6513 |
27: "GPSProcessingMethod", |
| 6514 |
28: "GPSAreaInformation", |
| 6515 |
29: "GPSDateStamp", |
| 6516 |
30: "GPSDifferential", |
| 6517 |
31: "GPSHPositioningError", |
| 6518 |
} |
| 6519 |
|
| 6520 |
def IOP_TAGS(): |
| 6521 |
return { |
| 6522 |
1: "InteroperabilityIndex", |
| 6523 |
2: "InteroperabilityVersion", |
| 6524 |
4096: "RelatedImageFileFormat", |
| 6525 |
4097: "RelatedImageWidth", |
| 6526 |
4098: "RelatedImageLength", |
| 6527 |
} |
| 6528 |
|
| 6529 |
def GEO_KEYS(): |
| 6530 |
return { |
| 6531 |
1024: "GTModelTypeGeoKey", |
| 6532 |
1025: "GTRasterTypeGeoKey", |
| 6533 |
1026: "GTCitationGeoKey", |
| 6534 |
2048: "GeographicTypeGeoKey", |
| 6535 |
2049: "GeogCitationGeoKey", |
| 6536 |
2050: "GeogGeodeticDatumGeoKey", |
| 6537 |
2051: "GeogPrimeMeridianGeoKey", |
| 6538 |
2052: "GeogLinearUnitsGeoKey", |
| 6539 |
2053: "GeogLinearUnitSizeGeoKey", |
| 6540 |
2054: "GeogAngularUnitsGeoKey", |
| 6541 |
2055: "GeogAngularUnitsSizeGeoKey", |
| 6542 |
2056: "GeogEllipsoidGeoKey", |
| 6543 |
2057: "GeogSemiMajorAxisGeoKey", |
| 6544 |
2058: "GeogSemiMinorAxisGeoKey", |
| 6545 |
2059: "GeogInvFlatteningGeoKey", |
| 6546 |
2060: "GeogAzimuthUnitsGeoKey", |
| 6547 |
2061: "GeogPrimeMeridianLongGeoKey", |
| 6548 |
2062: "GeogTOWGS84GeoKey", |
| 6549 |
3059: "ProjLinearUnitsInterpCorrectGeoKey", |
| 6550 |
3072: "ProjectedCSTypeGeoKey", |
| 6551 |
3073: "PCSCitationGeoKey", |
| 6552 |
3074: "ProjectionGeoKey", |
| 6553 |
3075: "ProjCoordTransGeoKey", |
| 6554 |
3076: "ProjLinearUnitsGeoKey", |
| 6555 |
3077: "ProjLinearUnitSizeGeoKey", |
| 6556 |
3078: "ProjStdParallel1GeoKey", |
| 6557 |
3079: "ProjStdParallel2GeoKey", |
| 6558 |
3080: "ProjNatOriginLongGeoKey", |
| 6559 |
3081: "ProjNatOriginLatGeoKey", |
| 6560 |
3082: "ProjFalseEastingGeoKey", |
| 6561 |
3083: "ProjFalseNorthingGeoKey", |
| 6562 |
3084: "ProjFalseOriginLongGeoKey", |
| 6563 |
3085: "ProjFalseOriginLatGeoKey", |
| 6564 |
3086: "ProjFalseOriginEastingGeoKey", |
| 6565 |
3087: "ProjFalseOriginNorthingGeoKey", |
| 6566 |
3088: "ProjCenterLongGeoKey", |
| 6567 |
3089: "ProjCenterLatGeoKey", |
| 6568 |
3090: "ProjCenterEastingGeoKey", |
| 6569 |
3091: "ProjFalseOriginNorthingGeoKey", |
| 6570 |
3092: "ProjScaleAtNatOriginGeoKey", |
| 6571 |
3093: "ProjScaleAtCenterGeoKey", |
| 6572 |
3094: "ProjAzimuthAngleGeoKey", |
| 6573 |
3095: "ProjStraightVertPoleLongGeoKey", |
| 6574 |
3096: "ProjRectifiedGridAngleGeoKey", |
| 6575 |
4096: "VerticalCSTypeGeoKey", |
| 6576 |
4097: "VerticalCitationGeoKey", |
| 6577 |
4098: "VerticalDatumGeoKey", |
| 6578 |
4099: "VerticalUnitsGeoKey", |
| 6579 |
} |
| 6580 |
|
| 6581 |
def GEO_CODES(): |
| 6582 |
try: |
| 6583 |
from .tifffile_geodb import GEO_CODES |
| 6584 |
except (ImportError, ValueError): |
| 6585 |
try: |
| 6586 |
from tifffile_geodb import GEO_CODES |
| 6587 |
except (ImportError, ValueError): |
| 6588 |
GEO_CODES = {} |
| 6589 |
return GEO_CODES |
| 6590 |
|
| 6591 |
def CZ_LSMINFO(): |
| 6592 |
return [ |
| 6593 |
("MagicNumber", "u4"), |
| 6594 |
("StructureSize", "i4"), |
| 6595 |
("DimensionX", "i4"), |
| 6596 |
("DimensionY", "i4"), |
| 6597 |
("DimensionZ", "i4"), |
| 6598 |
("DimensionChannels", "i4"), |
| 6599 |
("DimensionTime", "i4"), |
| 6600 |
("DataType", "i4"), |
| 6601 |
("ThumbnailX", "i4"), |
| 6602 |
("ThumbnailY", "i4"), |
| 6603 |
("VoxelSizeX", "f8"), |
| 6604 |
("VoxelSizeY", "f8"), |
| 6605 |
("VoxelSizeZ", "f8"), |
| 6606 |
("OriginX", "f8"), |
| 6607 |
("OriginY", "f8"), |
| 6608 |
("OriginZ", "f8"), |
| 6609 |
("ScanType", "u2"), |
| 6610 |
("SpectralScan", "u2"), |
| 6611 |
("TypeOfData", "u4"), |
| 6612 |
("OffsetVectorOverlay", "u4"), |
| 6613 |
("OffsetInputLut", "u4"), |
| 6614 |
("OffsetOutputLut", "u4"), |
| 6615 |
("OffsetChannelColors", "u4"), |
| 6616 |
("TimeIntervall", "f8"), |
| 6617 |
("OffsetChannelDataTypes", "u4"), |
| 6618 |
("OffsetScanInformation", "u4"), |
| 6619 |
("OffsetKsData", "u4"), |
| 6620 |
("OffsetTimeStamps", "u4"), |
| 6621 |
("OffsetEventList", "u4"), |
| 6622 |
("OffsetRoi", "u4"), |
| 6623 |
("OffsetBleachRoi", "u4"), |
| 6624 |
("OffsetNextRecording", "u4"), |
| 6625 |
|
| 6626 |
("DisplayAspectX", "f8"), |
| 6627 |
("DisplayAspectY", "f8"), |
| 6628 |
("DisplayAspectZ", "f8"), |
| 6629 |
("DisplayAspectTime", "f8"), |
| 6630 |
("OffsetMeanOfRoisOverlay", "u4"), |
| 6631 |
("OffsetTopoIsolineOverlay", "u4"), |
| 6632 |
("OffsetTopoProfileOverlay", "u4"), |
| 6633 |
("OffsetLinescanOverlay", "u4"), |
| 6634 |
("ToolbarFlags", "u4"), |
| 6635 |
("OffsetChannelWavelength", "u4"), |
| 6636 |
("OffsetChannelFactors", "u4"), |
| 6637 |
("ObjectiveSphereCorrection", "f8"), |
| 6638 |
("OffsetUnmixParameters", "u4"), |
| 6639 |
|
| 6640 |
("OffsetAcquisitionParameters", "u4"), |
| 6641 |
("OffsetCharacteristics", "u4"), |
| 6642 |
("OffsetPalette", "u4"), |
| 6643 |
("TimeDifferenceX", "f8"), |
| 6644 |
("TimeDifferenceY", "f8"), |
| 6645 |
("TimeDifferenceZ", "f8"), |
| 6646 |
("InternalUse1", "u4"), |
| 6647 |
("DimensionP", "i4"), |
| 6648 |
("DimensionM", "i4"), |
| 6649 |
("DimensionsReserved", "16i4"), |
| 6650 |
("OffsetTilePositions", "u4"), |
| 6651 |
("", "9u4"), |
| 6652 |
("OffsetPositions", "u4"), |
| 6653 |
|
| 6654 |
] |
| 6655 |
|
| 6656 |
def CZ_LSMINFO_READERS(): |
| 6657 |
|
| 6658 |
|
| 6659 |
return { |
| 6660 |
"ScanInformation": read_lsm_scaninfo, |
| 6661 |
"TimeStamps": read_lsm_timestamps, |
| 6662 |
"EventList": read_lsm_eventlist, |
| 6663 |
"ChannelColors": read_lsm_channelcolors, |
| 6664 |
"Positions": read_lsm_floatpairs, |
| 6665 |
"TilePositions": read_lsm_floatpairs, |
| 6666 |
"VectorOverlay": None, |
| 6667 |
"InputLut": None, |
| 6668 |
"OutputLut": None, |
| 6669 |
"TimeIntervall": None, |
| 6670 |
"ChannelDataTypes": None, |
| 6671 |
"KsData": None, |
| 6672 |
"Roi": None, |
| 6673 |
"BleachRoi": None, |
| 6674 |
"NextRecording": None, |
| 6675 |
"MeanOfRoisOverlay": None, |
| 6676 |
"TopoIsolineOverlay": None, |
| 6677 |
"TopoProfileOverlay": None, |
| 6678 |
"ChannelWavelength": None, |
| 6679 |
"SphereCorrection": None, |
| 6680 |
"ChannelFactors": None, |
| 6681 |
"UnmixParameters": None, |
| 6682 |
"AcquisitionParameters": None, |
| 6683 |
"Characteristics": None, |
| 6684 |
} |
| 6685 |
|
| 6686 |
def CZ_LSMINFO_SCANTYPE(): |
| 6687 |
|
| 6688 |
return { |
| 6689 |
0: "XYZCT", |
| 6690 |
1: "XYZCT", |
| 6691 |
2: "XYZCT", |
| 6692 |
3: "XYTCZ", |
| 6693 |
4: "XYZTC", |
| 6694 |
5: "XYTCZ", |
| 6695 |
6: "XYZTC", |
| 6696 |
7: "XYCTZ", |
| 6697 |
8: "XYCZT", |
| 6698 |
9: "XYTCZ", |
| 6699 |
10: "XYZCT", |
| 6700 |
} |
| 6701 |
|
| 6702 |
def CZ_LSMINFO_DIMENSIONS(): |
| 6703 |
|
| 6704 |
return { |
| 6705 |
"X": "DimensionX", |
| 6706 |
"Y": "DimensionY", |
| 6707 |
"Z": "DimensionZ", |
| 6708 |
"C": "DimensionChannels", |
| 6709 |
"T": "DimensionTime", |
| 6710 |
"P": "DimensionP", |
| 6711 |
"M": "DimensionM", |
| 6712 |
} |
| 6713 |
|
| 6714 |
def CZ_LSMINFO_DATATYPES(): |
| 6715 |
|
| 6716 |
return { |
| 6717 |
0: "varying data types", |
| 6718 |
1: "8 bit unsigned integer", |
| 6719 |
2: "12 bit unsigned integer", |
| 6720 |
5: "32 bit float", |
| 6721 |
} |
| 6722 |
|
| 6723 |
def CZ_LSMINFO_TYPEOFDATA(): |
| 6724 |
|
| 6725 |
return { |
| 6726 |
0: "Original scan data", |
| 6727 |
1: "Calculated data", |
| 6728 |
2: "3D reconstruction", |
| 6729 |
3: "Topography height map", |
| 6730 |
} |
| 6731 |
|
| 6732 |
def CZ_LSMINFO_SCANINFO_ARRAYS(): |
| 6733 |
return { |
| 6734 |
0x20000000: "Tracks", |
| 6735 |
0x30000000: "Lasers", |
| 6736 |
0x60000000: "DetectionChannels", |
| 6737 |
0x80000000: "IlluminationChannels", |
| 6738 |
0xA0000000: "BeamSplitters", |
| 6739 |
0xC0000000: "DataChannels", |
| 6740 |
0x11000000: "Timers", |
| 6741 |
0x13000000: "Markers", |
| 6742 |
} |
| 6743 |
|
| 6744 |
def CZ_LSMINFO_SCANINFO_STRUCTS(): |
| 6745 |
return { |
| 6746 |
|
| 6747 |
0x40000000: "Track", |
| 6748 |
0x50000000: "Laser", |
| 6749 |
0x70000000: "DetectionChannel", |
| 6750 |
0x90000000: "IlluminationChannel", |
| 6751 |
0xB0000000: "BeamSplitter", |
| 6752 |
0xD0000000: "DataChannel", |
| 6753 |
0x12000000: "Timer", |
| 6754 |
0x14000000: "Marker", |
| 6755 |
} |
| 6756 |
|
| 6757 |
def CZ_LSMINFO_SCANINFO_ATTRIBUTES(): |
| 6758 |
return { |
| 6759 |
|
| 6760 |
0x10000001: "Name", |
| 6761 |
0x10000002: "Description", |
| 6762 |
0x10000003: "Notes", |
| 6763 |
0x10000004: "Objective", |
| 6764 |
0x10000005: "ProcessingSummary", |
| 6765 |
0x10000006: "SpecialScanMode", |
| 6766 |
0x10000007: "ScanType", |
| 6767 |
0x10000008: "ScanMode", |
| 6768 |
0x10000009: "NumberOfStacks", |
| 6769 |
0x1000000A: "LinesPerPlane", |
| 6770 |
0x1000000B: "SamplesPerLine", |
| 6771 |
0x1000000C: "PlanesPerVolume", |
| 6772 |
0x1000000D: "ImagesWidth", |
| 6773 |
0x1000000E: "ImagesHeight", |
| 6774 |
0x1000000F: "ImagesNumberPlanes", |
| 6775 |
0x10000010: "ImagesNumberStacks", |
| 6776 |
0x10000011: "ImagesNumberChannels", |
| 6777 |
0x10000012: "LinscanXySize", |
| 6778 |
0x10000013: "ScanDirection", |
| 6779 |
0x10000014: "TimeSeries", |
| 6780 |
0x10000015: "OriginalScanData", |
| 6781 |
0x10000016: "ZoomX", |
| 6782 |
0x10000017: "ZoomY", |
| 6783 |
0x10000018: "ZoomZ", |
| 6784 |
0x10000019: "Sample0X", |
| 6785 |
0x1000001A: "Sample0Y", |
| 6786 |
0x1000001B: "Sample0Z", |
| 6787 |
0x1000001C: "SampleSpacing", |
| 6788 |
0x1000001D: "LineSpacing", |
| 6789 |
0x1000001E: "PlaneSpacing", |
| 6790 |
0x1000001F: "PlaneWidth", |
| 6791 |
0x10000020: "PlaneHeight", |
| 6792 |
0x10000021: "VolumeDepth", |
| 6793 |
0x10000023: "Nutation", |
| 6794 |
0x10000034: "Rotation", |
| 6795 |
0x10000035: "Precession", |
| 6796 |
0x10000036: "Sample0time", |
| 6797 |
0x10000037: "StartScanTriggerIn", |
| 6798 |
0x10000038: "StartScanTriggerOut", |
| 6799 |
0x10000039: "StartScanEvent", |
| 6800 |
0x10000040: "StartScanTime", |
| 6801 |
0x10000041: "StopScanTriggerIn", |
| 6802 |
0x10000042: "StopScanTriggerOut", |
| 6803 |
0x10000043: "StopScanEvent", |
| 6804 |
0x10000044: "StopScanTime", |
| 6805 |
0x10000045: "UseRois", |
| 6806 |
0x10000046: "UseReducedMemoryRois", |
| 6807 |
0x10000047: "User", |
| 6808 |
0x10000048: "UseBcCorrection", |
| 6809 |
0x10000049: "PositionBcCorrection1", |
| 6810 |
0x10000050: "PositionBcCorrection2", |
| 6811 |
0x10000051: "InterpolationY", |
| 6812 |
0x10000052: "CameraBinning", |
| 6813 |
0x10000053: "CameraSupersampling", |
| 6814 |
0x10000054: "CameraFrameWidth", |
| 6815 |
0x10000055: "CameraFrameHeight", |
| 6816 |
0x10000056: "CameraOffsetX", |
| 6817 |
0x10000057: "CameraOffsetY", |
| 6818 |
0x10000059: "RtBinning", |
| 6819 |
0x1000005A: "RtFrameWidth", |
| 6820 |
0x1000005B: "RtFrameHeight", |
| 6821 |
0x1000005C: "RtRegionWidth", |
| 6822 |
0x1000005D: "RtRegionHeight", |
| 6823 |
0x1000005E: "RtOffsetX", |
| 6824 |
0x1000005F: "RtOffsetY", |
| 6825 |
0x10000060: "RtZoom", |
| 6826 |
0x10000061: "RtLinePeriod", |
| 6827 |
0x10000062: "Prescan", |
| 6828 |
0x10000063: "ScanDirectionZ", |
| 6829 |
|
| 6830 |
0x40000001: "MultiplexType", |
| 6831 |
0x40000002: "MultiplexOrder", |
| 6832 |
0x40000003: "SamplingMode", |
| 6833 |
0x40000004: "SamplingMethod", |
| 6834 |
0x40000005: "SamplingNumber", |
| 6835 |
0x40000006: "Acquire", |
| 6836 |
0x40000007: "SampleObservationTime", |
| 6837 |
0x4000000B: "TimeBetweenStacks", |
| 6838 |
0x4000000C: "Name", |
| 6839 |
0x4000000D: "Collimator1Name", |
| 6840 |
0x4000000E: "Collimator1Position", |
| 6841 |
0x4000000F: "Collimator2Name", |
| 6842 |
0x40000010: "Collimator2Position", |
| 6843 |
0x40000011: "IsBleachTrack", |
| 6844 |
0x40000012: "IsBleachAfterScanNumber", |
| 6845 |
0x40000013: "BleachScanNumber", |
| 6846 |
0x40000014: "TriggerIn", |
| 6847 |
0x40000015: "TriggerOut", |
| 6848 |
0x40000016: "IsRatioTrack", |
| 6849 |
0x40000017: "BleachCount", |
| 6850 |
0x40000018: "SpiCenterWavelength", |
| 6851 |
0x40000019: "PixelTime", |
| 6852 |
0x40000021: "CondensorFrontlens", |
| 6853 |
0x40000023: "FieldStopValue", |
| 6854 |
0x40000024: "IdCondensorAperture", |
| 6855 |
0x40000025: "CondensorAperture", |
| 6856 |
0x40000026: "IdCondensorRevolver", |
| 6857 |
0x40000027: "CondensorFilter", |
| 6858 |
0x40000028: "IdTransmissionFilter1", |
| 6859 |
0x40000029: "IdTransmission1", |
| 6860 |
0x40000030: "IdTransmissionFilter2", |
| 6861 |
0x40000031: "IdTransmission2", |
| 6862 |
0x40000032: "RepeatBleach", |
| 6863 |
0x40000033: "EnableSpotBleachPos", |
| 6864 |
0x40000034: "SpotBleachPosx", |
| 6865 |
0x40000035: "SpotBleachPosy", |
| 6866 |
0x40000036: "SpotBleachPosz", |
| 6867 |
0x40000037: "IdTubelens", |
| 6868 |
0x40000038: "IdTubelensPosition", |
| 6869 |
0x40000039: "TransmittedLight", |
| 6870 |
0x4000003A: "ReflectedLight", |
| 6871 |
0x4000003B: "SimultanGrabAndBleach", |
| 6872 |
0x4000003C: "BleachPixelTime", |
| 6873 |
|
| 6874 |
0x50000001: "Name", |
| 6875 |
0x50000002: "Acquire", |
| 6876 |
0x50000003: "Power", |
| 6877 |
|
| 6878 |
0x70000001: "IntegrationMode", |
| 6879 |
0x70000002: "SpecialMode", |
| 6880 |
0x70000003: "DetectorGainFirst", |
| 6881 |
0x70000004: "DetectorGainLast", |
| 6882 |
0x70000005: "AmplifierGainFirst", |
| 6883 |
0x70000006: "AmplifierGainLast", |
| 6884 |
0x70000007: "AmplifierOffsFirst", |
| 6885 |
0x70000008: "AmplifierOffsLast", |
| 6886 |
0x70000009: "PinholeDiameter", |
| 6887 |
0x7000000A: "CountingTrigger", |
| 6888 |
0x7000000B: "Acquire", |
| 6889 |
0x7000000C: "PointDetectorName", |
| 6890 |
0x7000000D: "AmplifierName", |
| 6891 |
0x7000000E: "PinholeName", |
| 6892 |
0x7000000F: "FilterSetName", |
| 6893 |
0x70000010: "FilterName", |
| 6894 |
0x70000013: "IntegratorName", |
| 6895 |
0x70000014: "ChannelName", |
| 6896 |
0x70000015: "DetectorGainBc1", |
| 6897 |
0x70000016: "DetectorGainBc2", |
| 6898 |
0x70000017: "AmplifierGainBc1", |
| 6899 |
0x70000018: "AmplifierGainBc2", |
| 6900 |
0x70000019: "AmplifierOffsetBc1", |
| 6901 |
0x70000020: "AmplifierOffsetBc2", |
| 6902 |
0x70000021: "SpectralScanChannels", |
| 6903 |
0x70000022: "SpiWavelengthStart", |
| 6904 |
0x70000023: "SpiWavelengthStop", |
| 6905 |
0x70000026: "DyeName", |
| 6906 |
0x70000027: "DyeFolder", |
| 6907 |
|
| 6908 |
0x90000001: "Name", |
| 6909 |
0x90000002: "Power", |
| 6910 |
0x90000003: "Wavelength", |
| 6911 |
0x90000004: "Aquire", |
| 6912 |
0x90000005: "DetchannelName", |
| 6913 |
0x90000006: "PowerBc1", |
| 6914 |
0x90000007: "PowerBc2", |
| 6915 |
|
| 6916 |
0xB0000001: "FilterSet", |
| 6917 |
0xB0000002: "Filter", |
| 6918 |
0xB0000003: "Name", |
| 6919 |
|
| 6920 |
0xD0000001: "Name", |
| 6921 |
0xD0000003: "Acquire", |
| 6922 |
0xD0000004: "Color", |
| 6923 |
0xD0000005: "SampleType", |
| 6924 |
0xD0000006: "BitsPerSample", |
| 6925 |
0xD0000007: "RatioType", |
| 6926 |
0xD0000008: "RatioTrack1", |
| 6927 |
0xD0000009: "RatioTrack2", |
| 6928 |
0xD000000A: "RatioChannel1", |
| 6929 |
0xD000000B: "RatioChannel2", |
| 6930 |
0xD000000C: "RatioConst1", |
| 6931 |
0xD000000D: "RatioConst2", |
| 6932 |
0xD000000E: "RatioConst3", |
| 6933 |
0xD000000F: "RatioConst4", |
| 6934 |
0xD0000010: "RatioConst5", |
| 6935 |
0xD0000011: "RatioConst6", |
| 6936 |
0xD0000012: "RatioFirstImages1", |
| 6937 |
0xD0000013: "RatioFirstImages2", |
| 6938 |
0xD0000014: "DyeName", |
| 6939 |
0xD0000015: "DyeFolder", |
| 6940 |
0xD0000016: "Spectrum", |
| 6941 |
0xD0000017: "Acquire", |
| 6942 |
|
| 6943 |
0x12000001: "Name", |
| 6944 |
0x12000002: "Description", |
| 6945 |
0x12000003: "Interval", |
| 6946 |
0x12000004: "TriggerIn", |
| 6947 |
0x12000005: "TriggerOut", |
| 6948 |
0x12000006: "ActivationTime", |
| 6949 |
0x12000007: "ActivationNumber", |
| 6950 |
|
| 6951 |
0x14000001: "Name", |
| 6952 |
0x14000002: "Description", |
| 6953 |
0x14000003: "TriggerIn", |
| 6954 |
0x14000004: "TriggerOut", |
| 6955 |
} |
| 6956 |
|
| 6957 |
def NIH_IMAGE_HEADER(): |
| 6958 |
return [ |
| 6959 |
("FileID", "a8"), |
| 6960 |
("nLines", "i2"), |
| 6961 |
("PixelsPerLine", "i2"), |
| 6962 |
("Version", "i2"), |
| 6963 |
("OldLutMode", "i2"), |
| 6964 |
("OldnColors", "i2"), |
| 6965 |
("Colors", "u1", (3, 32)), |
| 6966 |
("OldColorStart", "i2"), |
| 6967 |
("ColorWidth", "i2"), |
| 6968 |
("ExtraColors", "u2", (6, 3)), |
| 6969 |
("nExtraColors", "i2"), |
| 6970 |
("ForegroundIndex", "i2"), |
| 6971 |
("BackgroundIndex", "i2"), |
| 6972 |
("XScale", "f8"), |
| 6973 |
("Unused2", "i2"), |
| 6974 |
("Unused3", "i2"), |
| 6975 |
("UnitsID", "i2"), |
| 6976 |
("p1", [("x", "i2"), ("y", "i2")]), |
| 6977 |
("p2", [("x", "i2"), ("y", "i2")]), |
| 6978 |
("CurveFitType", "i2"), |
| 6979 |
("nCoefficients", "i2"), |
| 6980 |
("Coeff", "f8", 6), |
| 6981 |
("UMsize", "u1"), |
| 6982 |
("UM", "a15"), |
| 6983 |
("UnusedBoolean", "u1"), |
| 6984 |
("BinaryPic", "b1"), |
| 6985 |
("SliceStart", "i2"), |
| 6986 |
("SliceEnd", "i2"), |
| 6987 |
("ScaleMagnification", "f4"), |
| 6988 |
("nSlices", "i2"), |
| 6989 |
("SliceSpacing", "f4"), |
| 6990 |
("CurrentSlice", "i2"), |
| 6991 |
("FrameInterval", "f4"), |
| 6992 |
("PixelAspectRatio", "f4"), |
| 6993 |
("ColorStart", "i2"), |
| 6994 |
("ColorEnd", "i2"), |
| 6995 |
("nColors", "i2"), |
| 6996 |
("Fill1", "3u2"), |
| 6997 |
("Fill2", "3u2"), |
| 6998 |
("Table", "u1"), |
| 6999 |
("LutMode", "u1"), |
| 7000 |
("InvertedTable", "b1"), |
| 7001 |
("ZeroClip", "b1"), |
| 7002 |
("XUnitSize", "u1"), |
| 7003 |
("XUnit", "a11"), |
| 7004 |
("StackType", "i2"), |
| 7005 |
|
| 7006 |
] |
| 7007 |
|
| 7008 |
def NIH_COLORTABLE_TYPE(): |
| 7009 |
return ( |
| 7010 |
"CustomTable", |
| 7011 |
"AppleDefault", |
| 7012 |
"Pseudo20", |
| 7013 |
"Pseudo32", |
| 7014 |
"Rainbow", |
| 7015 |
"Fire1", |
| 7016 |
"Fire2", |
| 7017 |
"Ice", |
| 7018 |
"Grays", |
| 7019 |
"Spectrum", |
| 7020 |
) |
| 7021 |
|
| 7022 |
def NIH_LUTMODE_TYPE(): |
| 7023 |
return ( |
| 7024 |
"PseudoColor", |
| 7025 |
"OldAppleDefault", |
| 7026 |
"OldSpectrum", |
| 7027 |
"GrayScale", |
| 7028 |
"ColorLut", |
| 7029 |
"CustomGrayscale", |
| 7030 |
) |
| 7031 |
|
| 7032 |
def NIH_CURVEFIT_TYPE(): |
| 7033 |
return ( |
| 7034 |
"StraightLine", |
| 7035 |
"Poly2", |
| 7036 |
"Poly3", |
| 7037 |
"Poly4", |
| 7038 |
"Poly5", |
| 7039 |
"ExpoFit", |
| 7040 |
"PowerFit", |
| 7041 |
"LogFit", |
| 7042 |
"RodbardFit", |
| 7043 |
"SpareFit1", |
| 7044 |
"Uncalibrated", |
| 7045 |
"UncalibratedOD", |
| 7046 |
) |
| 7047 |
|
| 7048 |
def NIH_UNITS_TYPE(): |
| 7049 |
return ( |
| 7050 |
"Nanometers", |
| 7051 |
"Micrometers", |
| 7052 |
"Millimeters", |
| 7053 |
"Centimeters", |
| 7054 |
"Meters", |
| 7055 |
"Kilometers", |
| 7056 |
"Inches", |
| 7057 |
"Feet", |
| 7058 |
"Miles", |
| 7059 |
"Pixels", |
| 7060 |
"OtherUnits", |
| 7061 |
) |
| 7062 |
|
| 7063 |
def NIH_STACKTYPE_TYPE(): |
| 7064 |
return ("VolumeStack", "RGBStack", "MovieStack", "HSVStack") |
| 7065 |
|
| 7066 |
def TVIPS_HEADER_V1(): |
| 7067 |
|
| 7068 |
return [ |
| 7069 |
("Version", "i4"), |
| 7070 |
("CommentV1", "a80"), |
| 7071 |
("HighTension", "i4"), |
| 7072 |
("SphericalAberration", "i4"), |
| 7073 |
("IlluminationAperture", "i4"), |
| 7074 |
("Magnification", "i4"), |
| 7075 |
("PostMagnification", "i4"), |
| 7076 |
("FocalLength", "i4"), |
| 7077 |
("Defocus", "i4"), |
| 7078 |
("Astigmatism", "i4"), |
| 7079 |
("AstigmatismDirection", "i4"), |
| 7080 |
("BiprismVoltage", "i4"), |
| 7081 |
("SpecimenTiltAngle", "i4"), |
| 7082 |
("SpecimenTiltDirection", "i4"), |
| 7083 |
("IlluminationTiltDirection", "i4"), |
| 7084 |
("IlluminationTiltAngle", "i4"), |
| 7085 |
("ImageMode", "i4"), |
| 7086 |
("EnergySpread", "i4"), |
| 7087 |
("ChromaticAberration", "i4"), |
| 7088 |
("ShutterType", "i4"), |
| 7089 |
("DefocusSpread", "i4"), |
| 7090 |
("CcdNumber", "i4"), |
| 7091 |
("CcdSize", "i4"), |
| 7092 |
("OffsetXV1", "i4"), |
| 7093 |
("OffsetYV1", "i4"), |
| 7094 |
("PhysicalPixelSize", "i4"), |
| 7095 |
("Binning", "i4"), |
| 7096 |
("ReadoutSpeed", "i4"), |
| 7097 |
("GainV1", "i4"), |
| 7098 |
("SensitivityV1", "i4"), |
| 7099 |
("ExposureTimeV1", "i4"), |
| 7100 |
("FlatCorrected", "i4"), |
| 7101 |
("DeadPxCorrected", "i4"), |
| 7102 |
("ImageMean", "i4"), |
| 7103 |
("ImageStd", "i4"), |
| 7104 |
("DisplacementX", "i4"), |
| 7105 |
("DisplacementY", "i4"), |
| 7106 |
("DateV1", "i4"), |
| 7107 |
("TimeV1", "i4"), |
| 7108 |
("ImageMin", "i4"), |
| 7109 |
("ImageMax", "i4"), |
| 7110 |
("ImageStatisticsQuality", "i4"), |
| 7111 |
] |
| 7112 |
|
| 7113 |
def TVIPS_HEADER_V2(): |
| 7114 |
return [ |
| 7115 |
("ImageName", "V160"), |
| 7116 |
("ImageFolder", "V160"), |
| 7117 |
("ImageSizeX", "i4"), |
| 7118 |
("ImageSizeY", "i4"), |
| 7119 |
("ImageSizeZ", "i4"), |
| 7120 |
("ImageSizeE", "i4"), |
| 7121 |
("ImageDataType", "i4"), |
| 7122 |
("Date", "i4"), |
| 7123 |
("Time", "i4"), |
| 7124 |
("Comment", "V1024"), |
| 7125 |
("ImageHistory", "V1024"), |
| 7126 |
("Scaling", "16f4"), |
| 7127 |
("ImageStatistics", "16c16"), |
| 7128 |
("ImageType", "i4"), |
| 7129 |
("ImageDisplaType", "i4"), |
| 7130 |
("PixelSizeX", "f4"), |
| 7131 |
("PixelSizeY", "f4"), |
| 7132 |
("ImageDistanceZ", "f4"), |
| 7133 |
("ImageDistanceE", "f4"), |
| 7134 |
("ImageMisc", "32f4"), |
| 7135 |
("TemType", "V160"), |
| 7136 |
("TemHighTension", "f4"), |
| 7137 |
("TemAberrations", "32f4"), |
| 7138 |
("TemEnergy", "32f4"), |
| 7139 |
("TemMode", "i4"), |
| 7140 |
("TemMagnification", "f4"), |
| 7141 |
("TemMagnificationCorrection", "f4"), |
| 7142 |
("PostMagnification", "f4"), |
| 7143 |
("TemStageType", "i4"), |
| 7144 |
("TemStagePosition", "5f4"), |
| 7145 |
("TemImageShift", "2f4"), |
| 7146 |
("TemBeamShift", "2f4"), |
| 7147 |
("TemBeamTilt", "2f4"), |
| 7148 |
("TilingParameters", "7f4"), |
| 7149 |
|
| 7150 |
("TemIllumination", "3f4"), |
| 7151 |
("TemShutter", "i4"), |
| 7152 |
("TemMisc", "32f4"), |
| 7153 |
("CameraType", "V160"), |
| 7154 |
("PhysicalPixelSizeX", "f4"), |
| 7155 |
("PhysicalPixelSizeY", "f4"), |
| 7156 |
("OffsetX", "i4"), |
| 7157 |
("OffsetY", "i4"), |
| 7158 |
("BinningX", "i4"), |
| 7159 |
("BinningY", "i4"), |
| 7160 |
("ExposureTime", "f4"), |
| 7161 |
("Gain", "f4"), |
| 7162 |
("ReadoutRate", "f4"), |
| 7163 |
("FlatfieldDescription", "V160"), |
| 7164 |
("Sensitivity", "f4"), |
| 7165 |
("Dose", "f4"), |
| 7166 |
("CamMisc", "32f4"), |
| 7167 |
("FeiMicroscopeInformation", "V1024"), |
| 7168 |
("FeiSpecimenInformation", "V1024"), |
| 7169 |
("Magic", "u4"), |
| 7170 |
] |
| 7171 |
|
| 7172 |
def MM_HEADER(): |
| 7173 |
|
| 7174 |
MM_DIMENSION = [ |
| 7175 |
("Name", "a16"), |
| 7176 |
("Size", "i4"), |
| 7177 |
("Origin", "f8"), |
| 7178 |
("Resolution", "f8"), |
| 7179 |
("Unit", "a64"), |
| 7180 |
] |
| 7181 |
return [ |
| 7182 |
("HeaderFlag", "i2"), |
| 7183 |
("ImageType", "u1"), |
| 7184 |
("ImageName", "a257"), |
| 7185 |
("OffsetData", "u4"), |
| 7186 |
("PaletteSize", "i4"), |
| 7187 |
("OffsetPalette0", "u4"), |
| 7188 |
("OffsetPalette1", "u4"), |
| 7189 |
("CommentSize", "i4"), |
| 7190 |
("OffsetComment", "u4"), |
| 7191 |
("Dimensions", MM_DIMENSION, 10), |
| 7192 |
("OffsetPosition", "u4"), |
| 7193 |
("MapType", "i2"), |
| 7194 |
("MapMin", "f8"), |
| 7195 |
("MapMax", "f8"), |
| 7196 |
("MinValue", "f8"), |
| 7197 |
("MaxValue", "f8"), |
| 7198 |
("OffsetMap", "u4"), |
| 7199 |
("Gamma", "f8"), |
| 7200 |
("Offset", "f8"), |
| 7201 |
("GrayChannel", MM_DIMENSION), |
| 7202 |
("OffsetThumbnail", "u4"), |
| 7203 |
("VoiceField", "i4"), |
| 7204 |
("OffsetVoiceField", "u4"), |
| 7205 |
] |
| 7206 |
|
| 7207 |
def MM_DIMENSIONS(): |
| 7208 |
|
| 7209 |
return { |
| 7210 |
"X": "X", |
| 7211 |
"Y": "Y", |
| 7212 |
"Z": "Z", |
| 7213 |
"T": "T", |
| 7214 |
"CH": "C", |
| 7215 |
"WAVELENGTH": "C", |
| 7216 |
"TIME": "T", |
| 7217 |
"XY": "R", |
| 7218 |
"EVENT": "V", |
| 7219 |
"EXPOSURE": "L", |
| 7220 |
} |
| 7221 |
|
| 7222 |
def UIC_TAGS(): |
| 7223 |
|
| 7224 |
|
| 7225 |
from fractions import Fraction |
| 7226 |
|
| 7227 |
return [ |
| 7228 |
("AutoScale", int), |
| 7229 |
("MinScale", int), |
| 7230 |
("MaxScale", int), |
| 7231 |
("SpatialCalibration", int), |
| 7232 |
("XCalibration", Fraction), |
| 7233 |
("YCalibration", Fraction), |
| 7234 |
("CalibrationUnits", str), |
| 7235 |
("Name", str), |
| 7236 |
("ThreshState", int), |
| 7237 |
("ThreshStateRed", int), |
| 7238 |
("tagid_10", None), |
| 7239 |
("ThreshStateGreen", int), |
| 7240 |
("ThreshStateBlue", int), |
| 7241 |
("ThreshStateLo", int), |
| 7242 |
("ThreshStateHi", int), |
| 7243 |
("Zoom", int), |
| 7244 |
("CreateTime", julian_datetime), |
| 7245 |
("LastSavedTime", julian_datetime), |
| 7246 |
("currentBuffer", int), |
| 7247 |
("grayFit", None), |
| 7248 |
("grayPointCount", None), |
| 7249 |
("grayX", Fraction), |
| 7250 |
("grayY", Fraction), |
| 7251 |
("grayMin", Fraction), |
| 7252 |
("grayMax", Fraction), |
| 7253 |
("grayUnitName", str), |
| 7254 |
("StandardLUT", int), |
| 7255 |
("wavelength", int), |
| 7256 |
("StagePosition", "(%i,2,2)u4"), |
| 7257 |
("CameraChipOffset", "(%i,2,2)u4"), |
| 7258 |
("OverlayMask", None), |
| 7259 |
("OverlayCompress", None), |
| 7260 |
("Overlay", None), |
| 7261 |
("SpecialOverlayMask", None), |
| 7262 |
("SpecialOverlayCompress", None), |
| 7263 |
("SpecialOverlay", None), |
| 7264 |
("ImageProperty", read_uic_image_property), |
| 7265 |
("StageLabel", "%ip"), |
| 7266 |
("AutoScaleLoInfo", Fraction), |
| 7267 |
("AutoScaleHiInfo", Fraction), |
| 7268 |
("AbsoluteZ", "(%i,2)u4"), |
| 7269 |
("AbsoluteZValid", "(%i,)u4"), |
| 7270 |
("Gamma", "I"), |
| 7271 |
("GammaRed", "I"), |
| 7272 |
("GammaGreen", "I"), |
| 7273 |
("GammaBlue", "I"), |
| 7274 |
("CameraBin", "2I"), |
| 7275 |
("NewLUT", int), |
| 7276 |
("ImagePropertyEx", None), |
| 7277 |
("PlaneProperty", int), |
| 7278 |
("UserLutTable", "(256,3)u1"), |
| 7279 |
("RedAutoScaleInfo", int), |
| 7280 |
("RedAutoScaleLoInfo", Fraction), |
| 7281 |
("RedAutoScaleHiInfo", Fraction), |
| 7282 |
("RedMinScaleInfo", int), |
| 7283 |
("RedMaxScaleInfo", int), |
| 7284 |
("GreenAutoScaleInfo", int), |
| 7285 |
("GreenAutoScaleLoInfo", Fraction), |
| 7286 |
("GreenAutoScaleHiInfo", Fraction), |
| 7287 |
("GreenMinScaleInfo", int), |
| 7288 |
("GreenMaxScaleInfo", int), |
| 7289 |
("BlueAutoScaleInfo", int), |
| 7290 |
("BlueAutoScaleLoInfo", Fraction), |
| 7291 |
("BlueAutoScaleHiInfo", Fraction), |
| 7292 |
("BlueMinScaleInfo", int), |
| 7293 |
("BlueMaxScaleInfo", int), |
| 7294 |
|
| 7295 |
] |
| 7296 |
|
| 7297 |
def PILATUS_HEADER(): |
| 7298 |
|
| 7299 |
|
| 7300 |
return { |
| 7301 |
"Detector": ([slice(1, None)], str), |
| 7302 |
"Pixel_size": ([1, 4], float), |
| 7303 |
"Silicon": ([3], float), |
| 7304 |
"Exposure_time": ([1], float), |
| 7305 |
"Exposure_period": ([1], float), |
| 7306 |
"Tau": ([1], float), |
| 7307 |
"Count_cutoff": ([1], int), |
| 7308 |
"Threshold_setting": ([1], float), |
| 7309 |
"Gain_setting": ([1, 2], str), |
| 7310 |
"N_excluded_pixels": ([1], int), |
| 7311 |
"Excluded_pixels": ([1], str), |
| 7312 |
"Flat_field": ([1], str), |
| 7313 |
"Trim_file": ([1], str), |
| 7314 |
"Image_path": ([1], str), |
| 7315 |
|
| 7316 |
"Wavelength": ([1], float), |
| 7317 |
"Energy_range": ([1, 2], float), |
| 7318 |
"Detector_distance": ([1], float), |
| 7319 |
"Detector_Voffset": ([1], float), |
| 7320 |
"Beam_xy": ([1, 2], float), |
| 7321 |
"Flux": ([1], str), |
| 7322 |
"Filter_transmission": ([1], float), |
| 7323 |
"Start_angle": ([1], float), |
| 7324 |
"Angle_increment": ([1], float), |
| 7325 |
"Detector_2theta": ([1], float), |
| 7326 |
"Polarization": ([1], float), |
| 7327 |
"Alpha": ([1], float), |
| 7328 |
"Kappa": ([1], float), |
| 7329 |
"Phi": ([1], float), |
| 7330 |
"Phi_increment": ([1], float), |
| 7331 |
"Chi": ([1], float), |
| 7332 |
"Chi_increment": ([1], float), |
| 7333 |
"Oscillation_axis": ([slice(1, None)], str), |
| 7334 |
"N_oscillations": ([1], int), |
| 7335 |
"Start_position": ([1], float), |
| 7336 |
"Position_increment": ([1], float), |
| 7337 |
"Shutter_time": ([1], float), |
| 7338 |
"Omega": ([1], float), |
| 7339 |
"Omega_increment": ([1], float), |
| 7340 |
} |
| 7341 |
|
| 7342 |
def REVERSE_BITORDER_BYTES(): |
| 7343 |
|
| 7344 |
return ( |
| 7345 |
b"\x00\x80@\xc0 \xa0`\xe0\x10\x90P\xd00\xb0p\xf0\x08\x88H\xc8(" |
| 7346 |
b"\xa8h\xe8\x18\x98X\xd88\xb8x\xf8\x04\x84D\xc4$\xa4d\xe4\x14" |
| 7347 |
b"\x94T\xd44\xb4t\xf4\x0c\x8cL\xcc,\xacl\xec\x1c\x9c\\\xdc<\xbc|" |
| 7348 |
b'\xfc\x02\x82B\xc2"\xa2b\xe2\x12\x92R\xd22\xb2r\xf2\n\x8aJ\xca*' |
| 7349 |
b"\xaaj\xea\x1a\x9aZ\xda:\xbaz\xfa\x06\x86F\xc6&\xa6f\xe6\x16" |
| 7350 |
b"\x96V\xd66\xb6v\xf6\x0e\x8eN\xce.\xaen\xee\x1e\x9e^\xde>\xbe~" |
| 7351 |
b"\xfe\x01\x81A\xc1!\xa1a\xe1\x11\x91Q\xd11\xb1q\xf1\t\x89I\xc9)" |
| 7352 |
b"\xa9i\xe9\x19\x99Y\xd99\xb9y\xf9\x05\x85E\xc5%\xa5e\xe5\x15" |
| 7353 |
b"\x95U\xd55\xb5u\xf5\r\x8dM\xcd-\xadm\xed\x1d\x9d]\xdd=\xbd}" |
| 7354 |
b"\xfd\x03\x83C\xc3#\xa3c\xe3\x13\x93S\xd33\xb3s\xf3\x0b\x8bK" |
| 7355 |
b"\xcb+\xabk\xeb\x1b\x9b[\xdb;\xbb{\xfb\x07\x87G\xc7'\xa7g\xe7" |
| 7356 |
b"\x17\x97W\xd77\xb7w\xf7\x0f\x8fO\xcf/\xafo\xef\x1f\x9f_" |
| 7357 |
b"\xdf?\xbf\x7f\xff" |
| 7358 |
) |
| 7359 |
|
| 7360 |
def REVERSE_BITORDER_ARRAY(): |
| 7361 |
|
| 7362 |
return numpy.frombuffer(TIFF.REVERSE_BITORDER_BYTES, dtype="uint8") |
| 7363 |
|
| 7364 |
def ALLOCATIONGRANULARITY(): |
| 7365 |
|
| 7366 |
import mmap |
| 7367 |
|
| 7368 |
return mmap.ALLOCATIONGRANULARITY |
| 7369 |
|
| 7370 |
|
| 7371 |
def read_tags(fh, byteorder, offsetsize, tagnames, customtags=None, maxifds=None): |
| 7372 |
"""Read tags from chain of IFDs and return as list of dicts. |
| 7373 |
|
| 7374 |
The file handle position must be at a valid IFD header. |
| 7375 |
|
| 7376 |
""" |
| 7377 |
if offsetsize == 4: |
| 7378 |
offsetformat = byteorder + "I" |
| 7379 |
tagnosize = 2 |
| 7380 |
tagnoformat = byteorder + "H" |
| 7381 |
tagsize = 12 |
| 7382 |
tagformat1 = byteorder + "HH" |
| 7383 |
tagformat2 = byteorder + "I4s" |
| 7384 |
elif offsetsize == 8: |
| 7385 |
offsetformat = byteorder + "Q" |
| 7386 |
tagnosize = 8 |
| 7387 |
tagnoformat = byteorder + "Q" |
| 7388 |
tagsize = 20 |
| 7389 |
tagformat1 = byteorder + "HH" |
| 7390 |
tagformat2 = byteorder + "Q8s" |
| 7391 |
else: |
| 7392 |
raise ValueError("invalid offset size") |
| 7393 |
|
| 7394 |
if customtags is None: |
| 7395 |
customtags = {} |
| 7396 |
if maxifds is None: |
| 7397 |
maxifds = 2**32 |
| 7398 |
|
| 7399 |
result = [] |
| 7400 |
unpack = struct.unpack |
| 7401 |
offset = fh.tell() |
| 7402 |
while len(result) < maxifds: |
| 7403 |
|
| 7404 |
try: |
| 7405 |
tagno = unpack(tagnoformat, fh.read(tagnosize))[0] |
| 7406 |
if tagno > 4096: |
| 7407 |
raise ValueError("suspicious number of tags") |
| 7408 |
except Exception: |
| 7409 |
warnings.warn("corrupted tag list at offset %i" % offset) |
| 7410 |
break |
| 7411 |
|
| 7412 |
tags = {} |
| 7413 |
data = fh.read(tagsize * tagno) |
| 7414 |
pos = fh.tell() |
| 7415 |
index = 0 |
| 7416 |
for _ in range(tagno): |
| 7417 |
code, type_ = unpack(tagformat1, data[index : index + 4]) |
| 7418 |
count, value = unpack(tagformat2, data[index + 4 : index + tagsize]) |
| 7419 |
index += tagsize |
| 7420 |
name = tagnames.get(code, str(code)) |
| 7421 |
try: |
| 7422 |
dtype = TIFF.DATA_FORMATS[type_] |
| 7423 |
except KeyError: |
| 7424 |
raise TiffTag.Error("unknown tag data type %i" % type_) |
| 7425 |
|
| 7426 |
fmt = "%s%i%s" % (byteorder, count * int(dtype[0]), dtype[1]) |
| 7427 |
size = struct.calcsize(fmt) |
| 7428 |
if size > offsetsize or code in customtags: |
| 7429 |
offset = unpack(offsetformat, value)[0] |
| 7430 |
if offset < 8 or offset > fh.size - size: |
| 7431 |
raise TiffTag.Error("invalid tag value offset %i" % offset) |
| 7432 |
fh.seek(offset) |
| 7433 |
if code in customtags: |
| 7434 |
readfunc = customtags[code][1] |
| 7435 |
value = readfunc(fh, byteorder, dtype, count, offsetsize) |
| 7436 |
elif type_ == 7 or (count > 1 and dtype[-1] == "B"): |
| 7437 |
value = read_bytes(fh, byteorder, dtype, count, offsetsize) |
| 7438 |
elif code in tagnames or dtype[-1] == "s": |
| 7439 |
value = unpack(fmt, fh.read(size)) |
| 7440 |
else: |
| 7441 |
value = read_numpy(fh, byteorder, dtype, count, offsetsize) |
| 7442 |
elif dtype[-1] == "B" or type_ == 7: |
| 7443 |
value = value[:size] |
| 7444 |
else: |
| 7445 |
value = unpack(fmt, value[:size]) |
| 7446 |
|
| 7447 |
if code not in customtags and code not in TIFF.TAG_TUPLE: |
| 7448 |
if len(value) == 1: |
| 7449 |
value = value[0] |
| 7450 |
if type_ != 7 and dtype[-1] == "s" and isinstance(value, bytes): |
| 7451 |
|
| 7452 |
|
| 7453 |
try: |
| 7454 |
value = bytes2str(stripascii(value).strip()) |
| 7455 |
except UnicodeDecodeError: |
| 7456 |
warnings.warn("tag %i: coercing invalid ASCII to bytes" % code) |
| 7457 |
|
| 7458 |
tags[name] = value |
| 7459 |
|
| 7460 |
result.append(tags) |
| 7461 |
|
| 7462 |
fh.seek(pos) |
| 7463 |
offset = unpack(offsetformat, fh.read(offsetsize))[0] |
| 7464 |
if offset == 0: |
| 7465 |
break |
| 7466 |
if offset >= fh.size: |
| 7467 |
warnings.warn("invalid page offset %i" % offset) |
| 7468 |
break |
| 7469 |
fh.seek(offset) |
| 7470 |
|
| 7471 |
if result and maxifds == 1: |
| 7472 |
result = result[0] |
| 7473 |
return result |
| 7474 |
|
| 7475 |
|
| 7476 |
def read_exif_ifd(fh, byteorder, dtype, count, offsetsize): |
| 7477 |
"""Read EXIF tags from file and return as dict.""" |
| 7478 |
exif = read_tags(fh, byteorder, offsetsize, TIFF.EXIF_TAGS, maxifds=1) |
| 7479 |
for name in ("ExifVersion", "FlashpixVersion"): |
| 7480 |
try: |
| 7481 |
exif[name] = bytes2str(exif[name]) |
| 7482 |
except Exception: |
| 7483 |
pass |
| 7484 |
if "UserComment" in exif: |
| 7485 |
idcode = exif["UserComment"][:8] |
| 7486 |
try: |
| 7487 |
if idcode == b"ASCII\x00\x00\x00": |
| 7488 |
exif["UserComment"] = bytes2str(exif["UserComment"][8:]) |
| 7489 |
elif idcode == b"UNICODE\x00": |
| 7490 |
exif["UserComment"] = exif["UserComment"][8:].decode("utf-16") |
| 7491 |
except Exception: |
| 7492 |
pass |
| 7493 |
return exif |
| 7494 |
|
| 7495 |
|
| 7496 |
def read_gps_ifd(fh, byteorder, dtype, count, offsetsize): |
| 7497 |
"""Read GPS tags from file and return as dict.""" |
| 7498 |
return read_tags(fh, byteorder, offsetsize, TIFF.GPS_TAGS, maxifds=1) |
| 7499 |
|
| 7500 |
|
| 7501 |
def read_interoperability_ifd(fh, byteorder, dtype, count, offsetsize): |
| 7502 |
"""Read Interoperability tags from file and return as dict.""" |
| 7503 |
tag_names = {1: "InteroperabilityIndex"} |
| 7504 |
return read_tags(fh, byteorder, offsetsize, tag_names, maxifds=1) |
| 7505 |
|
| 7506 |
|
| 7507 |
def read_bytes(fh, byteorder, dtype, count, offsetsize): |
| 7508 |
"""Read tag data from file and return as byte string.""" |
| 7509 |
dtype = "B" if dtype[-1] == "s" else byteorder + dtype[-1] |
| 7510 |
count *= numpy.dtype(dtype).itemsize |
| 7511 |
data = fh.read(count) |
| 7512 |
if len(data) != count: |
| 7513 |
warnings.warn("failed to read all bytes: %i, %i" % (len(data), count)) |
| 7514 |
return data |
| 7515 |
|
| 7516 |
|
| 7517 |
def read_utf8(fh, byteorder, dtype, count, offsetsize): |
| 7518 |
"""Read tag data from file and return as unicode string.""" |
| 7519 |
return fh.read(count).decode("utf-8") |
| 7520 |
|
| 7521 |
|
| 7522 |
def read_numpy(fh, byteorder, dtype, count, offsetsize): |
| 7523 |
"""Read tag data from file and return as numpy array.""" |
| 7524 |
dtype = "b" if dtype[-1] == "s" else byteorder + dtype[-1] |
| 7525 |
return fh.read_array(dtype, count) |
| 7526 |
|
| 7527 |
|
| 7528 |
def read_colormap(fh, byteorder, dtype, count, offsetsize): |
| 7529 |
"""Read ColorMap data from file and return as numpy array.""" |
| 7530 |
cmap = fh.read_array(byteorder + dtype[-1], count) |
| 7531 |
cmap.shape = (3, -1) |
| 7532 |
return cmap |
| 7533 |
|
| 7534 |
|
| 7535 |
def read_json(fh, byteorder, dtype, count, offsetsize): |
| 7536 |
"""Read JSON tag data from file and return as object.""" |
| 7537 |
data = fh.read(count) |
| 7538 |
try: |
| 7539 |
return json.loads(unicode(stripnull(data), "utf-8")) |
| 7540 |
except ValueError: |
| 7541 |
warnings.warn("invalid JSON '%s'" % data) |
| 7542 |
|
| 7543 |
|
| 7544 |
def read_mm_header(fh, byteorder, dtype, count, offsetsize): |
| 7545 |
"""Read FluoView mm_header tag from file and return as dict.""" |
| 7546 |
mmh = fh.read_record(TIFF.MM_HEADER, byteorder=byteorder) |
| 7547 |
mmh = recarray2dict(mmh) |
| 7548 |
mmh["Dimensions"] = [ |
| 7549 |
(bytes2str(d[0]).strip(), d[1], d[2], d[3], bytes2str(d[4]).strip()) |
| 7550 |
for d in mmh["Dimensions"] |
| 7551 |
] |
| 7552 |
d = mmh["GrayChannel"] |
| 7553 |
mmh["GrayChannel"] = ( |
| 7554 |
bytes2str(d[0]).strip(), |
| 7555 |
d[1], |
| 7556 |
d[2], |
| 7557 |
d[3], |
| 7558 |
bytes2str(d[4]).strip(), |
| 7559 |
) |
| 7560 |
return mmh |
| 7561 |
|
| 7562 |
|
| 7563 |
def read_mm_stamp(fh, byteorder, dtype, count, offsetsize): |
| 7564 |
"""Read FluoView mm_stamp tag from file and return as numpy.ndarray.""" |
| 7565 |
return fh.read_array(byteorder + "f8", 8) |
| 7566 |
|
| 7567 |
|
| 7568 |
def read_uic1tag(fh, byteorder, dtype, count, offsetsize, planecount=None): |
| 7569 |
"""Read MetaMorph STK UIC1Tag from file and return as dict. |
| 7570 |
|
| 7571 |
Return empty dictionary if planecount is unknown. |
| 7572 |
|
| 7573 |
""" |
| 7574 |
assert dtype in ("2I", "1I") and byteorder == "<" |
| 7575 |
result = {} |
| 7576 |
if dtype == "2I": |
| 7577 |
|
| 7578 |
values = fh.read_array("<u4", 2 * count).reshape(count, 2) |
| 7579 |
result = {"ZDistance": values[:, 0] / values[:, 1]} |
| 7580 |
elif planecount: |
| 7581 |
for _ in range(count): |
| 7582 |
tagid = struct.unpack("<I", fh.read(4))[0] |
| 7583 |
if tagid in (28, 29, 37, 40, 41): |
| 7584 |
|
| 7585 |
fh.read(4) |
| 7586 |
continue |
| 7587 |
name, value = read_uic_tag(fh, tagid, planecount, offset=True) |
| 7588 |
result[name] = value |
| 7589 |
return result |
| 7590 |
|
| 7591 |
|
| 7592 |
def read_uic2tag(fh, byteorder, dtype, planecount, offsetsize): |
| 7593 |
"""Read MetaMorph STK UIC2Tag from file and return as dict.""" |
| 7594 |
assert dtype == "2I" and byteorder == "<" |
| 7595 |
values = fh.read_array("<u4", 6 * planecount).reshape(planecount, 6) |
| 7596 |
return { |
| 7597 |
"ZDistance": values[:, 0] / values[:, 1], |
| 7598 |
"DateCreated": values[:, 2], |
| 7599 |
"TimeCreated": values[:, 3], |
| 7600 |
"DateModified": values[:, 4], |
| 7601 |
"TimeModified": values[:, 5], |
| 7602 |
} |
| 7603 |
|
| 7604 |
|
| 7605 |
def read_uic3tag(fh, byteorder, dtype, planecount, offsetsize): |
| 7606 |
"""Read MetaMorph STK UIC3Tag from file and return as dict.""" |
| 7607 |
assert dtype == "2I" and byteorder == "<" |
| 7608 |
values = fh.read_array("<u4", 2 * planecount).reshape(planecount, 2) |
| 7609 |
return {"Wavelengths": values[:, 0] / values[:, 1]} |
| 7610 |
|
| 7611 |
|
| 7612 |
def read_uic4tag(fh, byteorder, dtype, planecount, offsetsize): |
| 7613 |
"""Read MetaMorph STK UIC4Tag from file and return as dict.""" |
| 7614 |
assert dtype == "1I" and byteorder == "<" |
| 7615 |
result = {} |
| 7616 |
while True: |
| 7617 |
tagid = struct.unpack("<H", fh.read(2))[0] |
| 7618 |
if tagid == 0: |
| 7619 |
break |
| 7620 |
name, value = read_uic_tag(fh, tagid, planecount, offset=False) |
| 7621 |
result[name] = value |
| 7622 |
return result |
| 7623 |
|
| 7624 |
|
| 7625 |
def read_uic_tag(fh, tagid, planecount, offset): |
| 7626 |
"""Read a single UIC tag value from file and return tag name and value. |
| 7627 |
|
| 7628 |
UIC1Tags use an offset. |
| 7629 |
|
| 7630 |
""" |
| 7631 |
|
| 7632 |
def read_int(count=1): |
| 7633 |
value = struct.unpack("<%iI" % count, fh.read(4 * count)) |
| 7634 |
return value[0] if count == 1 else value |
| 7635 |
|
| 7636 |
try: |
| 7637 |
name, dtype = TIFF.UIC_TAGS[tagid] |
| 7638 |
except IndexError: |
| 7639 |
|
| 7640 |
return "_TagId%i" % tagid, read_int() |
| 7641 |
|
| 7642 |
Fraction = TIFF.UIC_TAGS[4][1] |
| 7643 |
|
| 7644 |
if offset: |
| 7645 |
pos = fh.tell() |
| 7646 |
if dtype not in (int, None): |
| 7647 |
off = read_int() |
| 7648 |
if off < 8: |
| 7649 |
if dtype is str: |
| 7650 |
return name, "" |
| 7651 |
warnings.warn("invalid offset for uic tag '%s': %i" % (name, off)) |
| 7652 |
return name, off |
| 7653 |
fh.seek(off) |
| 7654 |
|
| 7655 |
if dtype is None: |
| 7656 |
|
| 7657 |
name = "_" + name |
| 7658 |
value = read_int() |
| 7659 |
elif dtype is int: |
| 7660 |
|
| 7661 |
value = read_int() |
| 7662 |
elif dtype is Fraction: |
| 7663 |
|
| 7664 |
value = read_int(2) |
| 7665 |
value = value[0] / value[1] |
| 7666 |
elif dtype is julian_datetime: |
| 7667 |
|
| 7668 |
value = julian_datetime(*read_int(2)) |
| 7669 |
elif dtype is read_uic_image_property: |
| 7670 |
|
| 7671 |
value = read_uic_image_property(fh) |
| 7672 |
elif dtype is str: |
| 7673 |
|
| 7674 |
size = read_int() |
| 7675 |
if 0 <= size < 2**10: |
| 7676 |
value = struct.unpack("%is" % size, fh.read(size))[0][:-1] |
| 7677 |
value = bytes2str(stripnull(value)) |
| 7678 |
elif offset: |
| 7679 |
value = "" |
| 7680 |
warnings.warn("corrupt string in uic tag '%s'" % name) |
| 7681 |
else: |
| 7682 |
raise ValueError("invalid string size: %i" % size) |
| 7683 |
elif dtype == "%ip": |
| 7684 |
|
| 7685 |
value = [] |
| 7686 |
for _ in range(planecount): |
| 7687 |
size = read_int() |
| 7688 |
if 0 <= size < 2**10: |
| 7689 |
string = struct.unpack("%is" % size, fh.read(size))[0][:-1] |
| 7690 |
string = bytes2str(stripnull(string)) |
| 7691 |
value.append(string) |
| 7692 |
elif offset: |
| 7693 |
warnings.warn("corrupt string in uic tag '%s'" % name) |
| 7694 |
else: |
| 7695 |
raise ValueError("invalid string size: %i" % size) |
| 7696 |
else: |
| 7697 |
|
| 7698 |
dtype = "<" + dtype |
| 7699 |
if "%i" in dtype: |
| 7700 |
dtype = dtype % planecount |
| 7701 |
if "(" in dtype: |
| 7702 |
|
| 7703 |
value = fh.read_array(dtype, 1)[0] |
| 7704 |
if value.shape[-1] == 2: |
| 7705 |
|
| 7706 |
value = value[..., 0] / value[..., 1] |
| 7707 |
else: |
| 7708 |
|
| 7709 |
value = struct.unpack(dtype, fh.read(struct.calcsize(dtype))) |
| 7710 |
if len(value) == 1: |
| 7711 |
value = value[0] |
| 7712 |
|
| 7713 |
if offset: |
| 7714 |
fh.seek(pos + 4) |
| 7715 |
|
| 7716 |
return name, value |
| 7717 |
|
| 7718 |
|
| 7719 |
def read_uic_image_property(fh): |
| 7720 |
"""Read UIC ImagePropertyEx tag from file and return as dict.""" |
| 7721 |
|
| 7722 |
size = struct.unpack("B", fh.read(1))[0] |
| 7723 |
name = struct.unpack("%is" % size, fh.read(size))[0][:-1] |
| 7724 |
flags, prop = struct.unpack("<IB", fh.read(5)) |
| 7725 |
if prop == 1: |
| 7726 |
value = struct.unpack("II", fh.read(8)) |
| 7727 |
value = value[0] / value[1] |
| 7728 |
else: |
| 7729 |
size = struct.unpack("B", fh.read(1))[0] |
| 7730 |
value = struct.unpack("%is" % size, fh.read(size))[0] |
| 7731 |
return dict(name=name, flags=flags, value=value) |
| 7732 |
|
| 7733 |
|
| 7734 |
def read_cz_lsminfo(fh, byteorder, dtype, count, offsetsize): |
| 7735 |
"""Read CZ_LSMINFO tag from file and return as dict.""" |
| 7736 |
assert byteorder == "<" |
| 7737 |
magic_number, structure_size = struct.unpack("<II", fh.read(8)) |
| 7738 |
if magic_number not in (50350412, 67127628): |
| 7739 |
raise ValueError("invalid CZ_LSMINFO structure") |
| 7740 |
fh.seek(-8, 1) |
| 7741 |
|
| 7742 |
if structure_size < numpy.dtype(TIFF.CZ_LSMINFO).itemsize: |
| 7743 |
|
| 7744 |
lsminfo = [] |
| 7745 |
size = 0 |
| 7746 |
for name, dtype in TIFF.CZ_LSMINFO: |
| 7747 |
size += numpy.dtype(dtype).itemsize |
| 7748 |
if size > structure_size: |
| 7749 |
break |
| 7750 |
lsminfo.append((name, dtype)) |
| 7751 |
else: |
| 7752 |
lsminfo = TIFF.CZ_LSMINFO |
| 7753 |
|
| 7754 |
lsminfo = fh.read_record(lsminfo, byteorder=byteorder) |
| 7755 |
lsminfo = recarray2dict(lsminfo) |
| 7756 |
|
| 7757 |
|
| 7758 |
for name, reader in TIFF.CZ_LSMINFO_READERS.items(): |
| 7759 |
if reader is None: |
| 7760 |
continue |
| 7761 |
offset = lsminfo.get("Offset" + name, 0) |
| 7762 |
if offset < 8: |
| 7763 |
continue |
| 7764 |
fh.seek(offset) |
| 7765 |
try: |
| 7766 |
lsminfo[name] = reader(fh) |
| 7767 |
except ValueError: |
| 7768 |
pass |
| 7769 |
return lsminfo |
| 7770 |
|
| 7771 |
|
| 7772 |
def read_lsm_floatpairs(fh): |
| 7773 |
"""Read LSM sequence of float pairs from file and return as list.""" |
| 7774 |
size = struct.unpack("<i", fh.read(4))[0] |
| 7775 |
return fh.read_array("<2f8", count=size) |
| 7776 |
|
| 7777 |
|
| 7778 |
def read_lsm_positions(fh): |
| 7779 |
"""Read LSM positions from file and return as list.""" |
| 7780 |
size = struct.unpack("<I", fh.read(4))[0] |
| 7781 |
return fh.read_array("<2f8", count=size) |
| 7782 |
|
| 7783 |
|
| 7784 |
def read_lsm_timestamps(fh): |
| 7785 |
"""Read LSM time stamps from file and return as list.""" |
| 7786 |
size, count = struct.unpack("<ii", fh.read(8)) |
| 7787 |
if size != (8 + 8 * count): |
| 7788 |
warnings.warn("invalid LSM TimeStamps block") |
| 7789 |
return [] |
| 7790 |
|
| 7791 |
return fh.read_array("<f8", count=count) |
| 7792 |
|
| 7793 |
|
| 7794 |
def read_lsm_eventlist(fh): |
| 7795 |
"""Read LSM events from file and return as list of (time, type, text).""" |
| 7796 |
count = struct.unpack("<II", fh.read(8))[1] |
| 7797 |
events = [] |
| 7798 |
while count > 0: |
| 7799 |
esize, etime, etype = struct.unpack("<IdI", fh.read(16)) |
| 7800 |
etext = bytes2str(stripnull(fh.read(esize - 16))) |
| 7801 |
events.append((etime, etype, etext)) |
| 7802 |
count -= 1 |
| 7803 |
return events |
| 7804 |
|
| 7805 |
|
| 7806 |
def read_lsm_channelcolors(fh): |
| 7807 |
"""Read LSM ChannelColors structure from file and return as dict.""" |
| 7808 |
result = {"Mono": False, "Colors": [], "ColorNames": []} |
| 7809 |
pos = fh.tell() |
| 7810 |
size, ncolors, nnames, coffset, noffset, mono = struct.unpack( |
| 7811 |
"<IIIIII", fh.read(24) |
| 7812 |
) |
| 7813 |
if ncolors != nnames: |
| 7814 |
warnings.warn("invalid LSM ChannelColors structure") |
| 7815 |
return result |
| 7816 |
result["Mono"] = bool(mono) |
| 7817 |
|
| 7818 |
fh.seek(pos + coffset) |
| 7819 |
colors = fh.read_array("uint8", count=ncolors * 4).reshape((ncolors, 4)) |
| 7820 |
result["Colors"] = colors.tolist() |
| 7821 |
|
| 7822 |
fh.seek(pos + noffset) |
| 7823 |
buffer = fh.read(size - noffset) |
| 7824 |
names = [] |
| 7825 |
while len(buffer) > 4: |
| 7826 |
size = struct.unpack("<I", buffer[:4])[0] |
| 7827 |
names.append(bytes2str(buffer[4 : 3 + size])) |
| 7828 |
buffer = buffer[4 + size :] |
| 7829 |
result["ColorNames"] = names |
| 7830 |
return result |
| 7831 |
|
| 7832 |
|
| 7833 |
def read_lsm_scaninfo(fh): |
| 7834 |
"""Read LSM ScanInfo structure from file and return as dict.""" |
| 7835 |
block = {} |
| 7836 |
blocks = [block] |
| 7837 |
unpack = struct.unpack |
| 7838 |
if struct.unpack("<I", fh.read(4))[0] != 0x10000000: |
| 7839 |
|
| 7840 |
warnings.warn("invalid LSM ScanInfo structure") |
| 7841 |
return block |
| 7842 |
fh.read(8) |
| 7843 |
while True: |
| 7844 |
entry, dtype, size = unpack("<III", fh.read(12)) |
| 7845 |
if dtype == 2: |
| 7846 |
|
| 7847 |
value = bytes2str(stripnull(fh.read(size))) |
| 7848 |
elif dtype == 4: |
| 7849 |
|
| 7850 |
value = unpack("<i", fh.read(4))[0] |
| 7851 |
elif dtype == 5: |
| 7852 |
|
| 7853 |
value = unpack("<d", fh.read(8))[0] |
| 7854 |
else: |
| 7855 |
value = 0 |
| 7856 |
if entry in TIFF.CZ_LSMINFO_SCANINFO_ARRAYS: |
| 7857 |
blocks.append(block) |
| 7858 |
name = TIFF.CZ_LSMINFO_SCANINFO_ARRAYS[entry] |
| 7859 |
newobj = [] |
| 7860 |
block[name] = newobj |
| 7861 |
block = newobj |
| 7862 |
elif entry in TIFF.CZ_LSMINFO_SCANINFO_STRUCTS: |
| 7863 |
blocks.append(block) |
| 7864 |
newobj = {} |
| 7865 |
block.append(newobj) |
| 7866 |
block = newobj |
| 7867 |
elif entry in TIFF.CZ_LSMINFO_SCANINFO_ATTRIBUTES: |
| 7868 |
name = TIFF.CZ_LSMINFO_SCANINFO_ATTRIBUTES[entry] |
| 7869 |
block[name] = value |
| 7870 |
elif entry == 0xFFFFFFFF: |
| 7871 |
|
| 7872 |
block = blocks.pop() |
| 7873 |
else: |
| 7874 |
|
| 7875 |
block["Entry0x%x" % entry] = value |
| 7876 |
if not blocks: |
| 7877 |
break |
| 7878 |
return block |
| 7879 |
|
| 7880 |
|
| 7881 |
def read_tvips_header(fh, byteorder, dtype, count, offsetsize): |
| 7882 |
"""Read TVIPS EM-MENU headers and return as dict.""" |
| 7883 |
result = {} |
| 7884 |
header = fh.read_record(TIFF.TVIPS_HEADER_V1, byteorder=byteorder) |
| 7885 |
for name, typestr in TIFF.TVIPS_HEADER_V1: |
| 7886 |
result[name] = header[name].tolist() |
| 7887 |
if header["Version"] == 2: |
| 7888 |
header = fh.read_record(TIFF.TVIPS_HEADER_V2, byteorder=byteorder) |
| 7889 |
if header["Magic"] != int(0xAAAAAAAA): |
| 7890 |
warnings.warn("invalid TVIPS v2 magic number") |
| 7891 |
return {} |
| 7892 |
|
| 7893 |
for name, typestr in TIFF.TVIPS_HEADER_V2: |
| 7894 |
if typestr.startswith("V"): |
| 7895 |
s = header[name].tostring().decode("utf16", errors="ignore") |
| 7896 |
result[name] = stripnull(s, null="\0") |
| 7897 |
else: |
| 7898 |
result[name] = header[name].tolist() |
| 7899 |
|
| 7900 |
for axis in "XY": |
| 7901 |
header["PhysicalPixelSize" + axis] /= 1e9 |
| 7902 |
header["PixelSize" + axis] /= 1e9 |
| 7903 |
elif header.version != 1: |
| 7904 |
warnings.warn("unknown TVIPS header version") |
| 7905 |
return {} |
| 7906 |
return result |
| 7907 |
|
| 7908 |
|
| 7909 |
def read_fei_metadata(fh, byteorder, dtype, count, offsetsize): |
| 7910 |
"""Read FEI SFEG/HELIOS headers and return as dict.""" |
| 7911 |
result = {} |
| 7912 |
section = {} |
| 7913 |
data = bytes2str(fh.read(count)) |
| 7914 |
for line in data.splitlines(): |
| 7915 |
line = line.strip() |
| 7916 |
if line.startswith("["): |
| 7917 |
section = {} |
| 7918 |
result[line[1:-1]] = section |
| 7919 |
continue |
| 7920 |
try: |
| 7921 |
key, value = line.split("=") |
| 7922 |
except ValueError: |
| 7923 |
continue |
| 7924 |
section[key] = astype(value) |
| 7925 |
return result |
| 7926 |
|
| 7927 |
|
| 7928 |
def read_cz_sem(fh, byteorder, dtype, count, offsetsize): |
| 7929 |
"""Read Zeiss SEM tag and return as dict.""" |
| 7930 |
result = {"": ()} |
| 7931 |
key = None |
| 7932 |
data = bytes2str(fh.read(count)) |
| 7933 |
for line in data.splitlines(): |
| 7934 |
if line.isupper(): |
| 7935 |
key = line.lower() |
| 7936 |
elif key: |
| 7937 |
try: |
| 7938 |
name, value = line.split("=") |
| 7939 |
except ValueError: |
| 7940 |
continue |
| 7941 |
value = value.strip() |
| 7942 |
unit = "" |
| 7943 |
try: |
| 7944 |
v, u = value.split() |
| 7945 |
number = astype(v, (int, float)) |
| 7946 |
if number != v: |
| 7947 |
value = number |
| 7948 |
unit = u |
| 7949 |
except Exception: |
| 7950 |
number = astype(value, (int, float)) |
| 7951 |
if number != value: |
| 7952 |
value = number |
| 7953 |
if value in ("No", "Off"): |
| 7954 |
value = False |
| 7955 |
elif value in ("Yes", "On"): |
| 7956 |
value = True |
| 7957 |
result[key] = (name.strip(), value) |
| 7958 |
if unit: |
| 7959 |
result[key] += (unit,) |
| 7960 |
key = None |
| 7961 |
else: |
| 7962 |
result[""] += (astype(line, (int, float)),) |
| 7963 |
return result |
| 7964 |
|
| 7965 |
|
| 7966 |
def read_nih_image_header(fh, byteorder, dtype, count, offsetsize): |
| 7967 |
"""Read NIH_IMAGE_HEADER tag from file and return as dict.""" |
| 7968 |
a = fh.read_record(TIFF.NIH_IMAGE_HEADER, byteorder=byteorder) |
| 7969 |
a = a.view(a.dtype.newbyteorder(byteorder)) |
| 7970 |
a = recarray2dict(a) |
| 7971 |
a["XUnit"] = a["XUnit"][: a["XUnitSize"]] |
| 7972 |
a["UM"] = a["UM"][: a["UMsize"]] |
| 7973 |
return a |
| 7974 |
|
| 7975 |
|
| 7976 |
def read_scanimage_metadata(fh): |
| 7977 |
"""Read ScanImage BigTIFF v3 static and ROI metadata from open file. |
| 7978 |
|
| 7979 |
Return non-varying frame data as dict and ROI group data as JSON. |
| 7980 |
|
| 7981 |
The settings can be used to read image data and metadata without parsing |
| 7982 |
the TIFF file. |
| 7983 |
|
| 7984 |
Raise ValueError if file does not contain valid ScanImage v3 metadata. |
| 7985 |
|
| 7986 |
""" |
| 7987 |
fh.seek(0) |
| 7988 |
try: |
| 7989 |
byteorder, version = struct.unpack("<2sH", fh.read(4)) |
| 7990 |
if byteorder != b"II" or version != 43: |
| 7991 |
raise Exception |
| 7992 |
fh.seek(16) |
| 7993 |
magic, version, size0, size1 = struct.unpack("<IIII", fh.read(16)) |
| 7994 |
if magic != 117637889 or version != 3: |
| 7995 |
raise Exception |
| 7996 |
except Exception: |
| 7997 |
raise ValueError("not a ScanImage BigTIFF v3 file") |
| 7998 |
|
| 7999 |
frame_data = matlabstr2py(bytes2str(fh.read(size0)[:-1])) |
| 8000 |
roi_data = read_json(fh, "<", None, size1, None) if size1 > 1 else {} |
| 8001 |
return frame_data, roi_data |
| 8002 |
|
| 8003 |
|
| 8004 |
def read_micromanager_metadata(fh): |
| 8005 |
"""Read MicroManager non-TIFF settings from open file and return as dict. |
| 8006 |
|
| 8007 |
The settings can be used to read image data without parsing the TIFF file. |
| 8008 |
|
| 8009 |
Raise ValueError if the file does not contain valid MicroManager metadata. |
| 8010 |
|
| 8011 |
""" |
| 8012 |
fh.seek(0) |
| 8013 |
try: |
| 8014 |
byteorder = {b"II": "<", b"MM": ">"}[fh.read(2)] |
| 8015 |
except IndexError: |
| 8016 |
raise ValueError("not a MicroManager TIFF file") |
| 8017 |
|
| 8018 |
result = {} |
| 8019 |
fh.seek(8) |
| 8020 |
( |
| 8021 |
index_header, |
| 8022 |
index_offset, |
| 8023 |
display_header, |
| 8024 |
display_offset, |
| 8025 |
comments_header, |
| 8026 |
comments_offset, |
| 8027 |
summary_header, |
| 8028 |
summary_length, |
| 8029 |
) = struct.unpack(byteorder + "IIIIIIII", fh.read(32)) |
| 8030 |
|
| 8031 |
if summary_header != 2355492: |
| 8032 |
raise ValueError("invalid MicroManager summary header") |
| 8033 |
result["Summary"] = read_json(fh, byteorder, None, summary_length, None) |
| 8034 |
|
| 8035 |
if index_header != 54773648: |
| 8036 |
raise ValueError("invalid MicroManager index header") |
| 8037 |
fh.seek(index_offset) |
| 8038 |
header, count = struct.unpack(byteorder + "II", fh.read(8)) |
| 8039 |
if header != 3453623: |
| 8040 |
raise ValueError("invalid MicroManager index header") |
| 8041 |
data = struct.unpack(byteorder + "IIIII" * count, fh.read(20 * count)) |
| 8042 |
result["IndexMap"] = { |
| 8043 |
"Channel": data[::5], |
| 8044 |
"Slice": data[1::5], |
| 8045 |
"Frame": data[2::5], |
| 8046 |
"Position": data[3::5], |
| 8047 |
"Offset": data[4::5], |
| 8048 |
} |
| 8049 |
|
| 8050 |
if display_header != 483765892: |
| 8051 |
raise ValueError("invalid MicroManager display header") |
| 8052 |
fh.seek(display_offset) |
| 8053 |
header, count = struct.unpack(byteorder + "II", fh.read(8)) |
| 8054 |
if header != 347834724: |
| 8055 |
raise ValueError("invalid MicroManager display header") |
| 8056 |
result["DisplaySettings"] = read_json(fh, byteorder, None, count, None) |
| 8057 |
|
| 8058 |
if comments_header != 99384722: |
| 8059 |
raise ValueError("invalid MicroManager comments header") |
| 8060 |
fh.seek(comments_offset) |
| 8061 |
header, count = struct.unpack(byteorder + "II", fh.read(8)) |
| 8062 |
if header != 84720485: |
| 8063 |
raise ValueError("invalid MicroManager comments header") |
| 8064 |
result["Comments"] = read_json(fh, byteorder, None, count, None) |
| 8065 |
|
| 8066 |
return result |
| 8067 |
|
| 8068 |
|
| 8069 |
def read_metaseries_catalog(fh): |
| 8070 |
"""Read MetaSeries non-TIFF hint catalog from file. |
| 8071 |
|
| 8072 |
Raise ValueError if the file does not contain a valid hint catalog. |
| 8073 |
|
| 8074 |
""" |
| 8075 |
|
| 8076 |
raise NotImplementedError() |
| 8077 |
|
| 8078 |
|
| 8079 |
def imagej_metadata_tags(metadata, byteorder): |
| 8080 |
"""Return IJMetadata and IJMetadataByteCounts tags from metadata dict. |
| 8081 |
|
| 8082 |
The tags can be passed to the TiffWriter.save function as extratags. |
| 8083 |
|
| 8084 |
The metadata dict may contain the following keys and values: |
| 8085 |
|
| 8086 |
Info : str |
| 8087 |
Human-readable information as string. |
| 8088 |
Labels : sequence of str |
| 8089 |
Human-readable labels for each channel. |
| 8090 |
Ranges : sequence of doubles |
| 8091 |
Lower and upper values for each channel. |
| 8092 |
LUTs : sequence of (3, 256) uint8 ndarrays |
| 8093 |
Color palettes for each channel. |
| 8094 |
Plot : bytes |
| 8095 |
Undocumented ImageJ internal format. |
| 8096 |
ROI: bytes |
| 8097 |
Undocumented ImageJ internal region of interest format. |
| 8098 |
Overlays : bytes |
| 8099 |
Undocumented ImageJ internal format. |
| 8100 |
|
| 8101 |
""" |
| 8102 |
header = [{">": b"IJIJ", "<": b"JIJI"}[byteorder]] |
| 8103 |
bytecounts = [0] |
| 8104 |
body = [] |
| 8105 |
|
| 8106 |
def _string(data, byteorder): |
| 8107 |
return data.encode("utf-16" + {">": "be", "<": "le"}[byteorder]) |
| 8108 |
|
| 8109 |
def _doubles(data, byteorder): |
| 8110 |
return struct.pack(byteorder + ("d" * len(data)), *data) |
| 8111 |
|
| 8112 |
def _ndarray(data, byteorder): |
| 8113 |
return data.tobytes() |
| 8114 |
|
| 8115 |
def _bytes(data, byteorder): |
| 8116 |
return data |
| 8117 |
|
| 8118 |
metadata_types = ( |
| 8119 |
("Info", b"info", 1, _string), |
| 8120 |
("Labels", b"labl", None, _string), |
| 8121 |
("Ranges", b"rang", 1, _doubles), |
| 8122 |
("LUTs", b"luts", None, _ndarray), |
| 8123 |
("Plot", b"plot", 1, _bytes), |
| 8124 |
("ROI", b"roi ", 1, _bytes), |
| 8125 |
("Overlays", b"over", None, _bytes), |
| 8126 |
) |
| 8127 |
|
| 8128 |
for key, mtype, count, func in metadata_types: |
| 8129 |
if key.lower() in metadata: |
| 8130 |
key = key.lower() |
| 8131 |
elif key not in metadata: |
| 8132 |
continue |
| 8133 |
if byteorder == "<": |
| 8134 |
mtype = mtype[::-1] |
| 8135 |
values = metadata[key] |
| 8136 |
if count is None: |
| 8137 |
count = len(values) |
| 8138 |
else: |
| 8139 |
values = [values] |
| 8140 |
header.append(mtype + struct.pack(byteorder + "I", count)) |
| 8141 |
for value in values: |
| 8142 |
data = func(value, byteorder) |
| 8143 |
body.append(data) |
| 8144 |
bytecounts.append(len(data)) |
| 8145 |
|
| 8146 |
if not body: |
| 8147 |
return () |
| 8148 |
body = b"".join(body) |
| 8149 |
header = b"".join(header) |
| 8150 |
data = header + body |
| 8151 |
bytecounts[0] = len(header) |
| 8152 |
bytecounts = struct.pack(byteorder + ("I" * len(bytecounts)), *bytecounts) |
| 8153 |
return ( |
| 8154 |
(50839, "B", len(data), data, True), |
| 8155 |
(50838, "I", len(bytecounts) // 4, bytecounts, True), |
| 8156 |
) |
| 8157 |
|
| 8158 |
|
| 8159 |
def imagej_metadata(data, bytecounts, byteorder): |
| 8160 |
"""Return IJMetadata tag value as dict. |
| 8161 |
|
| 8162 |
The 'Info' string can have multiple formats, e.g. OIF or ScanImage, |
| 8163 |
that might be parsed into dicts using the matlabstr2py or |
| 8164 |
oiffile.SettingsFile functions. |
| 8165 |
|
| 8166 |
""" |
| 8167 |
|
| 8168 |
def _string(data, byteorder): |
| 8169 |
return data.decode("utf-16" + {">": "be", "<": "le"}[byteorder]) |
| 8170 |
|
| 8171 |
def _doubles(data, byteorder): |
| 8172 |
return struct.unpack(byteorder + ("d" * (len(data) // 8)), data) |
| 8173 |
|
| 8174 |
def _lut(data, byteorder): |
| 8175 |
return numpy.frombuffer(data, "uint8").reshape(-1, 256) |
| 8176 |
|
| 8177 |
def _bytes(data, byteorder): |
| 8178 |
return data |
| 8179 |
|
| 8180 |
metadata_types = { |
| 8181 |
b"info": ("Info", _string), |
| 8182 |
b"labl": ("Labels", _string), |
| 8183 |
b"rang": ("Ranges", _doubles), |
| 8184 |
b"luts": ("LUTs", _lut), |
| 8185 |
b"plot": ("Plots", _bytes), |
| 8186 |
b"roi ": ("ROI", _bytes), |
| 8187 |
b"over": ("Overlays", _bytes), |
| 8188 |
} |
| 8189 |
metadata_types.update( |
| 8190 |
dict((k[::-1], v) for k, v in metadata_types.items()) |
| 8191 |
) |
| 8192 |
|
| 8193 |
if not bytecounts: |
| 8194 |
raise ValueError("no ImageJ metadata") |
| 8195 |
|
| 8196 |
if data[:4] not in (b"IJIJ", b"JIJI"): |
| 8197 |
raise ValueError("invalid ImageJ metadata") |
| 8198 |
|
| 8199 |
header_size = bytecounts[0] |
| 8200 |
if header_size < 12 or header_size > 804: |
| 8201 |
raise ValueError("invalid ImageJ metadata header size") |
| 8202 |
|
| 8203 |
ntypes = (header_size - 4) // 8 |
| 8204 |
header = struct.unpack(byteorder + "4sI" * ntypes, data[4 : 4 + ntypes * 8]) |
| 8205 |
pos = 4 + ntypes * 8 |
| 8206 |
counter = 0 |
| 8207 |
result = {} |
| 8208 |
for mtype, count in zip(header[::2], header[1::2]): |
| 8209 |
values = [] |
| 8210 |
name, func = metadata_types.get(mtype, (bytes2str(mtype), read_bytes)) |
| 8211 |
for _ in range(count): |
| 8212 |
counter += 1 |
| 8213 |
pos1 = pos + bytecounts[counter] |
| 8214 |
values.append(func(data[pos:pos1], byteorder)) |
| 8215 |
pos = pos1 |
| 8216 |
result[name.strip()] = values[0] if count == 1 else values |
| 8217 |
return result |
| 8218 |
|
| 8219 |
|
| 8220 |
def imagej_description_metadata(description): |
| 8221 |
"""Return metatata from ImageJ image description as dict. |
| 8222 |
|
| 8223 |
Raise ValueError if not a valid ImageJ description. |
| 8224 |
|
| 8225 |
>>> description = 'ImageJ=1.11a\\nimages=510\\nhyperstack=true\\n' |
| 8226 |
>>> imagej_description_metadata(description) # doctest: +SKIP |
| 8227 |
{'ImageJ': '1.11a', 'images': 510, 'hyperstack': True} |
| 8228 |
|
| 8229 |
""" |
| 8230 |
|
| 8231 |
def _bool(val): |
| 8232 |
return {"true": True, "false": False}[val.lower()] |
| 8233 |
|
| 8234 |
result = {} |
| 8235 |
for line in description.splitlines(): |
| 8236 |
try: |
| 8237 |
key, val = line.split("=") |
| 8238 |
except Exception: |
| 8239 |
continue |
| 8240 |
key = key.strip() |
| 8241 |
val = val.strip() |
| 8242 |
for dtype in (int, float, _bool): |
| 8243 |
try: |
| 8244 |
val = dtype(val) |
| 8245 |
break |
| 8246 |
except Exception: |
| 8247 |
pass |
| 8248 |
result[key] = val |
| 8249 |
|
| 8250 |
if "ImageJ" not in result: |
| 8251 |
raise ValueError("not a ImageJ image description") |
| 8252 |
return result |
| 8253 |
|
| 8254 |
|
| 8255 |
def imagej_description( |
| 8256 |
shape, |
| 8257 |
rgb=None, |
| 8258 |
colormaped=False, |
| 8259 |
version="1.11a", |
| 8260 |
hyperstack=None, |
| 8261 |
mode=None, |
| 8262 |
loop=None, |
| 8263 |
**kwargs, |
| 8264 |
): |
| 8265 |
"""Return ImageJ image description from data shape. |
| 8266 |
|
| 8267 |
ImageJ can handle up to 6 dimensions in order TZCYXS. |
| 8268 |
|
| 8269 |
>>> imagej_description((51, 5, 2, 196, 171)) # doctest: +SKIP |
| 8270 |
ImageJ=1.11a |
| 8271 |
images=510 |
| 8272 |
channels=2 |
| 8273 |
slices=5 |
| 8274 |
frames=51 |
| 8275 |
hyperstack=true |
| 8276 |
mode=grayscale |
| 8277 |
loop=false |
| 8278 |
|
| 8279 |
""" |
| 8280 |
if colormaped: |
| 8281 |
raise NotImplementedError("ImageJ colormapping not supported") |
| 8282 |
shape = imagej_shape(shape, rgb=rgb) |
| 8283 |
rgb = shape[-1] in (3, 4) |
| 8284 |
|
| 8285 |
result = ["ImageJ=%s" % version] |
| 8286 |
append = [] |
| 8287 |
result.append("images=%i" % product(shape[:-3])) |
| 8288 |
if hyperstack is None: |
| 8289 |
hyperstack = True |
| 8290 |
append.append("hyperstack=true") |
| 8291 |
else: |
| 8292 |
append.append("hyperstack=%s" % bool(hyperstack)) |
| 8293 |
if shape[2] > 1: |
| 8294 |
result.append("channels=%i" % shape[2]) |
| 8295 |
if mode is None and not rgb: |
| 8296 |
mode = "grayscale" |
| 8297 |
if hyperstack and mode: |
| 8298 |
append.append("mode=%s" % mode) |
| 8299 |
if shape[1] > 1: |
| 8300 |
result.append("slices=%i" % shape[1]) |
| 8301 |
if shape[0] > 1: |
| 8302 |
result.append("frames=%i" % shape[0]) |
| 8303 |
if loop is None: |
| 8304 |
append.append("loop=false") |
| 8305 |
if loop is not None: |
| 8306 |
append.append("loop=%s" % bool(loop)) |
| 8307 |
for key, value in kwargs.items(): |
| 8308 |
append.append("%s=%s" % (key.lower(), value)) |
| 8309 |
|
| 8310 |
return "\n".join(result + append + [""]) |
| 8311 |
|
| 8312 |
|
| 8313 |
def imagej_shape(shape, rgb=None): |
| 8314 |
"""Return shape normalized to 6D ImageJ hyperstack TZCYXS. |
| 8315 |
|
| 8316 |
Raise ValueError if not a valid ImageJ hyperstack shape. |
| 8317 |
|
| 8318 |
>>> imagej_shape((2, 3, 4, 5, 3), False) |
| 8319 |
(2, 3, 4, 5, 3, 1) |
| 8320 |
|
| 8321 |
""" |
| 8322 |
shape = tuple(int(i) for i in shape) |
| 8323 |
ndim = len(shape) |
| 8324 |
if 1 > ndim > 6: |
| 8325 |
raise ValueError("invalid ImageJ hyperstack: not 2 to 6 dimensional") |
| 8326 |
if rgb is None: |
| 8327 |
rgb = shape[-1] in (3, 4) and ndim > 2 |
| 8328 |
if rgb and shape[-1] not in (3, 4): |
| 8329 |
raise ValueError("invalid ImageJ hyperstack: not a RGB image") |
| 8330 |
if not rgb and ndim == 6 and shape[-1] != 1: |
| 8331 |
raise ValueError("invalid ImageJ hyperstack: not a non-RGB image") |
| 8332 |
if rgb or shape[-1] == 1: |
| 8333 |
return (1,) * (6 - ndim) + shape |
| 8334 |
return (1,) * (5 - ndim) + shape + (1,) |
| 8335 |
|
| 8336 |
|
| 8337 |
def json_description(shape, **metadata): |
| 8338 |
"""Return JSON image description from data shape and other meta data. |
| 8339 |
|
| 8340 |
Return UTF-8 encoded JSON. |
| 8341 |
|
| 8342 |
>>> json_description((256, 256, 3), axes='YXS') # doctest: +SKIP |
| 8343 |
b'{"shape": [256, 256, 3], "axes": "YXS"}' |
| 8344 |
|
| 8345 |
""" |
| 8346 |
metadata.update(shape=shape) |
| 8347 |
return json.dumps(metadata) |
| 8348 |
|
| 8349 |
|
| 8350 |
def json_description_metadata(description): |
| 8351 |
"""Return metatata from JSON formatted image description as dict. |
| 8352 |
|
| 8353 |
Raise ValuError if description is of unknown format. |
| 8354 |
|
| 8355 |
>>> description = '{"shape": [256, 256, 3], "axes": "YXS"}' |
| 8356 |
>>> json_description_metadata(description) # doctest: +SKIP |
| 8357 |
{'shape': [256, 256, 3], 'axes': 'YXS'} |
| 8358 |
>>> json_description_metadata('shape=(256, 256, 3)') |
| 8359 |
{'shape': (256, 256, 3)} |
| 8360 |
|
| 8361 |
""" |
| 8362 |
if description[:6] == "shape=": |
| 8363 |
|
| 8364 |
shape = tuple(int(i) for i in description[7:-1].split(",")) |
| 8365 |
return dict(shape=shape) |
| 8366 |
if description[:1] == "{" and description[-1:] == "}": |
| 8367 |
|
| 8368 |
return json.loads(description) |
| 8369 |
raise ValueError("invalid JSON image description", description) |
| 8370 |
|
| 8371 |
|
| 8372 |
def fluoview_description_metadata(description, ignoresections=None): |
| 8373 |
"""Return metatata from FluoView image description as dict. |
| 8374 |
|
| 8375 |
The FluoView image description format is unspecified. Expect failures. |
| 8376 |
|
| 8377 |
>>> descr = ('[Intensity Mapping]\\nMap Ch0: Range=00000 to 02047\\n' |
| 8378 |
... '[Intensity Mapping End]') |
| 8379 |
>>> fluoview_description_metadata(descr) |
| 8380 |
{'Intensity Mapping': {'Map Ch0: Range': '00000 to 02047'}} |
| 8381 |
|
| 8382 |
""" |
| 8383 |
if not description.startswith("["): |
| 8384 |
raise ValueError("invalid FluoView image description") |
| 8385 |
if ignoresections is None: |
| 8386 |
ignoresections = {"Region Info (Fields)", "Protocol Description"} |
| 8387 |
|
| 8388 |
result = {} |
| 8389 |
sections = [result] |
| 8390 |
comment = False |
| 8391 |
for line in description.splitlines(): |
| 8392 |
if not comment: |
| 8393 |
line = line.strip() |
| 8394 |
if not line: |
| 8395 |
continue |
| 8396 |
if line[0] == "[": |
| 8397 |
if line[-5:] == " End]": |
| 8398 |
|
| 8399 |
del sections[-1] |
| 8400 |
section = sections[-1] |
| 8401 |
name = line[1:-5] |
| 8402 |
if comment: |
| 8403 |
section[name] = "\n".join(section[name]) |
| 8404 |
if name[:4] == "LUT ": |
| 8405 |
a = numpy.array(section[name], dtype="uint8") |
| 8406 |
a.shape = -1, 3 |
| 8407 |
section[name] = a |
| 8408 |
continue |
| 8409 |
|
| 8410 |
comment = False |
| 8411 |
name = line[1:-1] |
| 8412 |
if name[:4] == "LUT ": |
| 8413 |
section = [] |
| 8414 |
elif name in ignoresections: |
| 8415 |
section = [] |
| 8416 |
comment = True |
| 8417 |
else: |
| 8418 |
section = {} |
| 8419 |
sections.append(section) |
| 8420 |
result[name] = section |
| 8421 |
continue |
| 8422 |
|
| 8423 |
if comment: |
| 8424 |
section.append(line) |
| 8425 |
continue |
| 8426 |
line = line.split("=", 1) |
| 8427 |
if len(line) == 1: |
| 8428 |
section[line[0].strip()] = None |
| 8429 |
continue |
| 8430 |
key, value = line |
| 8431 |
if key[:4] == "RGB ": |
| 8432 |
section.extend(int(rgb) for rgb in value.split()) |
| 8433 |
else: |
| 8434 |
section[key.strip()] = astype(value.strip()) |
| 8435 |
return result |
| 8436 |
|
| 8437 |
|
| 8438 |
def pilatus_description_metadata(description): |
| 8439 |
"""Return metatata from Pilatus image description as dict. |
| 8440 |
|
| 8441 |
Return metadata from Pilatus pixel array detectors by Dectris, created |
| 8442 |
by camserver or TVX software. |
| 8443 |
|
| 8444 |
>>> pilatus_description_metadata('# Pixel_size 172e-6 m x 172e-6 m') |
| 8445 |
{'Pixel_size': (0.000172, 0.000172)} |
| 8446 |
|
| 8447 |
""" |
| 8448 |
result = {} |
| 8449 |
if not description.startswith("# "): |
| 8450 |
return result |
| 8451 |
for c in "#:=,()": |
| 8452 |
description = description.replace(c, " ") |
| 8453 |
for line in description.split("\n"): |
| 8454 |
if line[:2] != " ": |
| 8455 |
continue |
| 8456 |
line = line.split() |
| 8457 |
name = line[0] |
| 8458 |
if line[0] not in TIFF.PILATUS_HEADER: |
| 8459 |
try: |
| 8460 |
result["DateTime"] = datetime.datetime.strptime( |
| 8461 |
" ".join(line), "%Y-%m-%dT%H %M %S.%f" |
| 8462 |
) |
| 8463 |
except Exception: |
| 8464 |
result[name] = " ".join(line[1:]) |
| 8465 |
continue |
| 8466 |
indices, dtype = TIFF.PILATUS_HEADER[line[0]] |
| 8467 |
if isinstance(indices[0], slice): |
| 8468 |
|
| 8469 |
values = line[indices[0]] |
| 8470 |
else: |
| 8471 |
values = [line[i] for i in indices] |
| 8472 |
if dtype is float and values[0] == "not": |
| 8473 |
values = ["NaN"] |
| 8474 |
values = tuple(dtype(v) for v in values) |
| 8475 |
if dtype == str: |
| 8476 |
values = " ".join(values) |
| 8477 |
elif len(values) == 1: |
| 8478 |
values = values[0] |
| 8479 |
result[name] = values |
| 8480 |
return result |
| 8481 |
|
| 8482 |
|
| 8483 |
def svs_description_metadata(description): |
| 8484 |
"""Return metatata from Aperio image description as dict. |
| 8485 |
|
| 8486 |
The Aperio image description format is unspecified. Expect failures. |
| 8487 |
|
| 8488 |
>>> svs_description_metadata('Aperio Image Library v1.0') |
| 8489 |
{'Aperio Image Library': 'v1.0'} |
| 8490 |
|
| 8491 |
""" |
| 8492 |
if not description.startswith("Aperio Image Library "): |
| 8493 |
raise ValueError("invalid Aperio image description") |
| 8494 |
result = {} |
| 8495 |
lines = description.split("\n") |
| 8496 |
key, value = lines[0].strip().rsplit(None, 1) |
| 8497 |
result[key.strip()] = value.strip() |
| 8498 |
if len(lines) == 1: |
| 8499 |
return result |
| 8500 |
items = lines[1].split("|") |
| 8501 |
result[""] = items[0].strip() |
| 8502 |
for item in items[1:]: |
| 8503 |
key, value = item.split(" = ") |
| 8504 |
result[key.strip()] = astype(value.strip()) |
| 8505 |
return result |
| 8506 |
|
| 8507 |
|
| 8508 |
def stk_description_metadata(description): |
| 8509 |
"""Return metadata from MetaMorph image description as list of dict. |
| 8510 |
|
| 8511 |
The MetaMorph image description format is unspecified. Expect failures. |
| 8512 |
|
| 8513 |
""" |
| 8514 |
description = description.strip() |
| 8515 |
if not description: |
| 8516 |
return [] |
| 8517 |
try: |
| 8518 |
description = bytes2str(description) |
| 8519 |
except UnicodeDecodeError: |
| 8520 |
warnings.warn("failed to parse MetaMorph image description") |
| 8521 |
return [] |
| 8522 |
result = [] |
| 8523 |
for plane in description.split("\x00"): |
| 8524 |
d = {} |
| 8525 |
for line in plane.split("\r\n"): |
| 8526 |
line = line.split(":", 1) |
| 8527 |
if len(line) > 1: |
| 8528 |
name, value = line |
| 8529 |
d[name.strip()] = astype(value.strip()) |
| 8530 |
else: |
| 8531 |
value = line[0].strip() |
| 8532 |
if value: |
| 8533 |
if "" in d: |
| 8534 |
d[""].append(value) |
| 8535 |
else: |
| 8536 |
d[""] = [value] |
| 8537 |
result.append(d) |
| 8538 |
return result |
| 8539 |
|
| 8540 |
|
| 8541 |
def metaseries_description_metadata(description): |
| 8542 |
"""Return metatata from MetaSeries image description as dict.""" |
| 8543 |
if not description.startswith("<MetaData>"): |
| 8544 |
raise ValueError("invalid MetaSeries image description") |
| 8545 |
|
| 8546 |
from xml.etree import cElementTree as etree |
| 8547 |
|
| 8548 |
root = etree.fromstring(description) |
| 8549 |
types = {"float": float, "int": int, "bool": lambda x: asbool(x, "on", "off")} |
| 8550 |
|
| 8551 |
def parse(root, result): |
| 8552 |
|
| 8553 |
for child in root: |
| 8554 |
attrib = child.attrib |
| 8555 |
if not attrib: |
| 8556 |
result[child.tag] = parse(child, {}) |
| 8557 |
continue |
| 8558 |
if "id" in attrib: |
| 8559 |
i = attrib["id"] |
| 8560 |
t = attrib["type"] |
| 8561 |
v = attrib["value"] |
| 8562 |
if t in types: |
| 8563 |
result[i] = types[t](v) |
| 8564 |
else: |
| 8565 |
result[i] = v |
| 8566 |
return result |
| 8567 |
|
| 8568 |
adict = parse(root, {}) |
| 8569 |
if "Description" in adict: |
| 8570 |
adict["Description"] = adict["Description"].replace(" ", "\n") |
| 8571 |
return adict |
| 8572 |
|
| 8573 |
|
| 8574 |
def scanimage_description_metadata(description): |
| 8575 |
"""Return metatata from ScanImage image description as dict.""" |
| 8576 |
return matlabstr2py(description) |
| 8577 |
|
| 8578 |
|
| 8579 |
def scanimage_artist_metadata(artist): |
| 8580 |
"""Return metatata from ScanImage artist tag as dict.""" |
| 8581 |
try: |
| 8582 |
return json.loads(artist) |
| 8583 |
except ValueError: |
| 8584 |
warnings.warn("invalid JSON '%s'" % artist) |
| 8585 |
|
| 8586 |
|
| 8587 |
def _replace_by(module_function, package=__package__, warn=None, prefix="_"): |
| 8588 |
"""Try replace decorated function by module.function.""" |
| 8589 |
return lambda f: f |
| 8590 |
|
| 8591 |
def _warn(e, warn): |
| 8592 |
if warn is None: |
| 8593 |
warn = "\n Functionality might be degraded or be slow.\n" |
| 8594 |
elif warn is True: |
| 8595 |
warn = "" |
| 8596 |
elif not warn: |
| 8597 |
return |
| 8598 |
warnings.warn("%s%s" % (e, warn)) |
| 8599 |
|
| 8600 |
try: |
| 8601 |
from importlib import import_module |
| 8602 |
except ImportError as e: |
| 8603 |
_warn(e, warn) |
| 8604 |
return identityfunc |
| 8605 |
|
| 8606 |
def decorate(func, module_function=module_function, warn=warn): |
| 8607 |
module, function = module_function.split(".") |
| 8608 |
try: |
| 8609 |
if package: |
| 8610 |
module = import_module("." + module, package=package) |
| 8611 |
else: |
| 8612 |
module = import_module(module) |
| 8613 |
except Exception as e: |
| 8614 |
_warn(e, warn) |
| 8615 |
return func |
| 8616 |
try: |
| 8617 |
func, oldfunc = getattr(module, function), func |
| 8618 |
except Exception as e: |
| 8619 |
_warn(e, warn) |
| 8620 |
return func |
| 8621 |
globals()[prefix + func.__name__] = oldfunc |
| 8622 |
return func |
| 8623 |
|
| 8624 |
return decorate |
| 8625 |
|
| 8626 |
|
| 8627 |
def decode_floats(data): |
| 8628 |
"""Decode floating point horizontal differencing. |
| 8629 |
|
| 8630 |
The TIFF predictor type 3 reorders the bytes of the image values and |
| 8631 |
applies horizontal byte differencing to improve compression of floating |
| 8632 |
point images. The ordering of interleaved color channels is preserved. |
| 8633 |
|
| 8634 |
Parameters |
| 8635 |
---------- |
| 8636 |
data : numpy.ndarray |
| 8637 |
The image to be decoded. The dtype must be a floating point. |
| 8638 |
The shape must include the number of contiguous samples per pixel |
| 8639 |
even if 1. |
| 8640 |
|
| 8641 |
""" |
| 8642 |
shape = data.shape |
| 8643 |
dtype = data.dtype |
| 8644 |
if len(shape) < 3: |
| 8645 |
raise ValueError("invalid data shape") |
| 8646 |
if dtype.char not in "dfe": |
| 8647 |
raise ValueError("not a floating point image") |
| 8648 |
littleendian = data.dtype.byteorder == "<" or ( |
| 8649 |
sys.byteorder == "little" and data.dtype.byteorder == "=" |
| 8650 |
) |
| 8651 |
|
| 8652 |
data = data.view("uint8") |
| 8653 |
data.shape = shape[:-2] + (-1,) + shape[-1:] |
| 8654 |
numpy.cumsum(data, axis=-2, dtype="uint8", out=data) |
| 8655 |
|
| 8656 |
if littleendian: |
| 8657 |
data.shape = shape[:-2] + (-1,) + shape[-2:] |
| 8658 |
data = numpy.swapaxes(data, -3, -2) |
| 8659 |
data = numpy.swapaxes(data, -2, -1) |
| 8660 |
data = data[..., ::-1] |
| 8661 |
|
| 8662 |
data = numpy.ascontiguousarray(data) |
| 8663 |
data = data.view(dtype) |
| 8664 |
data.shape = shape |
| 8665 |
return data |
| 8666 |
|
| 8667 |
|
| 8668 |
@_replace_by("_tifffile.decode_packbits") |
| 8669 |
def decode_packbits(encoded): |
| 8670 |
"""Decompress PackBits encoded byte string. |
| 8671 |
|
| 8672 |
PackBits is a simple byte-oriented run-length compression scheme. |
| 8673 |
|
| 8674 |
""" |
| 8675 |
func = ord if sys.version[0] == "2" else identityfunc |
| 8676 |
result = [] |
| 8677 |
result_extend = result.extend |
| 8678 |
i = 0 |
| 8679 |
try: |
| 8680 |
while True: |
| 8681 |
n = func(encoded[i]) + 1 |
| 8682 |
i += 1 |
| 8683 |
if n < 129: |
| 8684 |
result_extend(encoded[i : i + n]) |
| 8685 |
i += n |
| 8686 |
elif n > 129: |
| 8687 |
result_extend(encoded[i : i + 1] * (258 - n)) |
| 8688 |
i += 1 |
| 8689 |
except IndexError: |
| 8690 |
pass |
| 8691 |
return b"".join(result) if sys.version[0] == "2" else bytes(result) |
| 8692 |
|
| 8693 |
|
| 8694 |
@_replace_by("_tifffile.decode_lzw") |
| 8695 |
def decode_lzw(encoded): |
| 8696 |
"""Decompress LZW (Lempel-Ziv-Welch) encoded TIFF strip (byte string). |
| 8697 |
|
| 8698 |
The strip must begin with a CLEAR code and end with an EOI code. |
| 8699 |
|
| 8700 |
This implementation of the LZW decoding algorithm is described in (1) and |
| 8701 |
is not compatible with old style LZW compressed files like quad-lzw.tif. |
| 8702 |
|
| 8703 |
""" |
| 8704 |
len_encoded = len(encoded) |
| 8705 |
bitcount_max = len_encoded * 8 |
| 8706 |
unpack = struct.unpack |
| 8707 |
|
| 8708 |
if sys.version[0] == "2": |
| 8709 |
newtable = [chr(i) for i in range(256)] |
| 8710 |
else: |
| 8711 |
newtable = [bytes([i]) for i in range(256)] |
| 8712 |
newtable.extend((0, 0)) |
| 8713 |
|
| 8714 |
def next_code(): |
| 8715 |
"""Return integer of 'bitw' bits at 'bitcount' position in encoded.""" |
| 8716 |
start = bitcount // 8 |
| 8717 |
s = encoded[start : start + 4] |
| 8718 |
try: |
| 8719 |
code = unpack(">I", s)[0] |
| 8720 |
except Exception: |
| 8721 |
code = unpack(">I", s + b"\x00" * (4 - len(s)))[0] |
| 8722 |
code <<= bitcount % 8 |
| 8723 |
code &= mask |
| 8724 |
return code >> shr |
| 8725 |
|
| 8726 |
switchbitch = { |
| 8727 |
255: (9, 23, int(9 * "1" + "0" * 23, 2)), |
| 8728 |
511: (10, 22, int(10 * "1" + "0" * 22, 2)), |
| 8729 |
1023: (11, 21, int(11 * "1" + "0" * 21, 2)), |
| 8730 |
2047: (12, 20, int(12 * "1" + "0" * 20, 2)), |
| 8731 |
} |
| 8732 |
bitw, shr, mask = switchbitch[255] |
| 8733 |
bitcount = 0 |
| 8734 |
|
| 8735 |
if len_encoded < 4: |
| 8736 |
raise ValueError("strip must be at least 4 characters long") |
| 8737 |
|
| 8738 |
if next_code() != 256: |
| 8739 |
raise ValueError("strip must begin with CLEAR code") |
| 8740 |
|
| 8741 |
code = 0 |
| 8742 |
oldcode = 0 |
| 8743 |
result = [] |
| 8744 |
result_append = result.append |
| 8745 |
while True: |
| 8746 |
code = next_code() |
| 8747 |
bitcount += bitw |
| 8748 |
if code == 257 or bitcount >= bitcount_max: |
| 8749 |
break |
| 8750 |
if code == 256: |
| 8751 |
table = newtable[:] |
| 8752 |
table_append = table.append |
| 8753 |
lentable = 258 |
| 8754 |
bitw, shr, mask = switchbitch[255] |
| 8755 |
code = next_code() |
| 8756 |
bitcount += bitw |
| 8757 |
if code == 257: |
| 8758 |
break |
| 8759 |
result_append(table[code]) |
| 8760 |
else: |
| 8761 |
if code < lentable: |
| 8762 |
decoded = table[code] |
| 8763 |
newcode = table[oldcode] + decoded[:1] |
| 8764 |
else: |
| 8765 |
newcode = table[oldcode] |
| 8766 |
newcode += newcode[:1] |
| 8767 |
decoded = newcode |
| 8768 |
result_append(decoded) |
| 8769 |
table_append(newcode) |
| 8770 |
lentable += 1 |
| 8771 |
oldcode = code |
| 8772 |
if lentable in switchbitch: |
| 8773 |
bitw, shr, mask = switchbitch[lentable] |
| 8774 |
|
| 8775 |
if code != 257: |
| 8776 |
warnings.warn("unexpected end of LZW stream (code %i)" % code) |
| 8777 |
|
| 8778 |
return b"".join(result) |
| 8779 |
|
| 8780 |
|
| 8781 |
@_replace_by("_tifffile.unpack_ints") |
| 8782 |
def unpack_ints(data, dtype, itemsize, runlen=0): |
| 8783 |
"""Decompress byte string to array of integers of any bit size <= 32. |
| 8784 |
|
| 8785 |
This Python implementation is slow and only handles itemsizes 1, 2, 4, 8, |
| 8786 |
16, 32, and 64. |
| 8787 |
|
| 8788 |
Parameters |
| 8789 |
---------- |
| 8790 |
data : byte str |
| 8791 |
Data to decompress. |
| 8792 |
dtype : numpy.dtype or str |
| 8793 |
A numpy boolean or integer type. |
| 8794 |
itemsize : int |
| 8795 |
Number of bits per integer. |
| 8796 |
runlen : int |
| 8797 |
Number of consecutive integers, after which to start at next byte. |
| 8798 |
|
| 8799 |
Examples |
| 8800 |
-------- |
| 8801 |
>>> unpack_ints(b'a', 'B', 1) |
| 8802 |
array([0, 1, 1, 0, 0, 0, 0, 1], dtype=uint8) |
| 8803 |
>>> unpack_ints(b'ab', 'B', 2) |
| 8804 |
array([1, 2, 0, 1, 1, 2, 0, 2], dtype=uint8) |
| 8805 |
|
| 8806 |
""" |
| 8807 |
if itemsize == 1: |
| 8808 |
data = numpy.frombuffer(data, "|B") |
| 8809 |
data = numpy.unpackbits(data) |
| 8810 |
if runlen % 8: |
| 8811 |
data = data.reshape(-1, runlen + (8 - runlen % 8)) |
| 8812 |
data = data[:, :runlen].reshape(-1) |
| 8813 |
return data.astype(dtype) |
| 8814 |
|
| 8815 |
dtype = numpy.dtype(dtype) |
| 8816 |
if itemsize in (8, 16, 32, 64): |
| 8817 |
return numpy.frombuffer(data, dtype) |
| 8818 |
if itemsize not in (1, 2, 4, 8, 16, 32): |
| 8819 |
raise ValueError("itemsize not supported: %i" % itemsize) |
| 8820 |
if dtype.kind not in "biu": |
| 8821 |
raise ValueError("invalid dtype") |
| 8822 |
|
| 8823 |
itembytes = next(i for i in (1, 2, 4, 8) if 8 * i >= itemsize) |
| 8824 |
if itembytes != dtype.itemsize: |
| 8825 |
raise ValueError("dtype.itemsize too small") |
| 8826 |
if runlen == 0: |
| 8827 |
runlen = (8 * len(data)) // itemsize |
| 8828 |
skipbits = runlen * itemsize % 8 |
| 8829 |
if skipbits: |
| 8830 |
skipbits = 8 - skipbits |
| 8831 |
shrbits = itembytes * 8 - itemsize |
| 8832 |
bitmask = int(itemsize * "1" + "0" * shrbits, 2) |
| 8833 |
dtypestr = ">" + dtype.char |
| 8834 |
|
| 8835 |
unpack = struct.unpack |
| 8836 |
size = runlen * (len(data) * 8 // (runlen * itemsize + skipbits)) |
| 8837 |
result = numpy.empty((size,), dtype) |
| 8838 |
bitcount = 0 |
| 8839 |
for i in range(size): |
| 8840 |
start = bitcount // 8 |
| 8841 |
s = data[start : start + itembytes] |
| 8842 |
try: |
| 8843 |
code = unpack(dtypestr, s)[0] |
| 8844 |
except Exception: |
| 8845 |
code = unpack(dtypestr, s + b"\x00" * (itembytes - len(s)))[0] |
| 8846 |
code <<= bitcount % 8 |
| 8847 |
code &= bitmask |
| 8848 |
result[i] = code >> shrbits |
| 8849 |
bitcount += itemsize |
| 8850 |
if (i + 1) % runlen == 0: |
| 8851 |
bitcount += skipbits |
| 8852 |
return result |
| 8853 |
|
| 8854 |
|
| 8855 |
def unpack_rgb(data, dtype="<B", bitspersample=(5, 6, 5), rescale=True): |
| 8856 |
"""Return array from byte string containing packed samples. |
| 8857 |
|
| 8858 |
Use to unpack RGB565 or RGB555 to RGB888 format. |
| 8859 |
|
| 8860 |
Parameters |
| 8861 |
---------- |
| 8862 |
data : byte str |
| 8863 |
The data to be decoded. Samples in each pixel are stored consecutively. |
| 8864 |
Pixels are aligned to 8, 16, or 32 bit boundaries. |
| 8865 |
dtype : numpy.dtype |
| 8866 |
The sample data type. The byteorder applies also to the data stream. |
| 8867 |
bitspersample : tuple |
| 8868 |
Number of bits for each sample in a pixel. |
| 8869 |
rescale : bool |
| 8870 |
Upscale samples to the number of bits in dtype. |
| 8871 |
|
| 8872 |
Returns |
| 8873 |
------- |
| 8874 |
result : ndarray |
| 8875 |
Flattened array of unpacked samples of native dtype. |
| 8876 |
|
| 8877 |
Examples |
| 8878 |
-------- |
| 8879 |
>>> data = struct.pack('BBBB', 0x21, 0x08, 0xff, 0xff) |
| 8880 |
>>> print(unpack_rgb(data, '<B', (5, 6, 5), False)) |
| 8881 |
[ 1 1 1 31 63 31] |
| 8882 |
>>> print(unpack_rgb(data, '<B', (5, 6, 5))) |
| 8883 |
[ 8 4 8 255 255 255] |
| 8884 |
>>> print(unpack_rgb(data, '<B', (5, 5, 5))) |
| 8885 |
[ 16 8 8 255 255 255] |
| 8886 |
|
| 8887 |
""" |
| 8888 |
dtype = numpy.dtype(dtype) |
| 8889 |
bits = int(numpy.sum(bitspersample)) |
| 8890 |
if not (bits <= 32 and all(i <= dtype.itemsize * 8 for i in bitspersample)): |
| 8891 |
raise ValueError("sample size not supported: %s" % str(bitspersample)) |
| 8892 |
dt = next(i for i in "BHI" if numpy.dtype(i).itemsize * 8 >= bits) |
| 8893 |
data = numpy.frombuffer(data, dtype.byteorder + dt) |
| 8894 |
result = numpy.empty((data.size, len(bitspersample)), dtype.char) |
| 8895 |
for i, bps in enumerate(bitspersample): |
| 8896 |
t = data >> int(numpy.sum(bitspersample[i + 1 :])) |
| 8897 |
t &= int("0b" + "1" * bps, 2) |
| 8898 |
if rescale: |
| 8899 |
o = ((dtype.itemsize * 8) // bps + 1) * bps |
| 8900 |
if o > data.dtype.itemsize * 8: |
| 8901 |
t = t.astype("I") |
| 8902 |
t *= (2**o - 1) // (2**bps - 1) |
| 8903 |
t //= 2 ** (o - (dtype.itemsize * 8)) |
| 8904 |
result[:, i] = t |
| 8905 |
return result.reshape(-1) |
| 8906 |
|
| 8907 |
|
| 8908 |
@_replace_by("_tifffile.reverse_bitorder") |
| 8909 |
def reverse_bitorder(data): |
| 8910 |
"""Reverse bits in each byte of byte string or numpy array. |
| 8911 |
|
| 8912 |
Decode data where pixels with lower column values are stored in the |
| 8913 |
lower-order bits of the bytes (FillOrder is LSB2MSB). |
| 8914 |
|
| 8915 |
Parameters |
| 8916 |
---------- |
| 8917 |
data : byte string or ndarray |
| 8918 |
The data to be bit reversed. If byte string, a new bit-reversed byte |
| 8919 |
string is returned. Numpy arrays are bit-reversed in-place. |
| 8920 |
|
| 8921 |
Examples |
| 8922 |
-------- |
| 8923 |
>>> reverse_bitorder(b'\\x01\\x64') |
| 8924 |
b'\\x80&' |
| 8925 |
>>> data = numpy.array([1, 666], dtype='uint16') |
| 8926 |
>>> reverse_bitorder(data) |
| 8927 |
>>> data |
| 8928 |
array([ 128, 16473], dtype=uint16) |
| 8929 |
|
| 8930 |
""" |
| 8931 |
try: |
| 8932 |
view = data.view("uint8") |
| 8933 |
numpy.take(TIFF.REVERSE_BITORDER_ARRAY, view, out=view) |
| 8934 |
except AttributeError: |
| 8935 |
return data.translate(TIFF.REVERSE_BITORDER_BYTES) |
| 8936 |
except ValueError: |
| 8937 |
raise NotImplementedError("slices of arrays not supported") |
| 8938 |
|
| 8939 |
|
| 8940 |
def apply_colormap(image, colormap, contig=True): |
| 8941 |
"""Return palette-colored image. |
| 8942 |
|
| 8943 |
The image values are used to index the colormap on axis 1. The returned |
| 8944 |
image is of shape image.shape+colormap.shape[0] and dtype colormap.dtype. |
| 8945 |
|
| 8946 |
Parameters |
| 8947 |
---------- |
| 8948 |
image : numpy.ndarray |
| 8949 |
Indexes into the colormap. |
| 8950 |
colormap : numpy.ndarray |
| 8951 |
RGB lookup table aka palette of shape (3, 2**bits_per_sample). |
| 8952 |
contig : bool |
| 8953 |
If True, return a contiguous array. |
| 8954 |
|
| 8955 |
Examples |
| 8956 |
-------- |
| 8957 |
>>> image = numpy.arange(256, dtype='uint8') |
| 8958 |
>>> colormap = numpy.vstack([image, image, image]).astype('uint16') * 256 |
| 8959 |
>>> apply_colormap(image, colormap)[-1] |
| 8960 |
array([65280, 65280, 65280], dtype=uint16) |
| 8961 |
|
| 8962 |
""" |
| 8963 |
image = numpy.take(colormap, image, axis=1) |
| 8964 |
image = numpy.rollaxis(image, 0, image.ndim) |
| 8965 |
if contig: |
| 8966 |
image = numpy.ascontiguousarray(image) |
| 8967 |
return image |
| 8968 |
|
| 8969 |
|
| 8970 |
def reorient(image, orientation): |
| 8971 |
"""Return reoriented view of image array. |
| 8972 |
|
| 8973 |
Parameters |
| 8974 |
---------- |
| 8975 |
image : numpy.ndarray |
| 8976 |
Non-squeezed output of asarray() functions. |
| 8977 |
Axes -3 and -2 must be image length and width respectively. |
| 8978 |
orientation : int or str |
| 8979 |
One of TIFF.ORIENTATION names or values. |
| 8980 |
|
| 8981 |
""" |
| 8982 |
ORIENTATION = TIFF.ORIENTATION |
| 8983 |
orientation = enumarg(ORIENTATION, orientation) |
| 8984 |
|
| 8985 |
if orientation == ORIENTATION.TOPLEFT: |
| 8986 |
return image |
| 8987 |
elif orientation == ORIENTATION.TOPRIGHT: |
| 8988 |
return image[..., ::-1, :] |
| 8989 |
elif orientation == ORIENTATION.BOTLEFT: |
| 8990 |
return image[..., ::-1, :, :] |
| 8991 |
elif orientation == ORIENTATION.BOTRIGHT: |
| 8992 |
return image[..., ::-1, ::-1, :] |
| 8993 |
elif orientation == ORIENTATION.LEFTTOP: |
| 8994 |
return numpy.swapaxes(image, -3, -2) |
| 8995 |
elif orientation == ORIENTATION.RIGHTTOP: |
| 8996 |
return numpy.swapaxes(image, -3, -2)[..., ::-1, :] |
| 8997 |
elif orientation == ORIENTATION.RIGHTBOT: |
| 8998 |
return numpy.swapaxes(image, -3, -2)[..., ::-1, :, :] |
| 8999 |
elif orientation == ORIENTATION.LEFTBOT: |
| 9000 |
return numpy.swapaxes(image, -3, -2)[..., ::-1, ::-1, :] |
| 9001 |
|
| 9002 |
|
| 9003 |
def repeat_nd(a, repeats): |
| 9004 |
"""Return read-only view into input array with elements repeated. |
| 9005 |
|
| 9006 |
Zoom nD image by integer factors using nearest neighbor interpolation |
| 9007 |
(box filter). |
| 9008 |
|
| 9009 |
Parameters |
| 9010 |
---------- |
| 9011 |
a : array_like |
| 9012 |
Input array. |
| 9013 |
repeats : sequence of int |
| 9014 |
The number of repetitions to apply along each dimension of input array. |
| 9015 |
|
| 9016 |
Example |
| 9017 |
------- |
| 9018 |
>>> repeat_nd([[1, 2], [3, 4]], (2, 2)) |
| 9019 |
array([[1, 1, 2, 2], |
| 9020 |
[1, 1, 2, 2], |
| 9021 |
[3, 3, 4, 4], |
| 9022 |
[3, 3, 4, 4]]) |
| 9023 |
|
| 9024 |
""" |
| 9025 |
a = numpy.asarray(a) |
| 9026 |
reshape = [] |
| 9027 |
shape = [] |
| 9028 |
strides = [] |
| 9029 |
for i, j, k in zip(a.strides, a.shape, repeats): |
| 9030 |
shape.extend((j, k)) |
| 9031 |
strides.extend((i, 0)) |
| 9032 |
reshape.append(j * k) |
| 9033 |
return numpy.lib.stride_tricks.as_strided( |
| 9034 |
a, shape, strides, writeable=False |
| 9035 |
).reshape(reshape) |
| 9036 |
|
| 9037 |
|
| 9038 |
def reshape_nd(data_or_shape, ndim): |
| 9039 |
"""Return image array or shape with at least ndim dimensions. |
| 9040 |
|
| 9041 |
Prepend 1s to image shape as necessary. |
| 9042 |
|
| 9043 |
>>> reshape_nd(numpy.empty(0), 1).shape |
| 9044 |
(0,) |
| 9045 |
>>> reshape_nd(numpy.empty(1), 2).shape |
| 9046 |
(1, 1) |
| 9047 |
>>> reshape_nd(numpy.empty((2, 3)), 3).shape |
| 9048 |
(1, 2, 3) |
| 9049 |
>>> reshape_nd(numpy.empty((3, 4, 5)), 3).shape |
| 9050 |
(3, 4, 5) |
| 9051 |
>>> reshape_nd((2, 3), 3) |
| 9052 |
(1, 2, 3) |
| 9053 |
|
| 9054 |
""" |
| 9055 |
is_shape = isinstance(data_or_shape, tuple) |
| 9056 |
shape = data_or_shape if is_shape else data_or_shape.shape |
| 9057 |
if len(shape) >= ndim: |
| 9058 |
return data_or_shape |
| 9059 |
shape = (1,) * (ndim - len(shape)) + shape |
| 9060 |
return shape if is_shape else data_or_shape.reshape(shape) |
| 9061 |
|
| 9062 |
|
| 9063 |
def squeeze_axes(shape, axes, skip="XY"): |
| 9064 |
"""Return shape and axes with single-dimensional entries removed. |
| 9065 |
|
| 9066 |
Remove unused dimensions unless their axes are listed in 'skip'. |
| 9067 |
|
| 9068 |
>>> squeeze_axes((5, 1, 2, 1, 1), 'TZYXC') |
| 9069 |
((5, 2, 1), 'TYX') |
| 9070 |
|
| 9071 |
""" |
| 9072 |
if len(shape) != len(axes): |
| 9073 |
raise ValueError("dimensions of axes and shape do not match") |
| 9074 |
shape, axes = zip(*(i for i in zip(shape, axes) if i[0] > 1 or i[1] in skip)) |
| 9075 |
return tuple(shape), "".join(axes) |
| 9076 |
|
| 9077 |
|
| 9078 |
def transpose_axes(image, axes, asaxes="CTZYX"): |
| 9079 |
"""Return image with its axes permuted to match specified axes. |
| 9080 |
|
| 9081 |
A view is returned if possible. |
| 9082 |
|
| 9083 |
>>> transpose_axes(numpy.zeros((2, 3, 4, 5)), 'TYXC', asaxes='CTZYX').shape |
| 9084 |
(5, 2, 1, 3, 4) |
| 9085 |
|
| 9086 |
""" |
| 9087 |
for ax in axes: |
| 9088 |
if ax not in asaxes: |
| 9089 |
raise ValueError("unknown axis %s" % ax) |
| 9090 |
|
| 9091 |
shape = image.shape |
| 9092 |
for ax in reversed(asaxes): |
| 9093 |
if ax not in axes: |
| 9094 |
axes = ax + axes |
| 9095 |
shape = (1,) + shape |
| 9096 |
image = image.reshape(shape) |
| 9097 |
|
| 9098 |
image = image.transpose([axes.index(ax) for ax in asaxes]) |
| 9099 |
return image |
| 9100 |
|
| 9101 |
|
| 9102 |
def reshape_axes(axes, shape, newshape, unknown="Q"): |
| 9103 |
"""Return axes matching new shape. |
| 9104 |
|
| 9105 |
Unknown dimensions are labelled 'Q'. |
| 9106 |
|
| 9107 |
>>> reshape_axes('YXS', (219, 301, 1), (219, 301)) |
| 9108 |
'YX' |
| 9109 |
>>> reshape_axes('IYX', (12, 219, 301), (3, 4, 219, 1, 301, 1)) |
| 9110 |
'QQYQXQ' |
| 9111 |
|
| 9112 |
""" |
| 9113 |
shape = tuple(shape) |
| 9114 |
newshape = tuple(newshape) |
| 9115 |
if len(axes) != len(shape): |
| 9116 |
raise ValueError("axes do not match shape") |
| 9117 |
|
| 9118 |
size = product(shape) |
| 9119 |
newsize = product(newshape) |
| 9120 |
if size != newsize: |
| 9121 |
raise ValueError("cannot reshape %s to %s" % (shape, newshape)) |
| 9122 |
if not axes or not newshape: |
| 9123 |
return "" |
| 9124 |
|
| 9125 |
lendiff = max(0, len(shape) - len(newshape)) |
| 9126 |
if lendiff: |
| 9127 |
newshape = newshape + (1,) * lendiff |
| 9128 |
|
| 9129 |
i = len(shape) - 1 |
| 9130 |
prodns = 1 |
| 9131 |
prods = 1 |
| 9132 |
result = [] |
| 9133 |
for ns in newshape[::-1]: |
| 9134 |
prodns *= ns |
| 9135 |
while i > 0 and shape[i] == 1 and ns != 1: |
| 9136 |
i -= 1 |
| 9137 |
if ns == shape[i] and prodns == prods * shape[i]: |
| 9138 |
prods *= shape[i] |
| 9139 |
result.append(axes[i]) |
| 9140 |
i -= 1 |
| 9141 |
else: |
| 9142 |
result.append(unknown) |
| 9143 |
|
| 9144 |
return "".join(reversed(result[lendiff:])) |
| 9145 |
|
| 9146 |
|
| 9147 |
def stack_pages(pages, out=None, maxworkers=1, *args, **kwargs): |
| 9148 |
"""Read data from sequence of TiffPage and stack them vertically. |
| 9149 |
|
| 9150 |
Additional parameters are passed to the TiffPage.asarray function. |
| 9151 |
|
| 9152 |
""" |
| 9153 |
npages = len(pages) |
| 9154 |
if npages == 0: |
| 9155 |
raise ValueError("no pages") |
| 9156 |
|
| 9157 |
if npages == 1: |
| 9158 |
return pages[0].asarray(out=out, *args, **kwargs) |
| 9159 |
|
| 9160 |
page0 = next(p for p in pages if p is not None) |
| 9161 |
page0.asarray(validate=None) |
| 9162 |
shape = (npages,) + page0.keyframe.shape |
| 9163 |
dtype = page0.keyframe.dtype |
| 9164 |
out = create_output(out, shape, dtype) |
| 9165 |
|
| 9166 |
if maxworkers is None: |
| 9167 |
maxworkers = multiprocessing.cpu_count() // 2 |
| 9168 |
page0.parent.filehandle.lock = maxworkers > 1 |
| 9169 |
|
| 9170 |
filecache = OpenFileCache( |
| 9171 |
size=max(4, maxworkers), lock=page0.parent.filehandle.lock |
| 9172 |
) |
| 9173 |
|
| 9174 |
def func(page, index, out=out, filecache=filecache, args=args, kwargs=kwargs): |
| 9175 |
"""Read, decode, and copy page data.""" |
| 9176 |
if page is not None: |
| 9177 |
filecache.open(page.parent.filehandle) |
| 9178 |
out[index] = page.asarray( |
| 9179 |
lock=filecache.lock, reopen=False, validate=False, *args, **kwargs |
| 9180 |
) |
| 9181 |
filecache.close(page.parent.filehandle) |
| 9182 |
|
| 9183 |
if maxworkers < 2: |
| 9184 |
for i, page in enumerate(pages): |
| 9185 |
func(page, i) |
| 9186 |
else: |
| 9187 |
with concurrent.futures.ThreadPoolExecutor(maxworkers) as executor: |
| 9188 |
executor.map(func, pages, range(npages)) |
| 9189 |
|
| 9190 |
filecache.clear() |
| 9191 |
page0.parent.filehandle.lock = None |
| 9192 |
|
| 9193 |
return out |
| 9194 |
|
| 9195 |
|
| 9196 |
def clean_offsets_counts(offsets, counts): |
| 9197 |
"""Return cleaned offsets and byte counts. |
| 9198 |
|
| 9199 |
Remove zero offsets and counts. Use to sanitize _offsets and _bytecounts |
| 9200 |
tag values for strips or tiles. |
| 9201 |
|
| 9202 |
""" |
| 9203 |
offsets = list(offsets) |
| 9204 |
counts = list(counts) |
| 9205 |
assert len(offsets) == len(counts) |
| 9206 |
j = 0 |
| 9207 |
for i, (o, b) in enumerate(zip(offsets, counts)): |
| 9208 |
if o > 0 and b > 0: |
| 9209 |
if i > j: |
| 9210 |
offsets[j] = o |
| 9211 |
counts[j] = b |
| 9212 |
j += 1 |
| 9213 |
elif b > 0 and o <= 0: |
| 9214 |
raise ValueError("invalid offset") |
| 9215 |
else: |
| 9216 |
warnings.warn("empty byte count") |
| 9217 |
if j == 0: |
| 9218 |
j = 1 |
| 9219 |
return offsets[:j], counts[:j] |
| 9220 |
|
| 9221 |
|
| 9222 |
def buffered_read(fh, lock, offsets, bytecounts, buffersize=2**26): |
| 9223 |
"""Return iterator over blocks read from file.""" |
| 9224 |
length = len(offsets) |
| 9225 |
i = 0 |
| 9226 |
while i < length: |
| 9227 |
data = [] |
| 9228 |
with lock: |
| 9229 |
size = 0 |
| 9230 |
while size < buffersize and i < length: |
| 9231 |
fh.seek(offsets[i]) |
| 9232 |
bytecount = bytecounts[i] |
| 9233 |
data.append(fh.read(bytecount)) |
| 9234 |
size += bytecount |
| 9235 |
i += 1 |
| 9236 |
for block in data: |
| 9237 |
yield block |
| 9238 |
|
| 9239 |
|
| 9240 |
def create_output(out, shape, dtype, mode="w+", suffix=".memmap"): |
| 9241 |
"""Return numpy array where image data of shape and dtype can be copied. |
| 9242 |
|
| 9243 |
The 'out' parameter may have the following values or types: |
| 9244 |
|
| 9245 |
None |
| 9246 |
An empty array of shape and dtype is created and returned. |
| 9247 |
numpy.ndarray |
| 9248 |
An existing writable array of compatible dtype and shape. A view of |
| 9249 |
the same array is returned after verification. |
| 9250 |
'memmap' or 'memmap:tempdir' |
| 9251 |
A memory-map to an array stored in a temporary binary file on disk |
| 9252 |
is created and returned. |
| 9253 |
str or open file |
| 9254 |
The file name or file object used to create a memory-map to an array |
| 9255 |
stored in a binary file on disk. The created memory-mapped array is |
| 9256 |
returned. |
| 9257 |
|
| 9258 |
""" |
| 9259 |
if out is None: |
| 9260 |
return numpy.zeros(shape, dtype) |
| 9261 |
if isinstance(out, str) and out[:6] == "memmap": |
| 9262 |
tempdir = out[7:] if len(out) > 7 else None |
| 9263 |
with tempfile.NamedTemporaryFile(dir=tempdir, suffix=suffix) as fh: |
| 9264 |
return numpy.memmap(fh, shape=shape, dtype=dtype, mode=mode) |
| 9265 |
if isinstance(out, numpy.ndarray): |
| 9266 |
if product(shape) != product(out.shape): |
| 9267 |
raise ValueError("incompatible output shape") |
| 9268 |
if not numpy.can_cast(dtype, out.dtype): |
| 9269 |
raise ValueError("incompatible output dtype") |
| 9270 |
return out.reshape(shape) |
| 9271 |
if isinstance(out, pathlib.Path): |
| 9272 |
out = str(out) |
| 9273 |
return numpy.memmap(out, shape=shape, dtype=dtype, mode=mode) |
| 9274 |
|
| 9275 |
|
| 9276 |
def matlabstr2py(string): |
| 9277 |
"""Return Python object from Matlab string representation. |
| 9278 |
|
| 9279 |
Return str, bool, int, float, list (Matlab arrays or cells), or |
| 9280 |
dict (Matlab structures) types. |
| 9281 |
|
| 9282 |
Use to access ScanImage metadata. |
| 9283 |
|
| 9284 |
>>> matlabstr2py('1') |
| 9285 |
1 |
| 9286 |
>>> matlabstr2py("['x y z' true false; 1 2.0 -3e4; NaN Inf @class]") |
| 9287 |
[['x y z', True, False], [1, 2.0, -30000.0], [nan, inf, '@class']] |
| 9288 |
>>> d = matlabstr2py("SI.hChannels.channelType = {'stripe' 'stripe'}\\n" |
| 9289 |
... "SI.hChannels.channelsActive = 2") |
| 9290 |
>>> d['SI.hChannels.channelType'] |
| 9291 |
['stripe', 'stripe'] |
| 9292 |
|
| 9293 |
""" |
| 9294 |
|
| 9295 |
|
| 9296 |
|
| 9297 |
def lex(s): |
| 9298 |
|
| 9299 |
tokens = ["["] |
| 9300 |
while True: |
| 9301 |
t, i = next_token(s) |
| 9302 |
if t is None: |
| 9303 |
break |
| 9304 |
if t == ";": |
| 9305 |
tokens.extend(("]", "[")) |
| 9306 |
elif t == "[": |
| 9307 |
tokens.extend(("[", "[")) |
| 9308 |
elif t == "]": |
| 9309 |
tokens.extend(("]", "]")) |
| 9310 |
else: |
| 9311 |
tokens.append(t) |
| 9312 |
s = s[i:] |
| 9313 |
tokens.append("]") |
| 9314 |
return tokens |
| 9315 |
|
| 9316 |
def next_token(s): |
| 9317 |
|
| 9318 |
length = len(s) |
| 9319 |
if length == 0: |
| 9320 |
return None, 0 |
| 9321 |
i = 0 |
| 9322 |
while i < length and s[i] == " ": |
| 9323 |
i += 1 |
| 9324 |
if i == length: |
| 9325 |
return None, i |
| 9326 |
if s[i] in "{[;]}": |
| 9327 |
return s[i], i + 1 |
| 9328 |
if s[i] == "'": |
| 9329 |
j = i + 1 |
| 9330 |
while j < length and s[j] != "'": |
| 9331 |
j += 1 |
| 9332 |
return s[i : j + 1], j + 1 |
| 9333 |
if s[i] == "<": |
| 9334 |
j = i + 1 |
| 9335 |
while j < length and s[j] != ">": |
| 9336 |
j += 1 |
| 9337 |
return s[i : j + 1], j + 1 |
| 9338 |
j = i |
| 9339 |
while j < length and s[j] not in " {[;]}": |
| 9340 |
j += 1 |
| 9341 |
return s[i:j], j |
| 9342 |
|
| 9343 |
def value(s, fail=False): |
| 9344 |
|
| 9345 |
s = s.strip() |
| 9346 |
if not s: |
| 9347 |
return s |
| 9348 |
if len(s) == 1: |
| 9349 |
try: |
| 9350 |
return int(s) |
| 9351 |
except Exception: |
| 9352 |
if fail: |
| 9353 |
raise ValueError() |
| 9354 |
return s |
| 9355 |
if s[0] == "'": |
| 9356 |
if fail and s[-1] != "'" or "'" in s[1:-1]: |
| 9357 |
raise ValueError() |
| 9358 |
return s[1:-1] |
| 9359 |
if s[0] == "<": |
| 9360 |
if fail and s[-1] != ">" or "<" in s[1:-1]: |
| 9361 |
raise ValueError() |
| 9362 |
return s |
| 9363 |
if fail and any(i in s for i in " ';[]{}"): |
| 9364 |
raise ValueError() |
| 9365 |
if s[0] == "@": |
| 9366 |
return s |
| 9367 |
if s in ("true", "True"): |
| 9368 |
return True |
| 9369 |
if s in ("false", "False"): |
| 9370 |
return False |
| 9371 |
if s[:6] == "zeros(": |
| 9372 |
return numpy.zeros([int(i) for i in s[6:-1].split(",")]).tolist() |
| 9373 |
if s[:5] == "ones(": |
| 9374 |
return numpy.ones([int(i) for i in s[5:-1].split(",")]).tolist() |
| 9375 |
if "." in s or "e" in s: |
| 9376 |
try: |
| 9377 |
return float(s) |
| 9378 |
except Exception: |
| 9379 |
pass |
| 9380 |
try: |
| 9381 |
return int(s) |
| 9382 |
except Exception: |
| 9383 |
pass |
| 9384 |
try: |
| 9385 |
return float(s) |
| 9386 |
except Exception: |
| 9387 |
if fail: |
| 9388 |
raise ValueError() |
| 9389 |
return s |
| 9390 |
|
| 9391 |
def parse(s): |
| 9392 |
|
| 9393 |
s = s.strip() |
| 9394 |
try: |
| 9395 |
return value(s, fail=True) |
| 9396 |
except ValueError: |
| 9397 |
pass |
| 9398 |
result = add2 = [] |
| 9399 |
levels = [add2] |
| 9400 |
for t in lex(s): |
| 9401 |
if t in "[{": |
| 9402 |
add2 = [] |
| 9403 |
levels.append(add2) |
| 9404 |
elif t in "]}": |
| 9405 |
x = levels.pop() |
| 9406 |
if len(x) == 1 and isinstance(x[0], (list, str)): |
| 9407 |
x = x[0] |
| 9408 |
add2 = levels[-1] |
| 9409 |
add2.append(x) |
| 9410 |
else: |
| 9411 |
add2.append(value(t)) |
| 9412 |
if len(result) == 1 and isinstance(result[0], (list, str)): |
| 9413 |
result = result[0] |
| 9414 |
return result |
| 9415 |
|
| 9416 |
if "\r" in string or "\n" in string: |
| 9417 |
|
| 9418 |
d = {} |
| 9419 |
for line in string.splitlines(): |
| 9420 |
line = line.strip() |
| 9421 |
if not line or line[0] == "%": |
| 9422 |
continue |
| 9423 |
k, v = line.split("=", 1) |
| 9424 |
k = k.strip() |
| 9425 |
if any(c in k for c in " ';[]{}<>"): |
| 9426 |
continue |
| 9427 |
d[k] = parse(v) |
| 9428 |
return d |
| 9429 |
return parse(string) |
| 9430 |
|
| 9431 |
|
| 9432 |
def stripnull(string, null=b"\x00"): |
| 9433 |
"""Return string truncated at first null character. |
| 9434 |
|
| 9435 |
Clean NULL terminated C strings. For unicode strings use null='\\0'. |
| 9436 |
|
| 9437 |
>>> stripnull(b'string\\x00') |
| 9438 |
b'string' |
| 9439 |
>>> stripnull('string\\x00', null='\\0') |
| 9440 |
'string' |
| 9441 |
|
| 9442 |
""" |
| 9443 |
i = string.find(null) |
| 9444 |
return string if (i < 0) else string[:i] |
| 9445 |
|
| 9446 |
|
| 9447 |
def stripascii(string): |
| 9448 |
"""Return string truncated at last byte that is 7-bit ASCII. |
| 9449 |
|
| 9450 |
Clean NULL separated and terminated TIFF strings. |
| 9451 |
|
| 9452 |
>>> stripascii(b'string\\x00string\\n\\x01\\x00') |
| 9453 |
b'string\\x00string\\n' |
| 9454 |
>>> stripascii(b'\\x00') |
| 9455 |
b'' |
| 9456 |
|
| 9457 |
""" |
| 9458 |
|
| 9459 |
i = len(string) |
| 9460 |
while i: |
| 9461 |
i -= 1 |
| 9462 |
if 8 < byte2int(string[i]) < 127: |
| 9463 |
break |
| 9464 |
else: |
| 9465 |
i = -1 |
| 9466 |
return string[: i + 1] |
| 9467 |
|
| 9468 |
|
| 9469 |
def asbool(value, true=(b"true", "true"), false=(b"false", "false")): |
| 9470 |
"""Return string as bool if possible, else raise TypeError. |
| 9471 |
|
| 9472 |
>>> asbool(b' False ') |
| 9473 |
False |
| 9474 |
|
| 9475 |
""" |
| 9476 |
value = value.strip().lower() |
| 9477 |
if value in true: |
| 9478 |
return True |
| 9479 |
if value in false: |
| 9480 |
return False |
| 9481 |
raise TypeError() |
| 9482 |
|
| 9483 |
|
| 9484 |
def astype(value, types=None): |
| 9485 |
"""Return argument as one of types if possible. |
| 9486 |
|
| 9487 |
>>> astype('42') |
| 9488 |
42 |
| 9489 |
>>> astype('3.14') |
| 9490 |
3.14 |
| 9491 |
>>> astype('True') |
| 9492 |
True |
| 9493 |
>>> astype(b'Neee-Wom') |
| 9494 |
'Neee-Wom' |
| 9495 |
|
| 9496 |
""" |
| 9497 |
if types is None: |
| 9498 |
types = int, float, asbool, bytes2str |
| 9499 |
for typ in types: |
| 9500 |
try: |
| 9501 |
return typ(value) |
| 9502 |
except (ValueError, AttributeError, TypeError, UnicodeEncodeError): |
| 9503 |
pass |
| 9504 |
return value |
| 9505 |
|
| 9506 |
|
| 9507 |
def format_size(size, threshold=1536): |
| 9508 |
"""Return file size as string from byte size. |
| 9509 |
|
| 9510 |
>>> format_size(1234) |
| 9511 |
'1234 B' |
| 9512 |
>>> format_size(12345678901) |
| 9513 |
'11.50 GiB' |
| 9514 |
|
| 9515 |
""" |
| 9516 |
if size < threshold: |
| 9517 |
return "%i B" % size |
| 9518 |
for unit in ("KiB", "MiB", "GiB", "TiB", "PiB"): |
| 9519 |
size /= 1024.0 |
| 9520 |
if size < threshold: |
| 9521 |
return "%.2f %s" % (size, unit) |
| 9522 |
|
| 9523 |
|
| 9524 |
def identityfunc(arg): |
| 9525 |
"""Single argument identity function. |
| 9526 |
|
| 9527 |
>>> identityfunc('arg') |
| 9528 |
'arg' |
| 9529 |
|
| 9530 |
""" |
| 9531 |
return arg |
| 9532 |
|
| 9533 |
|
| 9534 |
def nullfunc(*args, **kwargs): |
| 9535 |
"""Null function. |
| 9536 |
|
| 9537 |
>>> nullfunc('arg', kwarg='kwarg') |
| 9538 |
|
| 9539 |
""" |
| 9540 |
return |
| 9541 |
|
| 9542 |
|
| 9543 |
def sequence(value): |
| 9544 |
"""Return tuple containing value if value is not a sequence. |
| 9545 |
|
| 9546 |
>>> sequence(1) |
| 9547 |
(1,) |
| 9548 |
>>> sequence([1]) |
| 9549 |
[1] |
| 9550 |
|
| 9551 |
""" |
| 9552 |
try: |
| 9553 |
len(value) |
| 9554 |
return value |
| 9555 |
except TypeError: |
| 9556 |
return (value,) |
| 9557 |
|
| 9558 |
|
| 9559 |
def product(iterable): |
| 9560 |
"""Return product of sequence of numbers. |
| 9561 |
|
| 9562 |
Equivalent of functools.reduce(operator.mul, iterable, 1). |
| 9563 |
Multiplying numpy integers might overflow. |
| 9564 |
|
| 9565 |
>>> product([2**8, 2**30]) |
| 9566 |
274877906944 |
| 9567 |
>>> product([]) |
| 9568 |
1 |
| 9569 |
|
| 9570 |
""" |
| 9571 |
prod = 1 |
| 9572 |
for i in iterable: |
| 9573 |
prod *= i |
| 9574 |
return prod |
| 9575 |
|
| 9576 |
|
| 9577 |
def natural_sorted(iterable): |
| 9578 |
"""Return human sorted list of strings. |
| 9579 |
|
| 9580 |
E.g. for sorting file names. |
| 9581 |
|
| 9582 |
>>> natural_sorted(['f1', 'f2', 'f10']) |
| 9583 |
['f1', 'f2', 'f10'] |
| 9584 |
|
| 9585 |
""" |
| 9586 |
|
| 9587 |
def sortkey(x): |
| 9588 |
return [(int(c) if c.isdigit() else c) for c in re.split(numbers, x)] |
| 9589 |
|
| 9590 |
numbers = re.compile(r"(\d+)") |
| 9591 |
return sorted(iterable, key=sortkey) |
| 9592 |
|
| 9593 |
|
| 9594 |
def excel_datetime(timestamp, epoch=datetime.datetime.fromordinal(693594)): |
| 9595 |
"""Return datetime object from timestamp in Excel serial format. |
| 9596 |
|
| 9597 |
Convert LSM time stamps. |
| 9598 |
|
| 9599 |
>>> excel_datetime(40237.029999999795) |
| 9600 |
datetime.datetime(2010, 2, 28, 0, 43, 11, 999982) |
| 9601 |
|
| 9602 |
""" |
| 9603 |
return epoch + datetime.timedelta(timestamp) |
| 9604 |
|
| 9605 |
|
| 9606 |
def julian_datetime(julianday, milisecond=0): |
| 9607 |
"""Return datetime from days since 1/1/4713 BC and ms since midnight. |
| 9608 |
|
| 9609 |
Convert Julian dates according to MetaMorph. |
| 9610 |
|
| 9611 |
>>> julian_datetime(2451576, 54362783) |
| 9612 |
datetime.datetime(2000, 2, 2, 15, 6, 2, 783) |
| 9613 |
|
| 9614 |
""" |
| 9615 |
if julianday <= 1721423: |
| 9616 |
|
| 9617 |
return None |
| 9618 |
|
| 9619 |
a = julianday + 1 |
| 9620 |
if a > 2299160: |
| 9621 |
alpha = math.trunc((a - 1867216.25) / 36524.25) |
| 9622 |
a += 1 + alpha - alpha // 4 |
| 9623 |
b = a + (1524 if a > 1721423 else 1158) |
| 9624 |
c = math.trunc((b - 122.1) / 365.25) |
| 9625 |
d = math.trunc(365.25 * c) |
| 9626 |
e = math.trunc((b - d) / 30.6001) |
| 9627 |
|
| 9628 |
day = b - d - math.trunc(30.6001 * e) |
| 9629 |
month = e - (1 if e < 13.5 else 13) |
| 9630 |
year = c - (4716 if month > 2.5 else 4715) |
| 9631 |
|
| 9632 |
hour, milisecond = divmod(milisecond, 1000 * 60 * 60) |
| 9633 |
minute, milisecond = divmod(milisecond, 1000 * 60) |
| 9634 |
second, milisecond = divmod(milisecond, 1000) |
| 9635 |
|
| 9636 |
return datetime.datetime(year, month, day, hour, minute, second, milisecond) |
| 9637 |
|
| 9638 |
|
| 9639 |
def byteorder_isnative(byteorder): |
| 9640 |
"""Return if byteorder matches the system's byteorder. |
| 9641 |
|
| 9642 |
>>> byteorder_isnative('=') |
| 9643 |
True |
| 9644 |
|
| 9645 |
""" |
| 9646 |
if byteorder == "=" or byteorder == sys.byteorder: |
| 9647 |
return True |
| 9648 |
keys = {"big": ">", "little": "<"} |
| 9649 |
return keys.get(byteorder, byteorder) == keys[sys.byteorder] |
| 9650 |
|
| 9651 |
|
| 9652 |
def recarray2dict(recarray): |
| 9653 |
"""Return numpy.recarray as dict.""" |
| 9654 |
|
| 9655 |
result = {} |
| 9656 |
for descr, value in zip(recarray.dtype.descr, recarray): |
| 9657 |
name, dtype = descr[:2] |
| 9658 |
if dtype[1] == "S": |
| 9659 |
value = bytes2str(stripnull(value)) |
| 9660 |
elif value.ndim < 2: |
| 9661 |
value = value.tolist() |
| 9662 |
result[name] = value |
| 9663 |
return result |
| 9664 |
|
| 9665 |
|
| 9666 |
def xml2dict(xml, sanitize=True, prefix=None): |
| 9667 |
"""Return XML as dict. |
| 9668 |
|
| 9669 |
>>> xml2dict('<?xml version="1.0" ?><root attr="name"><key>1</key></root>') |
| 9670 |
{'root': {'key': 1, 'attr': 'name'}} |
| 9671 |
|
| 9672 |
""" |
| 9673 |
from xml.etree import cElementTree as etree |
| 9674 |
|
| 9675 |
at = tx = "" |
| 9676 |
if prefix: |
| 9677 |
at, tx = prefix |
| 9678 |
|
| 9679 |
def astype(value): |
| 9680 |
|
| 9681 |
for t in (int, float, asbool): |
| 9682 |
try: |
| 9683 |
return t(value) |
| 9684 |
except Exception: |
| 9685 |
pass |
| 9686 |
return value |
| 9687 |
|
| 9688 |
def etree2dict(t): |
| 9689 |
|
| 9690 |
key = t.tag |
| 9691 |
if sanitize: |
| 9692 |
key = key.rsplit("}", 1)[-1] |
| 9693 |
d = {key: {} if t.attrib else None} |
| 9694 |
children = list(t) |
| 9695 |
if children: |
| 9696 |
dd = collections.defaultdict(list) |
| 9697 |
for dc in map(etree2dict, children): |
| 9698 |
for k, v in dc.items(): |
| 9699 |
dd[k].append(astype(v)) |
| 9700 |
d = { |
| 9701 |
key: { |
| 9702 |
k: astype(v[0]) if len(v) == 1 else astype(v) for k, v in dd.items() |
| 9703 |
} |
| 9704 |
} |
| 9705 |
if t.attrib: |
| 9706 |
d[key].update((at + k, astype(v)) for k, v in t.attrib.items()) |
| 9707 |
if t.text: |
| 9708 |
text = t.text.strip() |
| 9709 |
if children or t.attrib: |
| 9710 |
if text: |
| 9711 |
d[key][tx + "value"] = astype(text) |
| 9712 |
else: |
| 9713 |
d[key] = astype(text) |
| 9714 |
return d |
| 9715 |
|
| 9716 |
return etree2dict(etree.fromstring(xml)) |
| 9717 |
|
| 9718 |
|
| 9719 |
def hexdump(bytestr, width=75, height=24, snipat=-2, modulo=2, ellipsis="..."): |
| 9720 |
"""Return hexdump representation of byte string. |
| 9721 |
|
| 9722 |
>>> hexdump(binascii.unhexlify('49492a00080000000e00fe0004000100')) |
| 9723 |
'49 49 2a 00 08 00 00 00 0e 00 fe 00 04 00 01 00 II*.............' |
| 9724 |
|
| 9725 |
""" |
| 9726 |
size = len(bytestr) |
| 9727 |
if size < 1 or width < 2 or height < 1: |
| 9728 |
return "" |
| 9729 |
if height == 1: |
| 9730 |
addr = b"" |
| 9731 |
bytesperline = min(modulo * (((width - len(addr)) // 4) // modulo), size) |
| 9732 |
if bytesperline < 1: |
| 9733 |
return "" |
| 9734 |
nlines = 1 |
| 9735 |
else: |
| 9736 |
addr = b"%%0%ix: " % len(b"%x" % size) |
| 9737 |
bytesperline = min(modulo * (((width - len(addr % 1)) // 4) // modulo), size) |
| 9738 |
if bytesperline < 1: |
| 9739 |
return "" |
| 9740 |
width = 3 * bytesperline + len(addr % 1) |
| 9741 |
nlines = (size - 1) // bytesperline + 1 |
| 9742 |
|
| 9743 |
if snipat is None or snipat == 1: |
| 9744 |
snipat = height |
| 9745 |
elif 0 < abs(snipat) < 1: |
| 9746 |
snipat = int(math.floor(height * snipat)) |
| 9747 |
if snipat < 0: |
| 9748 |
snipat += height |
| 9749 |
|
| 9750 |
if height == 1 or nlines == 1: |
| 9751 |
blocks = [(0, bytestr[:bytesperline])] |
| 9752 |
addr = b"" |
| 9753 |
height = 1 |
| 9754 |
width = 3 * bytesperline |
| 9755 |
elif height is None or nlines <= height: |
| 9756 |
blocks = [(0, bytestr)] |
| 9757 |
elif snipat <= 0: |
| 9758 |
start = bytesperline * (nlines - height) |
| 9759 |
blocks = [(start, bytestr[start:])] |
| 9760 |
elif snipat >= height or height < 3: |
| 9761 |
end = bytesperline * height |
| 9762 |
blocks = [(0, bytestr[:end])] |
| 9763 |
else: |
| 9764 |
end1 = bytesperline * snipat |
| 9765 |
end2 = bytesperline * (height - snipat - 1) |
| 9766 |
blocks = [ |
| 9767 |
(0, bytestr[:end1]), |
| 9768 |
(size - end1 - end2, None), |
| 9769 |
(size - end2, bytestr[size - end2 :]), |
| 9770 |
] |
| 9771 |
|
| 9772 |
ellipsis = str2bytes(ellipsis) |
| 9773 |
result = [] |
| 9774 |
for start, bytestr in blocks: |
| 9775 |
if bytestr is None: |
| 9776 |
result.append(ellipsis) |
| 9777 |
continue |
| 9778 |
hexstr = binascii.hexlify(bytestr) |
| 9779 |
strstr = re.sub(rb"[^\x20-\x7f]", b".", bytestr) |
| 9780 |
for i in range(0, len(bytestr), bytesperline): |
| 9781 |
h = hexstr[2 * i : 2 * i + bytesperline * 2] |
| 9782 |
r = (addr % (i + start)) if height > 1 else addr |
| 9783 |
r += b" ".join(h[i : i + 2] for i in range(0, 2 * bytesperline, 2)) |
| 9784 |
r += b" " * (width - len(r)) |
| 9785 |
r += strstr[i : i + bytesperline] |
| 9786 |
result.append(r) |
| 9787 |
result = b"\n".join(result) |
| 9788 |
if sys.version_info[0] == 3: |
| 9789 |
result = result.decode("ascii") |
| 9790 |
return result |
| 9791 |
|
| 9792 |
|
| 9793 |
def isprintable(string): |
| 9794 |
"""Return if all characters in string are printable. |
| 9795 |
|
| 9796 |
>>> isprintable('abc') |
| 9797 |
True |
| 9798 |
>>> isprintable(b'\01') |
| 9799 |
False |
| 9800 |
|
| 9801 |
""" |
| 9802 |
string = string.strip() |
| 9803 |
if len(string) < 1: |
| 9804 |
return True |
| 9805 |
if sys.version_info[0] == 3: |
| 9806 |
try: |
| 9807 |
return string.isprintable() |
| 9808 |
except Exception: |
| 9809 |
pass |
| 9810 |
try: |
| 9811 |
return string.decode("utf-8").isprintable() |
| 9812 |
except Exception: |
| 9813 |
pass |
| 9814 |
else: |
| 9815 |
if string.isalnum(): |
| 9816 |
return True |
| 9817 |
printable = ( |
| 9818 |
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRST" |
| 9819 |
"UVWXYZ!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c" |
| 9820 |
) |
| 9821 |
return all(c in printable for c in string) |
| 9822 |
|
| 9823 |
|
| 9824 |
def clean_whitespace(string, compact=False): |
| 9825 |
"""Return string with compressed whitespace.""" |
| 9826 |
for a, b in ( |
| 9827 |
("\r\n", "\n"), |
| 9828 |
("\r", "\n"), |
| 9829 |
("\n\n", "\n"), |
| 9830 |
("\t", " "), |
| 9831 |
(" ", " "), |
| 9832 |
): |
| 9833 |
string = string.replace(a, b) |
| 9834 |
if compact: |
| 9835 |
for a, b in (("\n", " "), ("[ ", "["), (" ", " "), (" ", " "), (" ", " ")): |
| 9836 |
string = string.replace(a, b) |
| 9837 |
return string.strip() |
| 9838 |
|
| 9839 |
|
| 9840 |
def pformat_xml(xml): |
| 9841 |
"""Return pretty formatted XML.""" |
| 9842 |
try: |
| 9843 |
import lxml.etree as etree |
| 9844 |
|
| 9845 |
if not isinstance(xml, bytes): |
| 9846 |
xml = xml.encode("utf-8") |
| 9847 |
xml = etree.parse(io.BytesIO(xml)) |
| 9848 |
xml = etree.tostring( |
| 9849 |
xml, pretty_print=True, xml_declaration=True, encoding=xml.docinfo.encoding |
| 9850 |
) |
| 9851 |
xml = bytes2str(xml) |
| 9852 |
except Exception: |
| 9853 |
if isinstance(xml, bytes): |
| 9854 |
xml = bytes2str(xml) |
| 9855 |
xml = xml.replace("><", ">\n<") |
| 9856 |
return xml.replace(" ", " ").replace("\t", " ") |
| 9857 |
|
| 9858 |
|
| 9859 |
def pformat(arg, width=79, height=24, compact=True): |
| 9860 |
"""Return pretty formatted representation of object as string. |
| 9861 |
|
| 9862 |
Whitespace might be altered. |
| 9863 |
|
| 9864 |
""" |
| 9865 |
if height is None or height < 1: |
| 9866 |
height = 1024 |
| 9867 |
if width is None or width < 1: |
| 9868 |
width = 256 |
| 9869 |
|
| 9870 |
npopt = numpy.get_printoptions() |
| 9871 |
numpy.set_printoptions(threshold=100, linewidth=width) |
| 9872 |
|
| 9873 |
if isinstance(arg, basestring): |
| 9874 |
if arg[:5].lower() in ("<?xml", b"<?xml"): |
| 9875 |
if height == 1: |
| 9876 |
arg = arg[: 4 * width] |
| 9877 |
else: |
| 9878 |
arg = pformat_xml(arg) |
| 9879 |
elif isinstance(arg, bytes): |
| 9880 |
if isprintable(arg): |
| 9881 |
arg = bytes2str(arg) |
| 9882 |
arg = clean_whitespace(arg) |
| 9883 |
else: |
| 9884 |
numpy.set_printoptions(**npopt) |
| 9885 |
return hexdump(arg, width=width, height=height, modulo=1) |
| 9886 |
arg = arg.rstrip() |
| 9887 |
elif isinstance(arg, numpy.record): |
| 9888 |
arg = arg.pprint() |
| 9889 |
else: |
| 9890 |
import pprint |
| 9891 |
|
| 9892 |
compact = {} if sys.version_info[0] == 2 else dict(compact=compact) |
| 9893 |
arg = pprint.pformat(arg, width=width, **compact) |
| 9894 |
|
| 9895 |
numpy.set_printoptions(**npopt) |
| 9896 |
|
| 9897 |
if height == 1: |
| 9898 |
arg = clean_whitespace(arg, compact=True) |
| 9899 |
return arg[:width] |
| 9900 |
|
| 9901 |
argl = list(arg.splitlines()) |
| 9902 |
if len(argl) > height: |
| 9903 |
arg = "\n".join(argl[: height // 2] + ["..."] + argl[-height // 2 :]) |
| 9904 |
return arg |
| 9905 |
|
| 9906 |
|
| 9907 |
def snipstr(string, width=79, snipat=0.5, ellipsis="..."): |
| 9908 |
"""Return string cut to specified length. |
| 9909 |
|
| 9910 |
>>> snipstr('abcdefghijklmnop', 8) |
| 9911 |
'abc...op' |
| 9912 |
|
| 9913 |
""" |
| 9914 |
if ellipsis is None: |
| 9915 |
if isinstance(string, bytes): |
| 9916 |
ellipsis = b"..." |
| 9917 |
else: |
| 9918 |
ellipsis = "\u2026" |
| 9919 |
esize = len(ellipsis) |
| 9920 |
|
| 9921 |
splitlines = string.splitlines() |
| 9922 |
|
| 9923 |
|
| 9924 |
result = [] |
| 9925 |
for line in splitlines: |
| 9926 |
if line is None: |
| 9927 |
result.append(ellipsis) |
| 9928 |
continue |
| 9929 |
linelen = len(line) |
| 9930 |
if linelen <= width: |
| 9931 |
result.append(string) |
| 9932 |
continue |
| 9933 |
|
| 9934 |
split = snipat |
| 9935 |
if split is None or split == 1: |
| 9936 |
split = linelen |
| 9937 |
elif 0 < abs(split) < 1: |
| 9938 |
split = int(math.floor(linelen * split)) |
| 9939 |
if split < 0: |
| 9940 |
split += linelen |
| 9941 |
if split < 0: |
| 9942 |
split = 0 |
| 9943 |
|
| 9944 |
if esize == 0 or width < esize + 1: |
| 9945 |
if split <= 0: |
| 9946 |
result.append(string[-width:]) |
| 9947 |
else: |
| 9948 |
result.append(string[:width]) |
| 9949 |
elif split <= 0: |
| 9950 |
result.append(ellipsis + string[esize - width :]) |
| 9951 |
elif split >= linelen or width < esize + 4: |
| 9952 |
result.append(string[: width - esize] + ellipsis) |
| 9953 |
else: |
| 9954 |
splitlen = linelen - width + esize |
| 9955 |
end1 = split - splitlen // 2 |
| 9956 |
end2 = end1 + splitlen |
| 9957 |
result.append(string[:end1] + ellipsis + string[end2:]) |
| 9958 |
|
| 9959 |
if isinstance(string, bytes): |
| 9960 |
return b"\n".join(result) |
| 9961 |
else: |
| 9962 |
return "\n".join(result) |
| 9963 |
|
| 9964 |
|
| 9965 |
def enumarg(enum, arg): |
| 9966 |
"""Return enum member from its name or value. |
| 9967 |
|
| 9968 |
>>> enumarg(TIFF.PHOTOMETRIC, 2) |
| 9969 |
<PHOTOMETRIC.RGB: 2> |
| 9970 |
>>> enumarg(TIFF.PHOTOMETRIC, 'RGB') |
| 9971 |
<PHOTOMETRIC.RGB: 2> |
| 9972 |
|
| 9973 |
""" |
| 9974 |
try: |
| 9975 |
return enum(arg) |
| 9976 |
except Exception: |
| 9977 |
try: |
| 9978 |
return enum[arg.upper()] |
| 9979 |
except Exception: |
| 9980 |
raise ValueError("invalid argument %s" % arg) |
| 9981 |
|
| 9982 |
|
| 9983 |
def parse_kwargs(kwargs, *keys, **keyvalues): |
| 9984 |
"""Return dict with keys from keys|keyvals and values from kwargs|keyvals. |
| 9985 |
|
| 9986 |
Existing keys are deleted from kwargs. |
| 9987 |
|
| 9988 |
>>> kwargs = {'one': 1, 'two': 2, 'four': 4} |
| 9989 |
>>> kwargs2 = parse_kwargs(kwargs, 'two', 'three', four=None, five=5) |
| 9990 |
>>> kwargs == {'one': 1} |
| 9991 |
True |
| 9992 |
>>> kwargs2 == {'two': 2, 'four': 4, 'five': 5} |
| 9993 |
True |
| 9994 |
|
| 9995 |
""" |
| 9996 |
result = {} |
| 9997 |
for key in keys: |
| 9998 |
if key in kwargs: |
| 9999 |
result[key] = kwargs[key] |
| 10000 |
del kwargs[key] |
| 10001 |
for key, value in keyvalues.items(): |
| 10002 |
if key in kwargs: |
| 10003 |
result[key] = kwargs[key] |
| 10004 |
del kwargs[key] |
| 10005 |
else: |
| 10006 |
result[key] = value |
| 10007 |
return result |
| 10008 |
|
| 10009 |
|
| 10010 |
def update_kwargs(kwargs, **keyvalues): |
| 10011 |
"""Update dict with keys and values if keys do not already exist. |
| 10012 |
|
| 10013 |
>>> kwargs = {'one': 1, } |
| 10014 |
>>> update_kwargs(kwargs, one=None, two=2) |
| 10015 |
>>> kwargs == {'one': 1, 'two': 2} |
| 10016 |
True |
| 10017 |
|
| 10018 |
""" |
| 10019 |
for key, value in keyvalues.items(): |
| 10020 |
if key not in kwargs: |
| 10021 |
kwargs[key] = value |
| 10022 |
|
| 10023 |
|
| 10024 |
def validate_jhove(filename, jhove="jhove", ignore=("More than 50 IFDs",)): |
| 10025 |
"""Validate TIFF file using jhove -m TIFF-hul. |
| 10026 |
|
| 10027 |
Raise ValueError if jhove outputs an error message unless the message |
| 10028 |
contains one of the strings in 'ignore'. |
| 10029 |
|
| 10030 |
JHOVE does not support bigtiff or more than 50 IFDs. |
| 10031 |
|
| 10032 |
See `JHOVE TIFF-hul Module <http://jhove.sourceforge.net/tiff-hul.html>`_ |
| 10033 |
|
| 10034 |
""" |
| 10035 |
import subprocess |
| 10036 |
|
| 10037 |
out = subprocess.check_output([jhove, filename, "-m", "TIFF-hul"]) |
| 10038 |
if b"ErrorMessage: " in out: |
| 10039 |
for line in out.splitlines(): |
| 10040 |
line = line.strip() |
| 10041 |
if line.startswith(b"ErrorMessage: "): |
| 10042 |
error = line[14:].decode("utf8") |
| 10043 |
for i in ignore: |
| 10044 |
if i in error: |
| 10045 |
break |
| 10046 |
else: |
| 10047 |
raise ValueError(error) |
| 10048 |
break |
| 10049 |
|
| 10050 |
|
| 10051 |
def lsm2bin(lsmfile, binfile=None, tile=(256, 256), verbose=True): |
| 10052 |
"""Convert [MP]TZCYX LSM file to series of BIN files. |
| 10053 |
|
| 10054 |
One BIN file containing 'ZCYX' data are created for each position, time, |
| 10055 |
and tile. The position, time, and tile indices are encoded at the end |
| 10056 |
of the filenames. |
| 10057 |
|
| 10058 |
""" |
| 10059 |
verbose = print_ if verbose else nullfunc |
| 10060 |
|
| 10061 |
if binfile is None: |
| 10062 |
binfile = lsmfile |
| 10063 |
elif binfile.lower() == "none": |
| 10064 |
binfile = None |
| 10065 |
if binfile: |
| 10066 |
binfile += "_(z%ic%iy%ix%i)_m%%ip%%it%%03iy%%ix%%i.bin" |
| 10067 |
|
| 10068 |
verbose("\nOpening LSM file... ", end="", flush=True) |
| 10069 |
start_time = time.time() |
| 10070 |
|
| 10071 |
with TiffFile(lsmfile) as lsm: |
| 10072 |
if not lsm.is_lsm: |
| 10073 |
verbose("\n", lsm, flush=True) |
| 10074 |
raise ValueError("not a LSM file") |
| 10075 |
series = lsm.series[0] |
| 10076 |
shape = series.shape |
| 10077 |
axes = series.axes |
| 10078 |
dtype = series.dtype |
| 10079 |
size = product(shape) * dtype.itemsize |
| 10080 |
|
| 10081 |
verbose("%.3f s" % (time.time() - start_time)) |
| 10082 |
|
| 10083 |
verbose( |
| 10084 |
"Image\n axes: %s\n shape: %s\n dtype: %s\n size: %s" |
| 10085 |
% (axes, shape, dtype, format_size(size)), |
| 10086 |
flush=True, |
| 10087 |
) |
| 10088 |
if not series.axes.endswith("TZCYX"): |
| 10089 |
raise ValueError("not a *TZCYX LSM file") |
| 10090 |
|
| 10091 |
verbose("Copying image from LSM to BIN files", end="", flush=True) |
| 10092 |
start_time = time.time() |
| 10093 |
tiles = shape[-2] // tile[-2], shape[-1] // tile[-1] |
| 10094 |
if binfile: |
| 10095 |
binfile = binfile % (shape[-4], shape[-3], tile[0], tile[1]) |
| 10096 |
shape = (1,) * (7 - len(shape)) + shape |
| 10097 |
|
| 10098 |
data = numpy.empty(shape[3:], dtype=dtype) |
| 10099 |
out = numpy.empty((shape[-4], shape[-3], tile[0], tile[1]), dtype=dtype) |
| 10100 |
|
| 10101 |
pages = iter(series.pages) |
| 10102 |
for m in range(shape[0]): |
| 10103 |
for p in range(shape[1]): |
| 10104 |
for t in range(shape[2]): |
| 10105 |
for z in range(shape[3]): |
| 10106 |
data[z] = next(pages).asarray() |
| 10107 |
for y in range(tiles[0]): |
| 10108 |
for x in range(tiles[1]): |
| 10109 |
out[:] = data[ |
| 10110 |
..., |
| 10111 |
y * tile[0] : (y + 1) * tile[0], |
| 10112 |
x * tile[1] : (x + 1) * tile[1], |
| 10113 |
] |
| 10114 |
if binfile: |
| 10115 |
out.tofile(binfile % (m, p, t, y, x)) |
| 10116 |
verbose(".", end="", flush=True) |
| 10117 |
verbose(" %.3f s" % (time.time() - start_time)) |
| 10118 |
|
| 10119 |
|
| 10120 |
def imshow( |
| 10121 |
data, |
| 10122 |
title=None, |
| 10123 |
vmin=0, |
| 10124 |
vmax=None, |
| 10125 |
cmap=None, |
| 10126 |
bitspersample=None, |
| 10127 |
photometric="RGB", |
| 10128 |
interpolation=None, |
| 10129 |
dpi=96, |
| 10130 |
figure=None, |
| 10131 |
subplot=111, |
| 10132 |
maxdim=32768, |
| 10133 |
**kwargs, |
| 10134 |
): |
| 10135 |
"""Plot n-dimensional images using matplotlib.pyplot. |
| 10136 |
|
| 10137 |
Return figure, subplot and plot axis. |
| 10138 |
Requires pyplot already imported C{from matplotlib import pyplot}. |
| 10139 |
|
| 10140 |
Parameters |
| 10141 |
---------- |
| 10142 |
bitspersample : int or None |
| 10143 |
Number of bits per channel in integer RGB images. |
| 10144 |
photometric : {'MINISWHITE', 'MINISBLACK', 'RGB', or 'PALETTE'} |
| 10145 |
The color space of the image data. |
| 10146 |
title : str |
| 10147 |
Window and subplot title. |
| 10148 |
figure : matplotlib.figure.Figure (optional). |
| 10149 |
Matplotlib to use for plotting. |
| 10150 |
subplot : int |
| 10151 |
A matplotlib.pyplot.subplot axis. |
| 10152 |
maxdim : int |
| 10153 |
maximum image width and length. |
| 10154 |
kwargs : optional |
| 10155 |
Arguments for matplotlib.pyplot.imshow. |
| 10156 |
|
| 10157 |
""" |
| 10158 |
isrgb = photometric in ("RGB",) |
| 10159 |
if data.dtype.kind == "b": |
| 10160 |
isrgb = False |
| 10161 |
if isrgb and not ( |
| 10162 |
data.shape[-1] in (3, 4) or (data.ndim > 2 and data.shape[-3] in (3, 4)) |
| 10163 |
): |
| 10164 |
isrgb = False |
| 10165 |
photometric = "MINISBLACK" |
| 10166 |
|
| 10167 |
data = data.squeeze() |
| 10168 |
if photometric in ("MINISWHITE", "MINISBLACK", None): |
| 10169 |
data = reshape_nd(data, 2) |
| 10170 |
else: |
| 10171 |
data = reshape_nd(data, 3) |
| 10172 |
|
| 10173 |
dims = data.ndim |
| 10174 |
if dims < 2: |
| 10175 |
raise ValueError("not an image") |
| 10176 |
elif dims == 2: |
| 10177 |
dims = 0 |
| 10178 |
isrgb = False |
| 10179 |
else: |
| 10180 |
if isrgb and data.shape[-3] in (3, 4): |
| 10181 |
data = numpy.swapaxes(data, -3, -2) |
| 10182 |
data = numpy.swapaxes(data, -2, -1) |
| 10183 |
elif not isrgb and ( |
| 10184 |
data.shape[-1] < data.shape[-2] // 8 |
| 10185 |
and data.shape[-1] < data.shape[-3] // 8 |
| 10186 |
and data.shape[-1] < 5 |
| 10187 |
): |
| 10188 |
data = numpy.swapaxes(data, -3, -1) |
| 10189 |
data = numpy.swapaxes(data, -2, -1) |
| 10190 |
isrgb = isrgb and data.shape[-1] in (3, 4) |
| 10191 |
dims -= 3 if isrgb else 2 |
| 10192 |
|
| 10193 |
if isrgb: |
| 10194 |
data = data[..., :maxdim, :maxdim, :maxdim] |
| 10195 |
else: |
| 10196 |
data = data[..., :maxdim, :maxdim] |
| 10197 |
|
| 10198 |
if photometric == "PALETTE" and isrgb: |
| 10199 |
datamax = data.max() |
| 10200 |
if datamax > 255: |
| 10201 |
data = data >> 8 |
| 10202 |
data = data.astype("B") |
| 10203 |
elif data.dtype.kind in "ui": |
| 10204 |
if not (isrgb and data.dtype.itemsize <= 1) or bitspersample is None: |
| 10205 |
try: |
| 10206 |
bitspersample = int(math.ceil(math.log(data.max(), 2))) |
| 10207 |
except Exception: |
| 10208 |
bitspersample = data.dtype.itemsize * 8 |
| 10209 |
elif not isinstance(bitspersample, inttypes): |
| 10210 |
|
| 10211 |
bitspersample = data.dtype.itemsize * 8 |
| 10212 |
datamax = 2**bitspersample |
| 10213 |
if isrgb: |
| 10214 |
if bitspersample < 8: |
| 10215 |
data = data << (8 - bitspersample) |
| 10216 |
elif bitspersample > 8: |
| 10217 |
data = data >> (bitspersample - 8) |
| 10218 |
data = data.astype("B") |
| 10219 |
elif data.dtype.kind == "f": |
| 10220 |
datamax = data.max() |
| 10221 |
if isrgb and datamax > 1.0: |
| 10222 |
if data.dtype.char == "d": |
| 10223 |
data = data.astype("f") |
| 10224 |
data /= datamax |
| 10225 |
else: |
| 10226 |
data = data / datamax |
| 10227 |
elif data.dtype.kind == "b": |
| 10228 |
datamax = 1 |
| 10229 |
elif data.dtype.kind == "c": |
| 10230 |
data = numpy.absolute(data) |
| 10231 |
datamax = data.max() |
| 10232 |
|
| 10233 |
if not isrgb: |
| 10234 |
if vmax is None: |
| 10235 |
vmax = datamax |
| 10236 |
if vmin is None: |
| 10237 |
if data.dtype.kind == "i": |
| 10238 |
dtmin = numpy.iinfo(data.dtype).min |
| 10239 |
vmin = numpy.min(data) |
| 10240 |
if vmin == dtmin: |
| 10241 |
vmin = numpy.min(data > dtmin) |
| 10242 |
if data.dtype.kind == "f": |
| 10243 |
dtmin = numpy.finfo(data.dtype).min |
| 10244 |
vmin = numpy.min(data) |
| 10245 |
if vmin == dtmin: |
| 10246 |
vmin = numpy.min(data > dtmin) |
| 10247 |
else: |
| 10248 |
vmin = 0 |
| 10249 |
|
| 10250 |
pyplot = sys.modules["matplotlib.pyplot"] |
| 10251 |
|
| 10252 |
if figure is None: |
| 10253 |
pyplot.rc("font", family="sans-serif", weight="normal", size=8) |
| 10254 |
figure = pyplot.figure( |
| 10255 |
dpi=dpi, figsize=(10.3, 6.3), frameon=True, facecolor="1.0", edgecolor="w" |
| 10256 |
) |
| 10257 |
try: |
| 10258 |
figure.canvas.manager.window.title(title) |
| 10259 |
except Exception: |
| 10260 |
pass |
| 10261 |
size = len(title.splitlines()) if title else 1 |
| 10262 |
pyplot.subplots_adjust( |
| 10263 |
bottom=0.03 * (dims + 2), |
| 10264 |
top=0.98 - size * 0.03, |
| 10265 |
left=0.1, |
| 10266 |
right=0.95, |
| 10267 |
hspace=0.05, |
| 10268 |
wspace=0.0, |
| 10269 |
) |
| 10270 |
subplot = pyplot.subplot(subplot) |
| 10271 |
|
| 10272 |
if title: |
| 10273 |
try: |
| 10274 |
title = unicode(title, "Windows-1252") |
| 10275 |
except TypeError: |
| 10276 |
pass |
| 10277 |
pyplot.title(title, size=11) |
| 10278 |
|
| 10279 |
if cmap is None: |
| 10280 |
if data.dtype.char == "?": |
| 10281 |
cmap = "gray" |
| 10282 |
elif data.dtype.kind in "buf" or vmin == 0: |
| 10283 |
cmap = "viridis" |
| 10284 |
else: |
| 10285 |
cmap = "coolwarm" |
| 10286 |
if photometric == "MINISWHITE": |
| 10287 |
cmap += "_r" |
| 10288 |
|
| 10289 |
image = pyplot.imshow( |
| 10290 |
numpy.atleast_2d(data[(0,) * dims].squeeze()), |
| 10291 |
vmin=vmin, |
| 10292 |
vmax=vmax, |
| 10293 |
cmap=cmap, |
| 10294 |
interpolation=interpolation, |
| 10295 |
**kwargs, |
| 10296 |
) |
| 10297 |
|
| 10298 |
if not isrgb: |
| 10299 |
pyplot.colorbar() |
| 10300 |
|
| 10301 |
def format_coord(x, y): |
| 10302 |
|
| 10303 |
x = int(x + 0.5) |
| 10304 |
y = int(y + 0.5) |
| 10305 |
try: |
| 10306 |
if dims: |
| 10307 |
return "%s @ %s [%4i, %4i]" % (curaxdat[1][y, x], current, y, x) |
| 10308 |
return "%s @ [%4i, %4i]" % (data[y, x], y, x) |
| 10309 |
except IndexError: |
| 10310 |
return "" |
| 10311 |
|
| 10312 |
def none(event): |
| 10313 |
return "" |
| 10314 |
|
| 10315 |
subplot.format_coord = format_coord |
| 10316 |
image.get_cursor_data = none |
| 10317 |
image.format_cursor_data = none |
| 10318 |
|
| 10319 |
if dims: |
| 10320 |
current = list((0,) * dims) |
| 10321 |
curaxdat = [0, data[tuple(current)].squeeze()] |
| 10322 |
sliders = [ |
| 10323 |
pyplot.Slider( |
| 10324 |
pyplot.axes([0.125, 0.03 * (axis + 1), 0.725, 0.025]), |
| 10325 |
"Dimension %i" % axis, |
| 10326 |
0, |
| 10327 |
data.shape[axis] - 1, |
| 10328 |
0, |
| 10329 |
facecolor="0.5", |
| 10330 |
valfmt="%%.0f [%i]" % data.shape[axis], |
| 10331 |
) |
| 10332 |
for axis in range(dims) |
| 10333 |
] |
| 10334 |
for slider in sliders: |
| 10335 |
slider.drawon = False |
| 10336 |
|
| 10337 |
def set_image(current, sliders=sliders, data=data): |
| 10338 |
|
| 10339 |
curaxdat[1] = data[tuple(current)].squeeze() |
| 10340 |
image.set_data(curaxdat[1]) |
| 10341 |
for ctrl, index in zip(sliders, current): |
| 10342 |
ctrl.eventson = False |
| 10343 |
ctrl.set_val(index) |
| 10344 |
ctrl.eventson = True |
| 10345 |
figure.canvas.draw() |
| 10346 |
|
| 10347 |
def on_changed(index, axis, data=data, current=current): |
| 10348 |
|
| 10349 |
index = int(round(index)) |
| 10350 |
curaxdat[0] = axis |
| 10351 |
if index == current[axis]: |
| 10352 |
return |
| 10353 |
if index >= data.shape[axis]: |
| 10354 |
index = 0 |
| 10355 |
elif index < 0: |
| 10356 |
index = data.shape[axis] - 1 |
| 10357 |
current[axis] = index |
| 10358 |
set_image(current) |
| 10359 |
|
| 10360 |
def on_keypressed(event, data=data, current=current): |
| 10361 |
|
| 10362 |
key = event.key |
| 10363 |
axis = curaxdat[0] |
| 10364 |
if str(key) in "0123456789": |
| 10365 |
on_changed(key, axis) |
| 10366 |
elif key == "right": |
| 10367 |
on_changed(current[axis] + 1, axis) |
| 10368 |
elif key == "left": |
| 10369 |
on_changed(current[axis] - 1, axis) |
| 10370 |
elif key == "up": |
| 10371 |
curaxdat[0] = 0 if axis == len(data.shape) - 1 else axis + 1 |
| 10372 |
elif key == "down": |
| 10373 |
curaxdat[0] = len(data.shape) - 1 if axis == 0 else axis - 1 |
| 10374 |
elif key == "end": |
| 10375 |
on_changed(data.shape[axis] - 1, axis) |
| 10376 |
elif key == "home": |
| 10377 |
on_changed(0, axis) |
| 10378 |
|
| 10379 |
figure.canvas.mpl_connect("key_press_event", on_keypressed) |
| 10380 |
for axis, ctrl in enumerate(sliders): |
| 10381 |
ctrl.on_changed(lambda k, a=axis: on_changed(k, a)) |
| 10382 |
|
| 10383 |
return figure, subplot, image |
| 10384 |
|
| 10385 |
|
| 10386 |
def _app_show(): |
| 10387 |
"""Block the GUI. For use as skimage plugin.""" |
| 10388 |
pyplot = sys.modules["matplotlib.pyplot"] |
| 10389 |
pyplot.show() |
| 10390 |
|
| 10391 |
|
| 10392 |
def askopenfilename(**kwargs): |
| 10393 |
"""Return file name(s) from Tkinter's file open dialog.""" |
| 10394 |
try: |
| 10395 |
from Tkinter import Tk |
| 10396 |
import tkFileDialog as filedialog |
| 10397 |
except ImportError: |
| 10398 |
from tkinter import Tk, filedialog |
| 10399 |
root = Tk() |
| 10400 |
root.withdraw() |
| 10401 |
root.update() |
| 10402 |
filenames = filedialog.askopenfilename(**kwargs) |
| 10403 |
root.destroy() |
| 10404 |
return filenames |
| 10405 |
|
| 10406 |
|
| 10407 |
def main(argv=None): |
| 10408 |
"""Command line usage main function.""" |
| 10409 |
if float(sys.version[0:3]) < 2.7: |
| 10410 |
print("This script requires Python version 2.7 or better.") |
| 10411 |
print("This is Python version %s" % sys.version) |
| 10412 |
return 0 |
| 10413 |
if argv is None: |
| 10414 |
argv = sys.argv |
| 10415 |
|
| 10416 |
import optparse |
| 10417 |
|
| 10418 |
parser = optparse.OptionParser( |
| 10419 |
usage="usage: %prog [options] path", |
| 10420 |
description="Display image data in TIFF files.", |
| 10421 |
version="%%prog %s" % __version__, |
| 10422 |
) |
| 10423 |
opt = parser.add_option |
| 10424 |
opt("-p", "--page", dest="page", type="int", default=-1, help="display single page") |
| 10425 |
opt( |
| 10426 |
"-s", |
| 10427 |
"--series", |
| 10428 |
dest="series", |
| 10429 |
type="int", |
| 10430 |
default=-1, |
| 10431 |
help="display series of pages of same shape", |
| 10432 |
) |
| 10433 |
opt( |
| 10434 |
"--nomultifile", |
| 10435 |
dest="nomultifile", |
| 10436 |
action="store_true", |
| 10437 |
default=False, |
| 10438 |
help="do not read OME series from multiple files", |
| 10439 |
) |
| 10440 |
opt( |
| 10441 |
"--noplots", |
| 10442 |
dest="noplots", |
| 10443 |
type="int", |
| 10444 |
default=8, |
| 10445 |
help="maximum number of plots", |
| 10446 |
) |
| 10447 |
opt( |
| 10448 |
"--interpol", |
| 10449 |
dest="interpol", |
| 10450 |
metavar="INTERPOL", |
| 10451 |
default="bilinear", |
| 10452 |
help="image interpolation method", |
| 10453 |
) |
| 10454 |
opt("--dpi", dest="dpi", type="int", default=96, help="plot resolution") |
| 10455 |
opt( |
| 10456 |
"--vmin", |
| 10457 |
dest="vmin", |
| 10458 |
type="int", |
| 10459 |
default=None, |
| 10460 |
help="minimum value for colormapping", |
| 10461 |
) |
| 10462 |
opt( |
| 10463 |
"--vmax", |
| 10464 |
dest="vmax", |
| 10465 |
type="int", |
| 10466 |
default=None, |
| 10467 |
help="maximum value for colormapping", |
| 10468 |
) |
| 10469 |
opt( |
| 10470 |
"--debug", |
| 10471 |
dest="debug", |
| 10472 |
action="store_true", |
| 10473 |
default=False, |
| 10474 |
help="raise exception on failures", |
| 10475 |
) |
| 10476 |
opt( |
| 10477 |
"--doctest", |
| 10478 |
dest="doctest", |
| 10479 |
action="store_true", |
| 10480 |
default=False, |
| 10481 |
help="runs the docstring examples", |
| 10482 |
) |
| 10483 |
opt("-v", "--detail", dest="detail", type="int", default=2) |
| 10484 |
opt("-q", "--quiet", dest="quiet", action="store_true") |
| 10485 |
|
| 10486 |
settings, path = parser.parse_args() |
| 10487 |
path = " ".join(path) |
| 10488 |
|
| 10489 |
if settings.doctest: |
| 10490 |
import doctest |
| 10491 |
|
| 10492 |
doctest.testmod(optionflags=doctest.ELLIPSIS) |
| 10493 |
return 0 |
| 10494 |
if not path: |
| 10495 |
path = askopenfilename( |
| 10496 |
title="Select a TIFF file", filetypes=TIFF.FILEOPEN_FILTER |
| 10497 |
) |
| 10498 |
if not path: |
| 10499 |
parser.error("No file specified") |
| 10500 |
|
| 10501 |
if any(i in path for i in "?*"): |
| 10502 |
path = glob.glob(path) |
| 10503 |
if not path: |
| 10504 |
print("no files match the pattern") |
| 10505 |
return 0 |
| 10506 |
|
| 10507 |
path = path[0] |
| 10508 |
|
| 10509 |
if not settings.quiet: |
| 10510 |
print("\nReading file structure...", end=" ") |
| 10511 |
start = time.time() |
| 10512 |
try: |
| 10513 |
tif = TiffFile(path, multifile=not settings.nomultifile) |
| 10514 |
except Exception as e: |
| 10515 |
if settings.debug: |
| 10516 |
raise |
| 10517 |
else: |
| 10518 |
print("\n", e) |
| 10519 |
sys.exit(0) |
| 10520 |
if not settings.quiet: |
| 10521 |
print("%.3f ms" % ((time.time() - start) * 1e3)) |
| 10522 |
|
| 10523 |
if tif.is_ome: |
| 10524 |
settings.norgb = True |
| 10525 |
|
| 10526 |
images = [] |
| 10527 |
if settings.noplots > 0: |
| 10528 |
if not settings.quiet: |
| 10529 |
print("Reading image data... ", end=" ") |
| 10530 |
|
| 10531 |
def notnone(x): |
| 10532 |
return next(i for i in x if i is not None) |
| 10533 |
|
| 10534 |
start = time.time() |
| 10535 |
try: |
| 10536 |
if settings.page >= 0: |
| 10537 |
images = [(tif.asarray(key=settings.page), tif[settings.page], None)] |
| 10538 |
elif settings.series >= 0: |
| 10539 |
images = [ |
| 10540 |
( |
| 10541 |
tif.asarray(series=settings.series), |
| 10542 |
notnone(tif.series[settings.series]._pages), |
| 10543 |
tif.series[settings.series], |
| 10544 |
) |
| 10545 |
] |
| 10546 |
else: |
| 10547 |
images = [] |
| 10548 |
for i, s in enumerate(tif.series[: settings.noplots]): |
| 10549 |
try: |
| 10550 |
images.append( |
| 10551 |
(tif.asarray(series=i), notnone(s._pages), tif.series[i]) |
| 10552 |
) |
| 10553 |
except ValueError as e: |
| 10554 |
images.append((None, notnone(s.pages), None)) |
| 10555 |
if settings.debug: |
| 10556 |
raise |
| 10557 |
else: |
| 10558 |
print("\nSeries %i failed: %s... " % (i, e), end="") |
| 10559 |
if not settings.quiet: |
| 10560 |
print("%.3f ms" % ((time.time() - start) * 1e3)) |
| 10561 |
except Exception as e: |
| 10562 |
if settings.debug: |
| 10563 |
raise |
| 10564 |
else: |
| 10565 |
print(e) |
| 10566 |
|
| 10567 |
if not settings.quiet: |
| 10568 |
print() |
| 10569 |
print(TiffFile.__str__(tif, detail=int(settings.detail))) |
| 10570 |
print() |
| 10571 |
tif.close() |
| 10572 |
|
| 10573 |
if images and settings.noplots > 0: |
| 10574 |
try: |
| 10575 |
import matplotlib |
| 10576 |
|
| 10577 |
matplotlib.use("TkAgg") |
| 10578 |
from matplotlib import pyplot |
| 10579 |
except ImportError as e: |
| 10580 |
warnings.warn("failed to import matplotlib.\n%s" % e) |
| 10581 |
else: |
| 10582 |
for img, page, series in images: |
| 10583 |
if img is None: |
| 10584 |
continue |
| 10585 |
vmin, vmax = settings.vmin, settings.vmax |
| 10586 |
if "GDAL_NODATA" in page.tags: |
| 10587 |
try: |
| 10588 |
vmin = numpy.min( |
| 10589 |
img[img > float(page.tags["GDAL_NODATA"].value)] |
| 10590 |
) |
| 10591 |
except ValueError: |
| 10592 |
pass |
| 10593 |
if tif.is_stk: |
| 10594 |
try: |
| 10595 |
vmin = tif.stk_metadata["MinScale"] |
| 10596 |
vmax = tif.stk_metadata["MaxScale"] |
| 10597 |
except KeyError: |
| 10598 |
pass |
| 10599 |
else: |
| 10600 |
if vmax <= vmin: |
| 10601 |
vmin, vmax = settings.vmin, settings.vmax |
| 10602 |
if series: |
| 10603 |
title = "%s\n%s\n%s" % (str(tif), str(page), str(series)) |
| 10604 |
else: |
| 10605 |
title = "%s\n %s" % (str(tif), str(page)) |
| 10606 |
photometric = "MINISBLACK" |
| 10607 |
if page.photometric not in (3,): |
| 10608 |
photometric = TIFF.PHOTOMETRIC(page.photometric).name |
| 10609 |
imshow( |
| 10610 |
img, |
| 10611 |
title=title, |
| 10612 |
vmin=vmin, |
| 10613 |
vmax=vmax, |
| 10614 |
bitspersample=page.bitspersample, |
| 10615 |
photometric=photometric, |
| 10616 |
interpolation=settings.interpol, |
| 10617 |
dpi=settings.dpi, |
| 10618 |
) |
| 10619 |
pyplot.show() |
| 10620 |
|
| 10621 |
|
| 10622 |
if sys.version_info[0] == 2: |
| 10623 |
inttypes = int, long |
| 10624 |
|
| 10625 |
def print_(*args, **kwargs): |
| 10626 |
"""Print function with flush support.""" |
| 10627 |
flush = kwargs.pop("flush", False) |
| 10628 |
print(*args, **kwargs) |
| 10629 |
if flush: |
| 10630 |
sys.stdout.flush() |
| 10631 |
|
| 10632 |
def bytes2str(b, encoding=None, errors=None): |
| 10633 |
"""Return string from bytes.""" |
| 10634 |
return b |
| 10635 |
|
| 10636 |
def str2bytes(s, encoding=None): |
| 10637 |
"""Return bytes from string.""" |
| 10638 |
return s |
| 10639 |
|
| 10640 |
def byte2int(b): |
| 10641 |
"""Return value of byte as int.""" |
| 10642 |
return ord(b) |
| 10643 |
|
| 10644 |
class FileNotFoundError(IOError): |
| 10645 |
pass |
| 10646 |
|
| 10647 |
TiffFrame = TiffPage |
| 10648 |
else: |
| 10649 |
inttypes = int |
| 10650 |
basestring = str, bytes |
| 10651 |
unicode = str |
| 10652 |
print_ = print |
| 10653 |
|
| 10654 |
def bytes2str(b, encoding=None, errors="strict"): |
| 10655 |
"""Return unicode string from encoded bytes.""" |
| 10656 |
if encoding is not None: |
| 10657 |
return b.decode(encoding, errors) |
| 10658 |
try: |
| 10659 |
return b.decode("utf-8", errors) |
| 10660 |
except UnicodeDecodeError: |
| 10661 |
return b.decode("cp1252", errors) |
| 10662 |
|
| 10663 |
def str2bytes(s, encoding="cp1252"): |
| 10664 |
"""Return bytes from unicode string.""" |
| 10665 |
return s.encode(encoding) |
| 10666 |
|
| 10667 |
def byte2int(b): |
| 10668 |
"""Return value of byte as int.""" |
| 10669 |
return b |
| 10670 |
|
| 10671 |
|
| 10672 |
if __name__ == "__main__": |
| 10673 |
sys.exit(main()) |