
    0-Php             '      j   d Z ddlmZ dZg dZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddlZddlZddlZddlZddlZddlZddlZddlmZmZmZmZ ddlmZ ddlmZ dd	lmZ dd
lm Z  ddl!Z!	 ddl"Z"n"# e#$ r 	 ddl$m%Z" n# e#$ r ddl%Z"Y nw xY wY nw xY wddl&m'Z'm(Z(m)Z)m*Z*m+Z+ e(rcddlm,Z,m-Z-m.Z. ddl&m/Z/m0Z0m1Z1m2Z2 ddl3m4Z4m5Z5m6Z6 e0d         Z7e2e8e'e9         e6e/         df         Z:e;e2e<e8f         e2e<e8f         e1e<         e/e=f         Z>e+	 d=ddddddddddddddddddddddddddddddddd>dL            Z?e+	 d=ddddddddddddddddddddddddddddddddMd?dR            Z?e+	 d=ddSdddddddddddddddddddddddddddddddT d@dW            Z?	 d=ddSdddddddddddddddddddddddddddddddT d@dXZ?	 d=ddddSdddSddddddSddddddddddddddddi ddSdSddddSdY%dAdZ@ddddddddBdZA G d deB          ZCe* G d d                      ZDe* G d d                      ZEe* G d d                      ZFe* G d d                      ZGe* G d d                      ZHe* G d deeGeHz                                 ZIe* G d d                      ZJe* G d d                      ZKe* G d d                      ZLe* G d deeGeHz  dz                                 ZM G d dee8                   ZNe* G d deN                      ZOe* G d d                      ZPe* G d d                      ZQe* G d d                      ZRe* G d dee<                               ZSe* G d d                      ZTe* G d d                      ZU G d deB          ZVe* G d dæ                      ZWe* G dĄ dee<edeXf         f                               ZYe* G dƄ dee<edeXf         f                               ZZ G dȄ dej[                  Z\ G dʄ dej[                  Z] G d̄ dej[                  Z^ G d΄ dej[                  Z_ G dЄ dej`                  Za G d҄ dej[                  Zb G dԄ dej[                  Zc G dք dej[                  Zd G d؄ dej[                  Ze G dڄ dej[                  Zf G d܄ dej[                  Zg G dބ dej[                  Zh G d dej[                  Zi G d d          Zj ej            ZkddddCdZldDdZmdDdZndDdZodEdZpdFdZqdGdZrdGdZsdHdZtdDdZudGdZv	 dIdJdZwdKdZxdKd ZydKdZzdLdZ{dMdZ|dDdZ}dNdZ~dNdZdNd	ZdNd
ZdOdZdMdZdMdZdMdZdDdZdDdZdDdZdDdZdDdZdDdZdPdZ	 d=dQdZdRdZdSdZdTd!ZdUd#ZdVd&ZdWd'Z	 	 	 dXdYd+Zddd,dZd.Zd[d1Zd\d4Zd]d6Zd^d7ZdWd8Z	 d=d_d:ZdWd;ZdWd<Zd`d=ZdWd>Zdad?ZdbdAZdcdCZ	 dddedFZdfdGZ	 	 	 dgdhdJZ	 didjdMZ	 	 	 dkddNdldRZdmdTZdndXZdodZZdpdaZdqddZdrdhZe+dsdk            Ze+dtdl            ZdudnZe+	 d=dvdq            Ze+	 d=dwdt            Z	 d=dxdxZ	 d=dydzZe+	 d=dzd}            Ze+	 d=d{d~            Z	 d=d|dZ	 d}d~dZddZe+	 ddd            Ze+	 ddd            Z	 	 dddZ	 d}ddZdddddddZddddddZddZd=ddZe+	 d=dHddd            Ze+	 d=dHddd            Z	 d=dHdddZddZe+	 	 ddd            Ze+	 	 ddd            Z	 	 dddZd=ddZddZddZdddńZddǄZddȄZddʄZÐdd̈́ZĐddфZŐddԄZƐddׄZǐd=ddۄZȐdIddބZɐdd߄ZʐddZːddZ̐dHdddddZ͐ddddddddZΐddZϐd}ddZАddZѐddZҐddddHdddZ	 dddd ddZԐddZՐddZ֐ddZאdd	Zؐdd
ZِddZ	 	 dddZ	 	 	 dkddZddddddddddd
ddZ	 d=ddHdddZddddddddddddd dddSd!dd1Zߐdd2Zdd3Z	 ddd7Zddd:ZeEZe(rdd;lmZmZmZ ed<k    r ej         e                       dS dS (  uTp  Read and write TIFF files.

Tifffile is a Python library to

(1) store NumPy arrays in TIFF (Tagged Image File Format) files, and
(2) read image and metadata from TIFF-like files used in bioimaging.

Image and metadata can be read from TIFF, BigTIFF, OME-TIFF, GeoTIFF,
Adobe DNG, ZIF (Zoomable Image File Format), MetaMorph STK, Zeiss LSM,
ImageJ hyperstack, Micro-Manager MMStack and NDTiff, SGI, NIHImage,
Olympus FluoView and SIS, ScanImage, Molecular Dynamics GEL,
Aperio SVS, Leica SCN, Roche BIF, PerkinElmer QPTIFF (QPI, PKI),
Hamamatsu NDPI, Argos AVS, and Philips DP formatted files.

Image data can be read as NumPy arrays or Zarr arrays/groups from strips,
tiles, pages (IFDs), SubIFDs, higher-order series, and pyramidal levels.

Image data can be written to TIFF, BigTIFF, OME-TIFF, and ImageJ hyperstack
compatible files in multi-page, volumetric, pyramidal, memory-mappable,
tiled, predicted, or compressed form.

Many compression and predictor schemes are supported via the imagecodecs
library, including LZW, PackBits, Deflate, PIXTIFF, LZMA, LERC, Zstd,
JPEG (8 and 12-bit, lossless), JPEG 2000, JPEG XR, JPEG XL, WebP, PNG, EER,
Jetraw, 24-bit floating-point, and horizontal differencing.

Tifffile can also be used to inspect TIFF structures, read image data from
multi-dimensional file sequences, write fsspec ReferenceFileSystem for
TIFF files and image file sequences, patch TIFF tag values, and parse
many proprietary metadata formats.

:Author: `Christoph Gohlke <https://www.cgohlke.com>`_
:License: BSD-3-Clause
:Version: 2025.6.11
:DOI: `10.5281/zenodo.6795860 <https://doi.org/10.5281/zenodo.6795860>`_

Quickstart
----------

Install the tifffile package and all dependencies from the
`Python Package Index <https://pypi.org/project/tifffile/>`_::

    python -m pip install -U tifffile[all]

Tifffile is also available in other package repositories such as Anaconda,
Debian, and MSYS2.

The tifffile library is type annotated and documented via docstrings::

    python -c "import tifffile; help(tifffile)"

Tifffile can be used as a console script to inspect and preview TIFF files::

    python -m tifffile --help

See `Examples`_ for using the programming interface.

Source code and support are available on
`GitHub <https://github.com/cgohlke/tifffile>`_.

Support is also provided on the
`image.sc <https://forum.image.sc/tag/tifffile>`_ forum.

Requirements
------------

This revision was tested with the following requirements and dependencies
(other versions may work):

- `CPython <https://www.python.org>`_ 3.11.9, 3.12.10, 3.13.5 3.14.0b2 64-bit
- `NumPy <https://pypi.org/project/numpy/>`_ 2.2.6
- `Imagecodecs <https://pypi.org/project/imagecodecs/>`_ 2025.3.30
  (required for encoding or decoding LZW, JPEG, etc. compressed segments)
- `Matplotlib <https://pypi.org/project/matplotlib/>`_ 3.10.3
  (required for plotting)
- `Lxml <https://pypi.org/project/lxml/>`_ 5.4.0
  (required only for validating and printing XML)
- `Zarr <https://pypi.org/project/zarr/>`_ 3.0.8
  (required only for using Zarr stores; Zarr 2 is not compatible)
- `Kerchunk <https://pypi.org/project/kerchunk/>`_ 0.2.8
  (required only for opening ReferenceFileSystem files)

Revisions
---------

2025.6.11

- Pass 5113 tests.
- Fix reading images with dimension length 1 through Zarr (#303).

2025.6.1

- Add experimental option to write iterator of bytes and bytecounts (#301).

2025.5.26

- Use threads in Zarr stores.

2025.5.24

- Fix incorrect tags created by Philips DP v1.1 (#299).
- Make Zarr stores partially listable.

2025.5.21

- Move Zarr stores to tifffile.zarr namespace (breaking).
- Require Zarr 3 for Zarr stores and remove support for Zarr 2 (breaking).
- Drop support for Python 3.10.

2025.5.10

- Raise ValueError when using zarr 3 (#296).
- Fall back to compression.zstd on Python >= 3.14 if no imagecodecs.
- Remove doctest command line option.
- Support Python 3.14.

2025.3.30

- Fix for imagecodecs 2025.3.30.

2025.3.13

- Change bytes2str to decode only up to first NULL character (breaking).
- Remove stripnull function calls to reduce overhead (#285).
- Deprecate stripnull function.

2025.2.18

- Fix julian_datetime milliseconds (#283).
- Remove deprecated dtype arguments from imread and FileSequence (breaking).
- Remove deprecated imsave and TiffWriter.save function/method (breaking).
- Remove deprecated option to pass multiple values to compression (breaking).
- Remove deprecated option to pass unit to resolution (breaking).
- Remove deprecated enums from TIFF namespace (breaking).
- Remove deprecated lazyattr and squeeze_axes functions (breaking).

2025.1.10

- Improve type hints.
- Deprecate Python 3.10.

2024.12.12

- Read PlaneProperty from STK UIC1Tag (#280).
- Allow 'None' as alias for COMPRESSION.NONE and PREDICTOR.NONE (#274).
- Zarr 3 is not supported (#272).

2024.9.20

- Fix writing colormap to ImageJ files (breaking).
- Improve typing.
- Drop support for Python 3.9.

2024.8.30

- Support writing OME Dataset and some StructuredAnnotations elements.

2024.8.28

- Fix LSM scan types and dimension orders (#269, breaking).
- Use IO[bytes] instead of BinaryIO for typing (#268).

2024.8.24

- Do not remove trailing length-1 dimension writing non-shaped file (breaking).
- Fix writing OME-TIFF with certain modulo axes orders.
- Make imshow NaN aware.

2024.8.10

- Relax bitspersample check for JPEG, JPEG2K, and JPEGXL compression (#265).

2024.7.24

- Fix reading contiguous multi-page series via Zarr store (#67).

2024.7.21

- Fix integer overflow in product function caused by numpy types.
- Allow tag reader functions to fail.

2024.7.2

- Enable memmap to create empty files with non-native byte order.
- Deprecate Python 3.9, support Python 3.13.

2024.6.18

- Ensure TiffPage.nodata is castable to dtype (breaking, #260).
- Support Argos AVS slides.

2024.5.22

- Derive TiffPages, TiffPageSeries, FileSequence, StoredShape from Sequence.
- Truncate circular IFD chain, do not raise TiffFileError (breaking).
- Deprecate access to TiffPages.pages and FileSequence.files.
- Enable DeprecationWarning for enums in TIFF namespace.
- Remove some deprecated code (breaking).
- Add iccprofile property to TiffPage and parameter to TiffWriter.write.
- Do not detect VSI as SIS format.
- Limit length of logged exception messages.
- Fix docstring examples not correctly rendered on GitHub (#254, #255).

- …

Refer to the CHANGES file for older revisions.

Notes
-----

TIFF, the Tagged Image File Format, was created by the Aldus Corporation and
Adobe Systems Incorporated.

Tifffile supports a subset of the TIFF6 specification, mainly 8, 16, 32, and
64-bit integer, 16, 32, and 64-bit float, grayscale and multi-sample images.
Specifically, CCITT and OJPEG compression, chroma subsampling without JPEG
compression, color space transformations, samples with differing types, or
IPTC, ICC, and XMP metadata are not implemented.

Besides classic TIFF, tifffile supports several TIFF-like formats that do not
strictly adhere to the TIFF6 specification. Some formats allow file and data
sizes to exceed the 4 GB limit of the classic TIFF:

- **BigTIFF** is identified by version number 43 and uses different file
  header, IFD, and tag structures with 64-bit offsets. The format also adds
  64-bit data types. Tifffile can read and write BigTIFF files.
- **ImageJ hyperstacks** store all image data, which may exceed 4 GB,
  contiguously after the first IFD. Files > 4 GB contain one IFD only.
  The size and shape of the up to 6-dimensional image data can be determined
  from the ImageDescription tag of the first IFD, which is Latin-1 encoded.
  Tifffile can read and write ImageJ hyperstacks.
- **OME-TIFF** files store up to 8-dimensional image data in one or multiple
  TIFF or BigTIFF files. The UTF-8 encoded OME-XML metadata found in the
  ImageDescription tag of the first IFD defines the position of TIFF IFDs in
  the high-dimensional image data. Tifffile can read OME-TIFF files (except
  multi-file pyramidal) and write NumPy arrays to single-file OME-TIFF.
- **Micro-Manager NDTiff** stores multi-dimensional image data in one
  or more classic TIFF files. Metadata contained in a separate NDTiff.index
  binary file defines the position of the TIFF IFDs in the image array.
  Each TIFF file also contains metadata in a non-TIFF binary structure at
  offset 8. Downsampled image data of pyramidal datasets are stored in
  separate folders. Tifffile can read NDTiff files. Version 0 and 1 series,
  tiling, stitching, and multi-resolution pyramids are not supported.
- **Micro-Manager MMStack** stores 6-dimensional image data in one or more
  classic TIFF files. Metadata contained in non-TIFF binary structures and
  JSON strings define the image stack dimensions and the position of the image
  frame data in the file and the image stack. The TIFF structures and metadata
  are often corrupted or wrong. Tifffile can read MMStack files.
- **Carl Zeiss LSM** files store all IFDs below 4 GB and wrap around 32-bit
  StripOffsets pointing to image data above 4 GB. The StripOffsets of each
  series and position require separate unwrapping. The StripByteCounts tag
  contains the number of bytes for the uncompressed data. Tifffile can read
  LSM files of any size.
- **MetaMorph Stack, STK** files contain additional image planes stored
  contiguously after the image data of the first page. The total number of
  planes is equal to the count of the UIC2tag. Tifffile can read STK files.
- **ZIF**, the Zoomable Image File format, is a subspecification of BigTIFF
  with SGI's ImageDepth extension and additional compression schemes.
  Only little-endian, tiled, interleaved, 8-bit per sample images with
  JPEG, PNG, JPEG XR, and JPEG 2000 compression are allowed. Tifffile can
  read and write ZIF files.
- **Hamamatsu NDPI** files use some 64-bit offsets in the file header, IFD,
  and tag structures. Single, LONG typed tag values can exceed 32-bit.
  The high bytes of 64-bit tag values and offsets are stored after IFD
  structures. Tifffile can read NDPI files > 4 GB.
  JPEG compressed segments with dimensions >65530 or missing restart markers
  cannot be decoded with common JPEG libraries. Tifffile works around this
  limitation by separately decoding the MCUs between restart markers, which
  performs poorly. BitsPerSample, SamplesPerPixel, and
  PhotometricInterpretation tags may contain wrong values, which can be
  corrected using the value of tag 65441.
- **Philips TIFF** slides store padded ImageWidth and ImageLength tag values
  for tiled pages. The values can be corrected using the DICOM_PIXEL_SPACING
  attributes of the XML formatted description of the first page. Tile offsets
  and byte counts may be 0. Tifffile can read Philips slides.
- **Ventana/Roche BIF** slides store tiles and metadata in a BigTIFF container.
  Tiles may overlap and require stitching based on the TileJointInfo elements
  in the XMP tag. Volumetric scans are stored using the ImageDepth extension.
  Tifffile can read BIF and decode individual tiles but does not perform
  stitching.
- **ScanImage** optionally allows corrupted non-BigTIFF files > 2 GB.
  The values of StripOffsets and StripByteCounts can be recovered using the
  constant differences of the offsets of IFD and tag values throughout the
  file. Tifffile can read such files if the image data are stored contiguously
  in each page.
- **GeoTIFF sparse** files allow strip or tile offsets and byte counts to be 0.
  Such segments are implicitly set to 0 or the NODATA value on reading.
  Tifffile can read GeoTIFF sparse files.
- **Tifffile shaped** files store the array shape and user-provided metadata
  of multi-dimensional image series in JSON format in the ImageDescription tag
  of the first page of the series. The format allows multiple series,
  SubIFDs, sparse segments with zero offset and byte count, and truncated
  series, where only the first page of a series is present, and the image data
  are stored contiguously. No other software besides Tifffile supports the
  truncated format.

Other libraries for reading, writing, inspecting, or manipulating scientific
TIFF files from Python are
`aicsimageio <https://pypi.org/project/aicsimageio>`_,
`apeer-ometiff-library
<https://github.com/apeer-micro/apeer-ometiff-library>`_,
`bigtiff <https://pypi.org/project/bigtiff>`_,
`fabio.TiffIO <https://github.com/silx-kit/fabio>`_,
`GDAL <https://github.com/OSGeo/gdal/>`_,
`imread <https://github.com/luispedro/imread>`_,
`large_image <https://github.com/girder/large_image>`_,
`openslide-python <https://github.com/openslide/openslide-python>`_,
`opentile <https://github.com/imi-bigpicture/opentile>`_,
`pylibtiff <https://github.com/pearu/pylibtiff>`_,
`pylsm <https://launchpad.net/pylsm>`_,
`pymimage <https://github.com/ardoi/pymimage>`_,
`python-bioformats <https://github.com/CellProfiler/python-bioformats>`_,
`pytiff <https://github.com/FZJ-INM1-BDA/pytiff>`_,
`scanimagetiffreader-python
<https://gitlab.com/vidriotech/scanimagetiffreader-python>`_,
`SimpleITK <https://github.com/SimpleITK/SimpleITK>`_,
`slideio <https://gitlab.com/bioslide/slideio>`_,
`tiffslide <https://github.com/bayer-science-for-a-better-life/tiffslide>`_,
`tifftools <https://github.com/DigitalSlideArchive/tifftools>`_,
`tyf <https://github.com/Moustikitos/tyf>`_,
`xtiff <https://github.com/BodenmillerGroup/xtiff>`_, and
`ndtiff <https://github.com/micro-manager/NDTiffStorage>`_.

References
----------

- TIFF 6.0 Specification and Supplements. Adobe Systems Incorporated.
  https://www.adobe.io/open/standards/TIFF.html
  https://download.osgeo.org/libtiff/doc/
- TIFF File Format FAQ. https://www.awaresystems.be/imaging/tiff/faq.html
- The BigTIFF File Format.
  https://www.awaresystems.be/imaging/tiff/bigtiff.html
- MetaMorph Stack (STK) Image File Format.
  http://mdc.custhelp.com/app/answers/detail/a_id/18862
- Image File Format Description LSM 5/7 Release 6.0 (ZEN 2010).
  Carl Zeiss MicroImaging GmbH. BioSciences. May 10, 2011
- The OME-TIFF format.
  https://docs.openmicroscopy.org/ome-model/latest/
- UltraQuant(r) Version 6.0 for Windows Start-Up Guide.
  http://www.ultralum.com/images%20ultralum/pdf/UQStart%20Up%20Guide.pdf
- Micro-Manager File Formats.
  https://micro-manager.org/wiki/Micro-Manager_File_Formats
- ScanImage BigTiff Specification.
  https://docs.scanimage.org/Appendix/ScanImage+BigTiff+Specification.html
- ZIF, the Zoomable Image File format. https://zif.photo/
- GeoTIFF File Format https://gdal.org/drivers/raster/gtiff.html
- Cloud optimized GeoTIFF.
  https://github.com/cogeotiff/cog-spec/blob/master/spec.md
- Tags for TIFF and Related Specifications. Digital Preservation.
  https://www.loc.gov/preservation/digital/formats/content/tiff_tags.shtml
- CIPA DC-008-2016: Exchangeable image file format for digital still cameras:
  Exif Version 2.31.
  http://www.cipa.jp/std/documents/e/DC-008-Translation-2016-E.pdf
- The EER (Electron Event Representation) file format.
  https://github.com/fei-company/EerReaderLib
- Digital Negative (DNG) Specification. Version 1.7.1.0, September 2023.
  https://helpx.adobe.com/content/dam/help/en/photoshop/pdf/DNG_Spec_1_7_1_0.pdf
- Roche Digital Pathology. BIF image file format for digital pathology.
  https://diagnostics.roche.com/content/dam/diagnostics/Blueprint/en/pdf/rmd/Roche-Digital-Pathology-BIF-Whitepaper.pdf
- Astro-TIFF specification. https://astro-tiff.sourceforge.io/
- Aperio Technologies, Inc. Digital Slides and Third-Party Data Interchange.
  Aperio_Digital_Slides_and_Third-party_data_interchange.pdf
- PerkinElmer image format.
  https://downloads.openmicroscopy.org/images/Vectra-QPTIFF/perkinelmer/PKI_Image%20Format.docx
- NDTiffStorage. https://github.com/micro-manager/NDTiffStorage
- Argos AVS File Format.
  https://github.com/user-attachments/files/15580286/ARGOS.AVS.File.Format.pdf

Examples
--------

Write a NumPy array to a single-page RGB TIFF file:

>>> import numpy
>>> data = numpy.random.randint(0, 255, (256, 256, 3), 'uint8')
>>> imwrite('temp.tif', data, photometric='rgb')

Read the image from the TIFF file as NumPy array:

>>> image = imread('temp.tif')
>>> image.shape
(256, 256, 3)

Use the `photometric` and `planarconfig` arguments to write a 3x3x3 NumPy
array to an interleaved RGB, a planar RGB, or a 3-page grayscale TIFF:

>>> data = numpy.random.randint(0, 255, (3, 3, 3), 'uint8')
>>> imwrite('temp.tif', data, photometric='rgb')
>>> imwrite('temp.tif', data, photometric='rgb', planarconfig='separate')
>>> imwrite('temp.tif', data, photometric='minisblack')

Use the `extrasamples` argument to specify how extra components are
interpreted, for example, for an RGBA image with unassociated alpha channel:

>>> data = numpy.random.randint(0, 255, (256, 256, 4), 'uint8')
>>> imwrite('temp.tif', data, photometric='rgb', extrasamples=['unassalpha'])

Write a 3-dimensional NumPy array to a multi-page, 16-bit grayscale TIFF file:

>>> data = numpy.random.randint(0, 2**12, (64, 301, 219), 'uint16')
>>> imwrite('temp.tif', data, photometric='minisblack')

Read the whole image stack from the multi-page TIFF file as NumPy array:

>>> image_stack = imread('temp.tif')
>>> image_stack.shape
(64, 301, 219)
>>> image_stack.dtype
dtype('uint16')

Read the image from the first page in the TIFF file as NumPy array:

>>> image = imread('temp.tif', key=0)
>>> image.shape
(301, 219)

Read images from a selected range of pages:

>>> images = imread('temp.tif', key=range(4, 40, 2))
>>> images.shape
(18, 301, 219)

Iterate over all pages in the TIFF file and successively read images:

>>> with TiffFile('temp.tif') as tif:
...     for page in tif.pages:
...         image = page.asarray()
...

Get information about the image stack in the TIFF file without reading
any image data:

>>> tif = TiffFile('temp.tif')
>>> len(tif.pages)  # number of pages in the file
64
>>> page = tif.pages[0]  # get shape and dtype of image in first page
>>> page.shape
(301, 219)
>>> page.dtype
dtype('uint16')
>>> page.axes
'YX'
>>> series = tif.series[0]  # get shape and dtype of first image series
>>> series.shape
(64, 301, 219)
>>> series.dtype
dtype('uint16')
>>> series.axes
'QYX'
>>> tif.close()

Inspect the "XResolution" tag from the first page in the TIFF file:

>>> with TiffFile('temp.tif') as tif:
...     tag = tif.pages[0].tags['XResolution']
...
>>> tag.value
(1, 1)
>>> tag.name
'XResolution'
>>> tag.code
282
>>> tag.count
1
>>> tag.dtype
<DATATYPE.RATIONAL: 5>

Iterate over all tags in the TIFF file:

>>> with TiffFile('temp.tif') as tif:
...     for page in tif.pages:
...         for tag in page.tags:
...             tag_name, tag_value = tag.name, tag.value
...

Overwrite the value of an existing tag, for example, XResolution:

>>> with TiffFile('temp.tif', mode='r+') as tif:
...     _ = tif.pages[0].tags['XResolution'].overwrite((96000, 1000))
...

Write a 5-dimensional floating-point array using BigTIFF format, separate
color components, tiling, Zlib compression level 8, horizontal differencing
predictor, and additional metadata:

>>> data = numpy.random.rand(2, 5, 3, 301, 219).astype('float32')
>>> imwrite(
...     'temp.tif',
...     data,
...     bigtiff=True,
...     photometric='rgb',
...     planarconfig='separate',
...     tile=(32, 32),
...     compression='zlib',
...     compressionargs={'level': 8},
...     predictor=True,
...     metadata={'axes': 'TZCYX'},
... )

Write a 10 fps time series of volumes with xyz voxel size 2.6755x2.6755x3.9474
micron^3 to an ImageJ hyperstack formatted TIFF file:

>>> volume = numpy.random.randn(6, 57, 256, 256).astype('float32')
>>> image_labels = [f'{i}' for i in range(volume.shape[0] * volume.shape[1])]
>>> imwrite(
...     'temp.tif',
...     volume,
...     imagej=True,
...     resolution=(1.0 / 2.6755, 1.0 / 2.6755),
...     metadata={
...         'spacing': 3.947368,
...         'unit': 'um',
...         'finterval': 1 / 10,
...         'fps': 10.0,
...         'axes': 'TZYX',
...         'Labels': image_labels,
...     },
... )

Read the volume and metadata from the ImageJ hyperstack file:

>>> with TiffFile('temp.tif') as tif:
...     volume = tif.asarray()
...     axes = tif.series[0].axes
...     imagej_metadata = tif.imagej_metadata
...
>>> volume.shape
(6, 57, 256, 256)
>>> axes
'TZYX'
>>> imagej_metadata['slices']
57
>>> imagej_metadata['frames']
6

Memory-map the contiguous image data in the ImageJ hyperstack file:

>>> memmap_volume = memmap('temp.tif')
>>> memmap_volume.shape
(6, 57, 256, 256)
>>> del memmap_volume

Create a TIFF file containing an empty image and write to the memory-mapped
NumPy array (note: this does not work with compression or tiling):

>>> memmap_image = memmap(
...     'temp.tif', shape=(256, 256, 3), dtype='float32', photometric='rgb'
... )
>>> type(memmap_image)
<class 'numpy.memmap'>
>>> memmap_image[255, 255, 1] = 1.0
>>> memmap_image.flush()
>>> del memmap_image

Write two NumPy arrays to a multi-series TIFF file (note: other TIFF readers
will not recognize the two series; use the OME-TIFF format for better
interoperability):

>>> series0 = numpy.random.randint(0, 255, (32, 32, 3), 'uint8')
>>> series1 = numpy.random.randint(0, 255, (4, 256, 256), 'uint16')
>>> with TiffWriter('temp.tif') as tif:
...     tif.write(series0, photometric='rgb')
...     tif.write(series1, photometric='minisblack')
...

Read the second image series from the TIFF file:

>>> series1 = imread('temp.tif', series=1)
>>> series1.shape
(4, 256, 256)

Successively write the frames of one contiguous series to a TIFF file:

>>> data = numpy.random.randint(0, 255, (30, 301, 219), 'uint8')
>>> with TiffWriter('temp.tif') as tif:
...     for frame in data:
...         tif.write(frame, contiguous=True)
...

Append an image series to the existing TIFF file (note: this does not work
with ImageJ hyperstack or OME-TIFF files):

>>> data = numpy.random.randint(0, 255, (301, 219, 3), 'uint8')
>>> imwrite('temp.tif', data, photometric='rgb', append=True)

Create a TIFF file from a generator of tiles:

>>> data = numpy.random.randint(0, 2**12, (31, 33, 3), 'uint16')
>>> def tiles(data, tileshape):
...     for y in range(0, data.shape[0], tileshape[0]):
...         for x in range(0, data.shape[1], tileshape[1]):
...             yield data[y : y + tileshape[0], x : x + tileshape[1]]
...
>>> imwrite(
...     'temp.tif',
...     tiles(data, (16, 16)),
...     tile=(16, 16),
...     shape=data.shape,
...     dtype=data.dtype,
...     photometric='rgb',
... )

Write a multi-dimensional, multi-resolution (pyramidal), multi-series OME-TIFF
file with optional metadata. Sub-resolution images are written to SubIFDs.
Limit parallel encoding to 2 threads. Write a thumbnail image as a separate
image series:

>>> data = numpy.random.randint(0, 255, (8, 2, 512, 512, 3), 'uint8')
>>> subresolutions = 2
>>> pixelsize = 0.29  # micrometer
>>> with TiffWriter('temp.ome.tif', bigtiff=True) as tif:
...     metadata = {
...         'axes': 'TCYXS',
...         'SignificantBits': 8,
...         'TimeIncrement': 0.1,
...         'TimeIncrementUnit': 's',
...         'PhysicalSizeX': pixelsize,
...         'PhysicalSizeXUnit': 'µm',
...         'PhysicalSizeY': pixelsize,
...         'PhysicalSizeYUnit': 'µm',
...         'Channel': {'Name': ['Channel 1', 'Channel 2']},
...         'Plane': {'PositionX': [0.0] * 16, 'PositionXUnit': ['µm'] * 16},
...         'Description': 'A multi-dimensional, multi-resolution image',
...         'MapAnnotation': {  # for OMERO
...             'Namespace': 'openmicroscopy.org/PyramidResolution',
...             '1': '256 256',
...             '2': '128 128',
...         },
...     }
...     options = dict(
...         photometric='rgb',
...         tile=(128, 128),
...         compression='jpeg',
...         resolutionunit='CENTIMETER',
...         maxworkers=2,
...     )
...     tif.write(
...         data,
...         subifds=subresolutions,
...         resolution=(1e4 / pixelsize, 1e4 / pixelsize),
...         metadata=metadata,
...         **options,
...     )
...     # write pyramid levels to the two subifds
...     # in production use resampling to generate sub-resolution images
...     for level in range(subresolutions):
...         mag = 2 ** (level + 1)
...         tif.write(
...             data[..., ::mag, ::mag, :],
...             subfiletype=1,
...             resolution=(1e4 / mag / pixelsize, 1e4 / mag / pixelsize),
...             **options,
...         )
...     # add a thumbnail image as a separate series
...     # it is recognized by QuPath as an associated image
...     thumbnail = (data[0, 0, ::8, ::8] >> 2).astype('uint8')
...     tif.write(thumbnail, metadata={'Name': 'thumbnail'})
...

Access the image levels in the pyramidal OME-TIFF file:

>>> baseimage = imread('temp.ome.tif')
>>> second_level = imread('temp.ome.tif', series=0, level=1)
>>> with TiffFile('temp.ome.tif') as tif:
...     baseimage = tif.series[0].asarray()
...     second_level = tif.series[0].levels[1].asarray()
...     number_levels = len(tif.series[0].levels)  # includes base level
...

Iterate over and decode single JPEG compressed tiles in the TIFF file:

>>> with TiffFile('temp.ome.tif') as tif:
...     fh = tif.filehandle
...     for page in tif.pages:
...         for index, (offset, bytecount) in enumerate(
...             zip(page.dataoffsets, page.databytecounts)
...         ):
...             _ = fh.seek(offset)
...             data = fh.read(bytecount)
...             tile, indices, shape = page.decode(
...                 data, index, jpegtables=page.jpegtables
...             )
...

Use Zarr to read parts of the tiled, pyramidal images in the TIFF file:

>>> import zarr
>>> store = imread('temp.ome.tif', aszarr=True)
>>> z = zarr.open(store, mode='r')
>>> z
<Group ZarrTiffStore>
>>> z['0']  # base layer
 <Array ZarrTiffStore/0 shape=(8, 2, 512, 512, 3) dtype=uint8>
>>> z['0'][2, 0, 128:384, 256:].shape  # read a tile from the base layer
(256, 256, 3)
>>> store.close()

Load the base layer from the Zarr store as a dask array:

>>> import dask.array
>>> store = imread('temp.ome.tif', aszarr=True)
>>> dask.array.from_zarr(store, '0', zarr_format=2)
dask.array<...shape=(8, 2, 512, 512, 3)...chunksize=(1, 1, 128, 128, 3)...
>>> store.close()

Write the Zarr store to a fsspec ReferenceFileSystem in JSON format:

>>> store = imread('temp.ome.tif', aszarr=True)
>>> store.write_fsspec('temp.ome.tif.json', url='file://')
>>> store.close()

Open the fsspec ReferenceFileSystem as a Zarr group:

>>> from kerchunk.utils import refs_as_store
>>> import imagecodecs.numcodecs
>>> imagecodecs.numcodecs.register_codecs(verbose=False)
>>> z = zarr.open(refs_as_store('temp.ome.tif.json'), mode='r')
>>> z
<Group <FsspecStore(ReferenceFileSystem, /)>>

Create an OME-TIFF file containing an empty, tiled image series and write
to it via the Zarr interface (note: this does not work with compression):

>>> imwrite(
...     'temp2.ome.tif',
...     shape=(8, 800, 600),
...     dtype='uint16',
...     photometric='minisblack',
...     tile=(128, 128),
...     metadata={'axes': 'CYX'},
... )
>>> store = imread('temp2.ome.tif', mode='r+', aszarr=True)
>>> z = zarr.open(store, mode='r+')
>>> z
<Array ZarrTiffStore shape=(8, 800, 600) dtype=uint16>
>>> z[3, 100:200, 200:300:2] = 1024
>>> store.close()

Read images from a sequence of TIFF files as NumPy array using two I/O worker
threads:

>>> imwrite('temp_C001T001.tif', numpy.random.rand(64, 64))
>>> imwrite('temp_C001T002.tif', numpy.random.rand(64, 64))
>>> image_sequence = imread(
...     ['temp_C001T001.tif', 'temp_C001T002.tif'], ioworkers=2, maxworkers=1
... )
>>> image_sequence.shape
(2, 64, 64)
>>> image_sequence.dtype
dtype('float64')

Read an image stack from a series of TIFF files with a file name pattern
as NumPy or Zarr arrays:

>>> image_sequence = TiffSequence('temp_C0*.tif', pattern=r'_(C)(\d+)(T)(\d+)')
>>> image_sequence.shape
(1, 2)
>>> image_sequence.axes
'CT'
>>> data = image_sequence.asarray()
>>> data.shape
(1, 2, 64, 64)
>>> store = image_sequence.aszarr()
>>> zarr.open(store, mode='r', ioworkers=2, maxworkers=1)
<Array ZarrFileSequenceStore shape=(1, 2, 64, 64) dtype=float64>
>>> image_sequence.close()

Write the Zarr store to a fsspec ReferenceFileSystem in JSON format:

>>> store = image_sequence.aszarr()
>>> store.write_fsspec('temp.json', url='file://')

Open the fsspec ReferenceFileSystem as a Zarr array:

>>> from kerchunk.utils import refs_as_store
>>> import tifffile.numcodecs
>>> tifffile.numcodecs.register_codec()
>>> zarr.open(refs_as_store('temp.json'), mode='r')
<Array <FsspecStore(ReferenceFileSystem, /)> shape=(1, 2, 64, 64) ...>

Inspect the TIFF file from the command line::

    $ python -m tifffile temp.ome.tif

    )annotationsz	2025.6.11)K__version__TiffFileTiffFileError	TiffFrameTiffPage	TiffPagesTiffPageSeries
TiffReaderTiffSequenceTiffTagTiffTagsTiffTagRegistry
TiffWriter
TiffFormatimreadimshowimwritelsm2binmemmapread_ndtiff_indexread_gdal_structural_metadataread_micromanager_metadataread_scanimage_metadatatiff2fsspectiffcommentTIFFDATATYPE	CHUNKMODECOMPRESSIONEXTRASAMPLEFILETYPE	FILLORDER	OFILETYPEORIENTATIONPHOTOMETRICPLANARCONFIG	PREDICTORRESUNITSAMPLEFORMATOmeXmlOmeXmlError	FileCache
FileHandleFileSequenceStoredShapeTiledSequenceNullContextTimeraskopenfilenameastypecreate_outputenumargenumstrformat_sizehexdumpimagej_descriptionimagej_metadata_tagloggermatlabstr2pynatural_sortednullfuncparse_filenamesparse_kwargspformatproduct	repeat_ndreshape_axes
reshape_ndstrptimetranspose_axesupdate_kwargsvalidate_jhovexml2dict_TIFF	stripnullN)CallableIterableMappingSequence)ThreadPoolExecutor)datetime)	timedelta)cached_property   _imagecodecs)IOTYPE_CHECKINGcastfinaloverload)
Collection	ContainerIterator)AnyLiteralOptionalUnion)	ArrayLike	DTypeLikeNDArray><.)	selectionaszarrkeyserieslevelsqueeze
maxworkers
buffersizemodenameoffsetsizepattern	axesorder
categoriesr   sort	container
chunkshapedtype	axestiled	ioworkers	chunkmode	fillvaluezattrsmultiscalesomexmloutout_inplace
_multifile
_useframesfilesYstr | os.PathLike[Any] | FileHandle | IO[bytes] | Sequence[str | os.PathLike[Any]] | Nonerl   
Any | Nonerm   Literal[False]rn   "int | slice | Iterable[int] | Nonero   
int | Nonerp   rq   bool | Nonerr   rs   rt   Literal['r', 'r+'] | Noneru   
str | Nonerv   rw   rx   ry   Sequence[int] | Nonerz    dict[str, dict[str, int]] | Noner   "Callable[..., NDArray[Any]] | Noner{    Callable[..., Any] | bool | Noner|   str | os.PathLike[Any] | Noner}   tuple[int, ...] | Noner~   DTypeLike | Noner   1dict[int, int] | Sequence[tuple[int, int]] | Noner   r   CHUNKMODE | int | str | Noner   int | float | Noner   dict[str, Any] | Noner   r   r   
OutputTyper   r   r   kwargsrb   returnNDArray[Any]c                   d S N )!r   rl   rm   rn   ro   rp   rq   rr   rs   rt   ru   rv   rw   rx   ry   rz   r   r{   r|   r}   r~   r   r   r   r   r   r   r   r   r   r   r   r   s!                                    Q/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/tifffile/tifffile.pyr   r     s
    V 3    )rl   rn   ro   rp   rq   rr   rs   rt   ru   rv   rw   rx   ry   rz   r   
imreadargsr{   r|   r}   
chunkdtyper   r   r   r   r   r   r   r   r   r   r   Literal[True]r   r   %ZarrTiffStore | ZarrFileSequenceStorec                    d S r   r   "r   rl   rm   rn   ro   rp   rq   rr   rs   rt   ru   rv   rw   rx   ry   rz   r   r   r{   r|   r}   r   r   r   r   r   r   r   r   r   r   r   r   r   s"                                     r   r   r     s
    X -0Cr   F) rl   rm   rn   ro   rp   rq   rr   rs   rt   ru   rv   rw   rx   ry   rz   r   r   r{   r|   r}   r   r   r   r   r   r   r   r   r   r   r   r   bool4NDArray[Any] | ZarrTiffStore | ZarrFileSequenceStorec                    d S r   r   r   s"                                     r   r   r     s
    X <?3r   c                $   |p|du}t          |!gd |!D             R  }"|1|!r/t          dd                    d |!D                       z             |et          | t                    rd| v sd| v rt          j        |           } | st          d          t          | t                    r0t          | t                    st          |           d	k    r| d
         } t          | t                    st          | t                    st          | f|	|
||||| d|"5 }#|rh|t          |t                    sJ |#                    ||||||||||
  
        }$||$cddd           S d	dlm}%  |%|$||          cddd           S |#                    |||||||          cddd           S # 1 swxY w Y   n+t          | t          t           f          rt          d          t#          d||||||||| d	|"|!}&t%          | f|||||dt#          |          5 }'|rE |'j        d|||||||d|&}$||$cddd           S d	dlm}%  |%|$||          cddd           S  |'j        d||||||d|&cddd           S # 1 swxY w Y   dS )a,	  Return image from TIFF file(s) as NumPy array or Zarr store.

    The first image series in the file(s) is returned by default.

    Parameters:
        files:
            File name, seekable binary stream, glob pattern, or sequence of
            file names. May be *None* if `container` is specified.
        selection:
            Subset of image to be extracted.
            If not None, a Zarr array is created, indexed with the
            `selection` value, and returned as a NumPy array. Only segments
            that are part of the selection will be read from file.
            Refer to the Zarr documentation for valid selections.
            Depending on selection size, image size, and storage properties,
            it may be more efficient to read the whole image from file and
            then index it.
        aszarr:
            Return file sequences, series, or single pages as Zarr store
            instead of NumPy array if `selection` is None.
        mode, name, offset, size, omexml, _multifile, _useframes:
            Passed to :py:class:`TiffFile`.
        key, series, level, squeeze, maxworkers, buffersize:
            Passed to :py:meth:`TiffFile.asarray`
            or :py:meth:`TiffFile.aszarr`.
        imread, container, sort, pattern, axesorder, axestiled, categories:
            Passed to :py:class:`FileSequence`.
        chunkmode, fillvalue, zattrs, multiscales:
            Passed to :py:class:`ZarrTiffStore`
            or :py:class:`ZarrFileSequenceStore`.
        chunkshape, chunkdtype, ioworkers:
            Passed to :py:meth:`FileSequence.asarray` or
            :py:class:`ZarrFileSequenceStore`.
        out_inplace:
            Passed to :py:meth:`FileSequence.asarray`
        out:
            Passed to :py:meth:`TiffFile.asarray`,
            :py:meth:`FileSequence.asarray`, or :py:func:`zarr_selection`.
        imreadargs:
            Additional arguments passed to :py:attr:`FileSequence.imread`.
        **kwargs:
            Additional arguments passed to :py:class:`TiffFile` or
            :py:attr:`FileSequence.imread`.

    Returns:
        Images from specified files, series, or pages.
        Zarr store instances must be closed after use.
        See :py:meth:`TiffPage.asarray` for operations that are applied
        (or not) to the image data stored in the file.

    Nc              3  6   K   | ]}|d d         dk    |V  d S N   is_r   ).0ks     r   	<genexpr>zimread.<locals>.<genexpr>  s.      %J%JA1RaR5E>>a>>>>%J%Jr   z*imread() got unexpected keyword arguments , c              3  "   K   | ]
}d | d V  dS )'Nr   )r   rn   s     r   r   zimread.<locals>.<genexpr>  s*      55s
C


555555r   *?no files foundrW   r   )rt   ru   rv   rw   r   r   r   )
rn   ro   rp   rq   rr   rs   r   r   r   r   )zarr_selectionr   )rn   ro   rp   rq   rr   rs   r   zBinaryIO not supported)	rn   ro   rp   rq   rr   rs   r   r   r   )rx   ry   rz   r|   r{   r   )r   r   r}   r   r   r   r   )r   r}   r   r   r   r   r   )rB   	TypeErrorjoin
isinstancestrglob
ValueErrorrR   lenr   intrm   zarrr   asarrayr.   rZ   kwargs_notnoner   )(r   rl   rm   rn   ro   rp   rq   rr   rs   rt   ru   rv   rw   rx   ry   rz   r   r   r{   r|   r}   r   r   r   r   r   r   r   r   r   r   r   r   r   is_flagstifstorer   imread_kwargsimseqs(                                           r   r   r   @  s   @ .	-FFK%J%J%J%J%JKKKH~&~8ii55f555556
 
 	

 eS!! 	%se||se||Ie$$E 	/-... uh''	uc**	 E

a!HEeS!! (	E8)D)D (	
%%
 
 
 
 '  E;*S#*>*>;;;JJ%# '#-#-"+"+%$/ '  E !($5' ' ' ' ' ' ' '8 544444)>%DDD=' ' ' ' ' ' ' '> {{!#)) #  ?' ' ' ' ' ' ' ' ' ' ' ' ' ' ' 'R 
EJ+	,	, 31222"     M 


 
 
'
'
'
 
 "
 
 	= EL 	##%%##	 	  	 	E  +"
 "
 "
 "
 "
 "
 "
 "
. -,,,,,!>%<<<3"
 "
 "
 "
 "
 "
 "
 "
4 u} 
!!#
 
 
 
5"
 "
 "
 "
 "
 "
 "
 "
 "
 "
 "
 "
 "
 "
 "
 "
 "
 "
s<   >F-%F-F--F14F1JJ%JJ	J	)%rt   bigtiff	byteorderimagejomeshapedappendshaper~   photometricplanarconfigextrasamples
volumetrictilerowsperstripbitspersamplecompressioncompressionargs	predictorsubsampling
jpegtables
iccprofilecolormapdescriptionrT   
resolutionresolutionunitsubfiletypesoftwaremetadata	extratags
contiguoustruncatealignrr   rs   returnoffsetdata`ArrayLike | Iterator[NDArray[Any] | None] | Iterator[bytes] | Iterator[tuple[bytes, int]] | Nonefile/str | os.PathLike[Any] | FileHandle | IO[bytes]Literal['w', 'x', 'r+'] | Noner   r   ByteOrder | Noner   r   r   r   r   r   PHOTOMETRIC | int | str | Noner   PLANARCONFIG | int | str | Noner   (Sequence[EXTRASAMPLE | int | str] | Noner   r   r   r   r   COMPRESSION | int | str | Noner   r   #PREDICTOR | int | str | bool | Noner   tuple[int, int] | Noner   bytes | Noner   r   ArrayLike | Noner   str | bytes | NonerT   str | bool | DateTime | Noner   >tuple[float | tuple[int, int], float | tuple[int, int]] | Noner   RESUNIT | int | str | Noner   FILETYPE | int | Noner   str | bytes | bool | Noner   r   Sequence[TagTuple] | Noner   r   r   r   c      %   
     X   |W|	|
t          d          t          j        |
          }
t          |	          }	t	          |	          |
j        z  }'||
j        }n)	 |j        }'||j        j        }n# t          $ r d}'Y nw xY w||'dk    o	| o|" o|dv }t          | |||||||          5 }( |(j
        |fi d|	d|
d	|d
|d|d|d|d|d|d|d|d|d|d|d|d|d|d|d|d|d|d|d|d| d|!d |"d!|#d"|$d#|%d$|&})ddd           n# 1 swxY w Y   |)S )%a=  Write NumPy array to TIFF file.

    A BigTIFF file is written if the data size is larger than 4 GB less
    32 MB for metadata, and `bigtiff` is not *False*, and `imagej`,
    `truncate` and `compression` are not enabled.
    Unless `byteorder` is specified, the TIFF file byte order is determined
    from the dtype of `data` or the `dtype` argument.

    Parameters:
        file:
            Passed to :py:class:`TiffWriter`.
        data, shape, dtype:
            Passed to :py:meth:`TiffWriter.write`.
        mode, append, byteorder, bigtiff, imagej, ome, shaped:
            Passed to :py:class:`TiffWriter`.
        photometric, planarconfig, extrasamples, volumetric, tile,        rowsperstrip, bitspersample, compression, compressionargs, predictor,        subsampling, jpegtables, iccprofile, colormap, description, datetime,        resolution, resolutionunit, subfiletype, software,        metadata, extratags, maxworkers, buffersize,         contiguous, truncate, align:
            Passed to :py:meth:`TiffWriter.write`.
        returnoffset:
            Return offset and number of bytes of memory-mappable image data
            in file.

    Returns:
        If `returnoffset` is *True* and the image data in the file are
        memory-mappable, the offset and number of bytes of the image
        data in the file.

    Nz,missing required 'shape' or 'dtype' argumentr   l      | >   NNONENonenoner   rW   rt   r   r   r   r   r   r   r   r~   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rT   r   r   r   r   r   r   r   r   r   rr   rs   r   )r   numpyr~   tuplerD   itemsizer   nbytes	Exceptionr   write)*r   r   rt   r   r   r   r   r   r   r   r~   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rT   r   r   r   r   r   r   r   r   r   rr   rs   r   datasizer   results*                                             r   r   r     s   h |=EMKLLLE""e5>>EN2I	{H  J0	 	 	 	HHH	 }$ D
DD CC	 	 
	
 	
 	
 *
 
 
  
  
% 
 % 
 $	 

 & 
 & 
 "z 
  
 & 
 (- 
 $ 
 ,O 
  i 
 $ 
 "z 
  "z! 
" X# 
$ $% 
& X' 
( "z) 
* *>+ 
, $- 
. X/ 
0 X1 
2  i3 
4 "z5 
6 X7 
8 %9 
: "z; 
< "z= 
> &? 
*
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
V Ms%   A1 1B ?B ,A'DD#&D#r+)r   r~   pagero   rp   rt   filenamestr | os.PathLike[Any]r  r   Literal['r+', 'r', 'c']numpy.memmap[Any, Any]c                 t          j        |           } |t          |          }||~t          j        |          }d|v r|                    |d                   }|                    d||t          j        d           t          | fi |}|t          d          |d         }	nt          | fi |5 }
|D|
j        |         j        |         }|j        t          d          |j        }|j        }|j        }	nB|
j        |         }|j        st          d          |j        d         }	|j        }|j        }|J t          j        |
j        |j        z             }ddd           n# 1 swxY w Y   t          j        | |||	|d          S )ag  Return memory-mapped NumPy array of image data stored in TIFF file.

    Memory-mapping requires the image data stored in native byte order,
    without tiling, compression, predictors, etc.
    If `shape` and `dtype` are provided, existing files are overwritten or
    appended to depending on the `append` argument.
    Else, the image data of a specified page or series in an existing
    file are memory-mapped. By default, the image data of the first
    series are memory-mapped.
    Call `flush` to write any changes in the array to the file.

    Parameters:
        filename:
            Name of TIFF file which stores array.
        shape:
            Shape of empty array.
        dtype:
            Datatype of empty array.
        page:
            Index of page which image data to memory-map.
        series:
            Index of page series which image data to memory-map.
        level:
            Index of pyramid level which image data to memory-map.
        mode:
            Memory-map file open mode. The default is 'r+', which opens
            existing file for reading and writing.
        **kwargs:
            Additional arguments passed to :py:func:`imwrite` or
            :py:class:`TiffFile`.

    Returns:
        Image in TIFF file as memory-mapped NumPy array.

    Raises:
        ValueError: Image data in TIFF file are not memory-mappable.

    Nr   T)r   r   r~   r   r   z"image data are not memory-mappabler   C)osfspathr  r  r~   newbyteorderupdater   ALLOCATIONGRANULARITYr   r   r   ro   levels
dataoffsetr   pagesis_memmappabledataoffsetsr   charr   )r  r   r~   r  ro   rp   rt   r   r  rv   r   
tiffseriestiffpages                r   r   r     s   d y""HeU.E""&  &&vk':;;E, 	 	
 	
 	
 ,,V,,>ABBB h))&)) 	<S| Z/6u=
(0$%IJJJ"("(#.9T?. K$%IJJJ!-a0  (((K
 :;;E!	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	<" <%vucBBBs   5B*E++E/2E/c                      e Zd ZdZdS )r   z-Exception to indicate invalid TIFF structure.N__name__
__module____qualname____doc__r   r   r   r   r     s        7777r   r   c            !         e Zd ZU dZded<   	 ded<   ded<   ded	<   d
ed<   d
ed<   d
ed<   ded<   ded<   ded<   ded<   ded<   ded<   ded<   ded<   ded<   ded <   ded!<   ded"<   d#ed$<   d#ed%<   ded&<   d'ed(<   d)d*d)d*d*d)d)d+dd:Z	 dd)d)d)d)d)d*d)d)d)d)d)d)d)d)d)d)d)d)d)d)d)d)d)i d)d*d*d)d)d)d*d;ddoZddqZddrZe	dds            Z
ddtZdduZ	 ddd~ZddZddZedd            ZddZddZddZd)S )r   a  Write NumPy arrays to TIFF file.

    TiffWriter's main purpose is saving multi-dimensional NumPy arrays in
    TIFF containers, not to create any possible TIFF format.
    Specifically, ExifIFD and GPSIFD tags are not supported.

    TiffWriter instances must be closed with :py:meth:`TiffWriter.close`,
    which is automatically called when using the 'with' context manager.

    TiffWriter instances are not thread-safe. All attributes are read-only.

    Parameters:
        file:
            Specifies file to write.
        mode:
            Binary file open mode if `file` is file name.
            The default is 'w', which opens files for writing, truncating
            existing files.
            'x' opens files for exclusive creation, failing on existing files.
            'r+' opens files for updating, enabling `append`.
        bigtiff:
            Write 64-bit BigTIFF formatted file, which can exceed 4 GB.
            By default, a classic 32-bit TIFF file is written, which is
            limited to 4 GB.
            If `append` is *True*, the existing file's format is used.
        byteorder:
            Endianness of TIFF format. One of '<', '>', '=', or '|'.
            The default is the system's native byte order.
        append:
            If `file` is existing standard TIFF file, append image data
            and tags to file.
            Parameters `bigtiff` and `byteorder` set from existing file.
            Appending does not scale well with the number of pages already in
            the file and may corrupt specifically formatted TIFF files such as
            OME-TIFF, LSM, STK, ImageJ, or FluoView.
        imagej:
            Write ImageJ hyperstack compatible file if `ome` is not enabled.
            This format can handle data types uint8, uint16, or float32 and
            data shapes up to 6 dimensions in TZCYXS order.
            RGB images (S=3 or S=4) must be `uint8`.
            ImageJ's default byte order is big-endian, but this
            implementation uses the system's native byte order by default.
            ImageJ hyperstacks do not support BigTIFF or compression.
            The ImageJ file format is undocumented.
            Use FIJI's Bio-Formats import function for compressed files.
        ome:
            Write OME-TIFF compatible file.
            By default, the OME-TIFF format is used if the file name extension
            contains '.ome.', `imagej` is not enabled, and the `description`
            argument in the first call of :py:meth:`TiffWriter.write` is not
            specified.
            The format supports multiple, up to 9 dimensional image series.
            The default axes order is TZC(S)YX(S).
            Refer to the OME model for restrictions of this format.
        shaped:
            Write tifffile "shaped" compatible file.
            The shape of multi-dimensional images is stored in JSON format in
            a ImageDescription tag of the first page of a series.
            This is the default format used by tifffile unless `imagej` or
            `ome` are enabled or ``metadata=None`` is passed to
            :py:meth:`TiffWriter.write`.

    Raises:
        ValueError:
            The TIFF file cannot be appended to. Use ``append='force'`` to
            force appending, which may result in a corrupted file.

    r   tiffr.   _fhzOmeXml | None_omexmlr   _omer   _imagej	_tifffile	_truncater   	_metadataNDArray[numpy.uint16] | None	_colormapz)list[tuple[int, bytes, Any, bool]] | None_tagsr   
_datashapenumpy.dtype[Any] | None
_datadtyper   _dataoffsetlist[int] | None_databytecounts_dataoffsetstagTiffTag | None_descriptiontagr   
_ifdoffset_subifds_subifdslevel	list[int]_subifdsoffsets_nextifdoffsets	_ifdindexzStoredShape | None_storedshapeNFr
  r   r   rt   r   r   r   r   r   
bool | strr   r   r   r   r  c                 |dv s t          |t                    r|j        dk    rd}d}|r	 t          |dd          5 }	|	                                }
	 t	          |	          5 }|dk    r|j        st          d	          |j        }|j        }t          t          |j        j                  | _        d d d            n# 1 swxY w Y   |	                    |
           n# |	                    |
           w xY wd}d d d            n# 1 swxY w Y   n# t          t           f$ r d
}Y nw xY w|r|dvrt          d          d}n|d}||dv rt"          j        dk    rdnd}n|dvrt          d|           |dk    r |rt$          j        nt$          j        | _        n|rt$          j        nt$          j        | _        d
| _        d | _        d | _        d | _        d | _        d | _        d | _        d | _        d | _         d | _!        d| _"        d| _#        g | _$        g | _%        d| _&        d | _'        d | _(        t          ||d          | _)        |r&| j)                            dtT          j+                   n|J | j)        ,                    |dk    rdnd           |r3| j)        ,                    t[          j.        |dz   ddd                     n0| j)        ,                    t[          j.        |dz   d                     | j)                                        | _        | j)        ,                    t[          j.        | j        j/        d                     |d nta          |          | _1        | j1        rd
nta          |          | _2        | j2        rd
| _1        | j1        s| j2        rd
| _3        n|dnta          |          | _3        |r!|r!ti          j5        | dtl                     d S d S d S )N>   r  r+brM  r  Trbr   )rt   rw   forcez)cannot append to file containing metadataF>   Nr  rM  zappend mode must be 'r+'w>   =|littlerk   rj   >   rk   rj   zinvalid byteorder    II   MMHHH+      H*   z% writing nonconformant BigTIFF ImageJ)7r   r.   _modetellr   is_appendabler   r   
is_bigtiffr\   r   r"  next_page_offsetrC  seekOSErrorFileNotFoundErrorsysr   BIG_LE
CLASSIC_LEr/  BIG_BE
CLASSIC_BEr5  r6  r8  r9  r:  r<  r=  r?  r@  rB  rD  rE  rG  rH  rI  r1  rJ  r0  r  SEEK_ENDr  structpackoffsetformatr   r2  r3  r4  warningswarnUserWarning)selfr   rt   r   r   r   r   r   r   fhposr   s               r   __init__zTiffWriter.__init__s  s    =  tZ(( !-1Z5-@-@DF 	4a888 "B''))C%%b\\ 	S%009J0&0$O'" '" !" ),I&)nG.2 #SY%?/ /DO	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 !F" " " " " " " " " " " " " " "  ./     	... !;<<<DD\D	Z 7 7"}88cIIj((=)==>>>'.CDODII'.CDODI
###!! dA666 	CHMM!R[))))(((HNNI$4$455%@@@ Av{9u+<b!QGGHHHHv{9s?B??@@@"hmmooDOHNN6;ty'=qAABBBKDDT#YY	 $	;uutF||< 	DI9 	F 	F"DNN%+^TTfDN 	g 	M@@@+    	 	 	 	sq   D DC $AB?3C ?C	C C	C 
D C77D<D DD DD D*)D*)r   r~   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rT   r   r   r   r   subifdsr   r   r   r   r   rr   rs   r   r   r   r   r   r~   r   r   r   r   r   r   r   r   r   r   r   r   %COMPRESSION | int | str | bool | Noner   r   r   r   r   r   r   r   r   r   r   r   rT   r   r   r  r   r  r   r  r   r  rt  int | Sequence[int] | Noner   r   r  r   r   r   rr   rs   r   c               [   t          d          }!d}"d}#d}$d}%d}&d}'d}(d})d}*| j        }+| j        j        },|O||t	          d          d}"d}#t          |          }-t          j        |                              |,          }.nt          |d          rM||t	          d          |}#t          |          }-t          j        |                              |,          }.nZt          |d          rt          t          j        |          }|}"t          j        |j                                      |,          }.t          |d          st          j        ||.d          }"n4	 |j        j        rt          j        ||.d          }"n# t          $ r Y nw xY w|"j        }-d}#|-t          j        |          |.k    rt	          d	|d
|.           |%||"j        k    rt	          d|d|"j                   nFt          j        |                              |,          }.t          j        ||.d          }"|"j        }-d}#~t#          d |-D                       rt	          d          |.j        dk    }/|/rS|-d         dk    rdnd}0t'          |-d|0                   }1|-|0         dz  r|1|-|0         dz  dz   z  }1n&|1|-|0         dz  z  }1nt'          |-          |.j        z  }1|1dk    r
d}"d}d}
|d}|r?t+          |t,                    s|dv s&t+          |t
          t.          f          r|d         dv rd}|rt+          |t,                    s|dv rd}|-}2|
duo|
|.j        dz  k    }3| j        :| j        2|t          j        ||,dz             }|rK| j        dd         |-k    s8| j        |.k    s-|| j        $| j        |t          j        || j                  sR|                                  | j        rt	          d          | j        h| j        dk     r\| j         J | j!        J  | j        j"        dO| j        | j        | j        d         dk    rdndd         | j         j        d| j!         n6|4| #                                 |+$                    dtJ          j&                   | j'        rm| j(        s|rt	          d          | xj        dz  c_        | j        | j'        k    r$g | _)        g | _*        d| _        d| _'        d| _+        n|rt	          d          d| _        d| _        nx|s|3s|rt	          d          | j        d         dz   f|-z   | _        |+,                                }4|"|+-                    |1           n|+.                    |"|.           | r|4|1fS dS | j/        |d |+j0        v | _/        nd| _/        | j1        s| j        rt-          |          | _(        n|rt	          d!          d| _(        | j(        r|s|3s|rt	          d"          |1dk    rd#}-te          j3        | d$th                     | j        j5        }5| j        j6        }6| j        j7        }7| j        j8        }8tr          j:        }9tr          j;        }:tr          j<        };tr          j=        }<tr          j>        }=t~          j@        }>t~          jA        }?|t          tr          |          }|rt          t~          |          }|&t          d% t          |          D                       }|i }|rt+          |t
          t.          f          rt          d&          t+          |t                    r|F                                }|d'k    rd}nt+          |t,                    rd}t          t          |          jH        }@d}nd}@d}|@dk    ri }n	|@d(v rd|d)<   |J |r|st	          d*          |@t          jJ        v rt	          d+t          |@                    t+          |t,                    r7|.jK        d,k    rd-}An|.jK        d.v r|.j        d/k    rd0}Anwt	          d+|.          t          t          |          }|.jK        d.v r|jH        d1vr|.j        d/k    s|.jK        d,k    r|jH        d2vrt	          d3|d4|.          |jH        }And}A~t          jM        |A         })| j/        ry|te          j3        | d5th                     d}| j        '|t                      | _        nt          dOi || _        |s|r"t          |          d0k    rt	          d6          d}n| j        r|te          j3        | d7th                     d}|.j        d8vrt	          d9|.j                  |s|r"t          |          d0k    rt	          d:          d}|r||;k    nd}B|.j        d;k    r||;k    rt	          d9|.d<          d}B|d}B|d}Cn|P                    d=d          }Ct          |-|B|C>          }D||?k    rt	          d?          |Dd         d@v r|;}n|||.j        d;k    r|=}n|9}d}|Br|>nd}|=t          j        ||,dz             }|| _        | j        rs|j        dAk    rt	          dB          |.j        d;k    r	||9|:hv r|=}n|.j        d;k    r||=k    s3|.j        dCv r||9|:hv s$te          j3        | dD|. dE|th                     d}n|5|.j        dFv r,|=}d}|j        d-d0|.j        dz  z  fk    rt	          dG          nl||=k    rBd}|.j        dFvrt	          dH          |j        d-d0|.j        dz  z  fk    rt	          dG          n$te          j3        | dI|. dE|th                     d}|rdt          |          cxk     rd/k     r2n n/|d         dJz  s$|d         dJz  st#          dK |D                       rt	          dL|           t          dM |D                       }|rt          |          d0k    rdN|z   }t          |          d-k    }ndO}t-          |          }t+          |t
                    sJ t          |-t          jS        P                    |d0                    }t          |          }E|r|Ed-k     rd}|d}F|9}|/r|:}n||>k    r|Ed0k    r|d         d@v r|;}|.j        dFv}Fn||?k    r,|r|Ed-k    r|dP         d@v r|;}d}Fnu|Ed0k    r|dQ         d@v r|;}d}Fn`|Ed0k    r|d         d@v r|;}|>}|.j        dFv}FnB| j        s| j/        r|9}d}n/|r|Ed-k    r|dP         d@v r|;}|?}d}Fn|Ed0k    r|dQ         d@v r|;}|?}d}F|FrA||>k    rdR}GndS}Gte          j3        dT|- dU|. dV|Gd          dW|Gd          dX	t          d0Y           ~G~F~-|J t          jS        |         }H|r!t          |          |rd-nd0k    r
d}|Hdk    r|9}|Hdk    r!t          |          d-k     rt	          dZ|d[          t          |          d/k     rd}|G||;k    r|Hd/h}In|Hh}I|d         |Iv r|>}n,||rdPndQ         |Iv r|?}n|d         ||rdPndQ         k    r|?}n|>}||>k    r7|d         |!_U        |d         |!_V        |dQ         |!_W        |r|dP         |!_X        nD|d         |!_V        |d         |!_W        |r|dQ         |!_X        |dP         |!_Y        n|dQ         |!_Y        |!jZ        |Hk    r|!jZ        |Hz
  |!_[        n|tr          j\        k    rBt          |          d0k    rt	          d\          d}d}|d         |!_V        |d         |!_W        n3|r t          |          |rd-nd0k    r||>k    r|t          |          dk    r7|d         |!_U        |d         |!_V        |dQ         |!_W        |r|dP         |!_X        nd}d|!_U        |d         |!_V        |d         |!_W        |r|dQ         |!_X        nr|d         |!_V        |d         |!_W        |t          |          dk    r+|r|dQ         |!_X        |dP         |!_Y        n&|dQ         |!_Y        nd}d|!_Y        |r|dQ         |!_X        |!jZ        dz
  |!_[        nd}| j1        rQ|s|i k    rIt          |          d0k    r5|d         dk    r)|dd         }t          |          d0k    r|d         dk    )n0| j        r)t          |          d0k    r|d         dk    r
|dd         }t          |          d-k     rd}|s*|d         |!_V        |d         |!_W        |r|dQ         |!_X        nE|d         |!_U        |d         |!_V        |dQ         |!_W        |r|dP         |!_X        |!jZ        dz
  |!_[        |s6|r4t          |          d-k    r!|d         dk    rt	          d]|!d^|           |1|d/z  r,|/r|!jZ        dk    r|d_v st	          d`          tr          j]        }d}3|/r|
|
dk    rt	          da|
db          d}
nI|@dcv r=|
dd|v r	|dd         }
n
|.dek    rdfnd}
d0|
cxk    rdJk    sn t	          da|
dg          n|@dhv rR|
dd|v r	|dd         }
n
|.j        dz  }
|
dddJdi|.j                 k    r|
|.j        dz  k    st	          da|
dj|.          n|
|.j        dz  }
n|.jK        dkk    s|.j        d/k    r#|
|.j        dz  k    rt	          da|
dl|.          |
dddJdi|.j                 k    r|
|.j        dz  k    st	          da|
dj|.          |r"|
|.j        dz  k    rt	          da|
dm          n|
|.j        dz  k    rd}3|!j^        dk    r&|!j_        }J|Jdk    rdnt'          |2          |Jz  |!_^        |1dk    r|!j`        st          dn|!          ||=k    r*|!jZ        dk    s|!j[        dk    rt	          dn|!do          n(|!jZ        |Hk     rt	          dp|dq|H dr|!jZ                   ||!jb        |k    rt	          |ds|!          ~|"|"c                    |!j                  }"g }K|rdt}Ldu}Mndv}Ldw}M|M| _d        | je        }N| jf        }O|dO}| |O|Kdxd0d|d           |si n|g                                | _!        | j        %t          | j        jh                  dk    rdy}nd}n| j        rit          | j!        dzd{d|d}d~ddddddddddd          }Pt          |P|,          D ]}Q |O|Kg|QR   t          |2f|!jU        d@v | j        dud| j!        }|dz  }n| j1        rB|s|i k    r:| j(        r| j!        l                    d           t          |2fi | j!        }|dz  }nU|St+          |t                    s|o                    d          }t          | ddxd0t          |          |d          | _q        d}|d| _1        nL|o                    d          } |O|Kdxd0d|d           t          | ddxd0t          |          |d          | _q        ~|d}|r |O|Kdd0d|d           |rt+          |t                    r/t          |          dk    s|dJ         dk    rt	          d          nQt+          |t                    r|s                    d          }n&t          jt                    s                    d          } |O|Kdd0d|d            |O|Kdd-d|@           |@dk    rZd|vrd}RnA|d         d}Rn6|d         dk    rd}Rn'|d         dk    rd0}Rnt	          d|d                    |O|Kdd/d0d/|Rf           ~R|Adk    r |O|Kdd-d|A            |O|Kdd/d|!jV                    |O|Kdd/d|!jW                   |r* |O|Kdd/d|d                     |O|Kdd/d|d                    |r+ |O|Kdd/d|!jX                   |r |O|Kdd/d|d                    | |O|Kdd/d|           |s| j'        rk| j        dk     r`| j'        r| j'        }n/t          |d          rt          |          }nt          |          }|| _'         |O|Kd|7d/k    rdnd|dg|z             |/s:|.jK        dkk    s/dd0d-dd|.jK                 }S |O|Kdd-|!jZ        |Sf|!jZ        z             | |O|Kdd-|jv        |           | |O|Kddt          |          |            |O|Kdd-d|!jZ                   |/r |!jZ        dk    r |O|Kdd-d|!jb                   nL|!jZ        dk    r2 |O|Kdd-d|!jb                    |O|Kdd-|!jZ        |
f|!jZ        z             n |O|Kdd-d|
           |!j[        dk    r|\|!j[        t          |          k    r't	          d|!j[         dt          |                      |O|Kdd-t          |          |           n=||;k    r|!j[        dk    r |O|Kdd-dd0           n |O|Kdd-|!j[        d|!j[        z             | |O|Kddt          |          |           |@dk    r|!jb        dk    r||;|<hv r |d}n|dvrt	          d|          t          |          dz  }T|r(|d         |Tz  s|d         |Tz  rt	          d|T           |!j[        dk    rt	          d           |O|Kdd-d0|           t          tr          |P                    dd                    }U||d<   |jx        |d<   |Ujx        |d<    |O|Kdd-d|U           |U|<k    r(t          d |D                       r |O|KddddĦ           n|dvr&t                      {                    | d|           d}d}T |O|Kdd-d|jH                   ||<k    r7 |O|Kdd-d0dǦ           t          dȄ |D                       r |O|KddddĦ           |t          t          |          }n"| j        s|t          j}        }nt          j~        }|v |O|Kdddt          |d                               |O|Kdddt          |d                              t          |          d0k    rt	          d˦           |O|Kdd-d|           n- |O|KddddǦ            |O|KddddǦ            |O|Kdd-d|           |p|3p|/ }|rt          |          d0k    r]|!jW        |d         z   dz
  |d         z  |!jV        |d         z   dz
  |d         z  f}V|o!|!jW        |d         k    o|!jV        |d         k    }n|!jX        |d         z   dz
  |d         z  |!jW        |d         z   dz
  |d         z  |!jV        |d0         z   dz
  |d0         z  f}V|o2|!jX        |d         k    o!|!jW        |d         k    o|!jV        |d0         k    }t'          |V          |!jY        z  }Wt'          |          |!jU        z  |.j        z  g|Wz  }X|                     |X|@          }Y |O|K|L|Y|W|X            |O|K|M|6|Wdg|Wz             |W |Y }Y|s<|"t          |"||V          }#n'|#%|s#|3s!|/s|W|!j^        z  |Xd         fdd҄}Z |Z            }#d}	n|r|	|	|!jW        k    r|!jY        |!jX        z  }[|!jW        |!jV        z  |!jU        z  |.j        z  g|[z  }X|                     |X|@          }Y |O|K|L|Y|[|X            |O|K|M|6|[dg|[z              |O|Kdd/d|!jW                   |[ |Y }Y|!jW        }	|[}\n4|!jV        |!jU        z  |.j        z  }]|@dk    r|!jW        }	|	|rd|]z  }	n|!jW        }	|	dk     r|T}	n5|	|!jW        k    r|!jW        }	n"|r |	|Tz  rt          j        |	|Tz            |Tz  }	|	J  |O|Kdd/d|	           |!jW        |	z   dz
  |	z  }^|^|!jY        z  |!jX        z  }\|	|]z  }_|_g|\z  }X|_|]|^|	z  |!jW        z
  z  z
  }`t	          |^dz
  |\|^          D ]}a|`|X|a<   |                     |X|@          }Y |O|K|L|Y|\|X            |O|K|M|6|\dg|\z             |Y|\z  }Y|"|st          |"          }#|#|st	          d֦          dׄ |KD             }b|bl                    t          j                   |D ]B}c|cd         |bv r-t                      {                    | d|cd                     9 |O|Kg|cR   C~b~t          |Kdل ڦ          }Kd}dd}ed}f|#t          |#          \  }g}#t+          |gt
                    r=d}f|g\  }g}ht+          |gt                    s!t	          dېt          |g          dܝ          t+          |gt                    }e|esct          j        |g          }g|r|!jU        dk    r|gj        d         dk    rd}d|gj        j        |.j        k    rt	          d|gj        d|.          nd}g|/r>|@dk    r	|dfdd}i|i}*n|@dv rt          j        |@         |d|fdd}j|j}*ngt          d          |rIt          j        |@         }k|@dk    r|d|d<   |r|k|fdd}*n.|)
|)|k|d|fdd}*n"|r|k|fdd}*n|@dk    r|k}*nd}*n|3r|
|dfdd}*nd}*~|s|es|*d}e|rh||!jU        fz   }lt'          |l          |.j        z  }mt                              ||W|!j^        z  |m|@          }t          |W|!j^        z  |#|*|l|.||d          }#njt                              ||\|!j^        z  |_|@          }t          |#|!j        |.|	          }#t          |\|!j^        z  |#|*|	|!jV        |!jU        f|.||d          }#|+,                                }nd}ot	          |rdn|!j^                  D 	]}p|n}q|qd0z  r|+                    d           |qdz  }q| j        dk     r9|+$                    | j                   |+                     |N|6|q                     |+$                    |q           |pd0k     rd}'t'          j                    }r|r                     |N|5t          |K                               |r,                                }s|r                    d                    d |KD                                  |r,                                }t|r                     |N|6d                     t-          |K          D ]\  }u}v|s|u|8z  z   d/z   |7z   }4|vd         }w|vd0         }x|xr|r,                                }(|(d0z  r|r                    d           |(dz  }(|r$                    |4           |r                     |N|6|q|(z                        |r$                    |(           |r                    |x           |w|Mk    r|4|(f}%|w|Lk    r|4|(f}&|wdxk    r\| jq        S| jq        j        dk    rC|x                    | jq        jH                  r$|q|sz   |u|8z  z   | jq        _        |q|(z   | jq        _        3|wdk    r|4|(f}'?|w|Mk    r|4df}%K|w|Lk    r|4df}&W|wdxk    rf| jq        ]| jq        j        dk    rM| jq        jH        |vd         dPd         v r1|q|sz   |u|8z  z   | jq        _        | jq        j        |7z   d/z   | jq        _        |wdk    r|4df}'|r,                                }y|yd0z  r|r                    d           |ydz  }y|+$                    |ytJ          j                   |+,                                }o|dJ}||o|z  z
  |z  }z|+$                    |ztJ          j                   |o|zz  }o|r|#d}{|er|#D ]}g|{|+                    |g          z  }{~gnI|!j_        |.j        z  }||#D ]7}g|g|{|+-                    ||          z  }{n|{|+.                    |g|.          z  }{~g8|{|1k    rt	          d|{ d|1           n$|"|+-                    |1           n|+.                    |"|.           n|fr|#J dg|r|Wn|\z  }$|o}4t	          |r|Wn|\          D ]l}}t          t
          t          t          f         t7          |#                    \  }g}h|h|X|}<   |4|$|}<   |4t          |g          z  }4|+                    |g           ~gmn^|erg|#J t	          |r|Wn|\          D ]M}}t          t          t7          |#                    }gt          |g          |X|}<   |+                    |g           ~gNn|r|#J ||!jU        fz   }lt'          |l          |.j        z  }mt	          |W          D ]}~t7          |#          }g|gd|X|~<   t          j        |g|.          }g|gj        |mk    r\|gj        |mk    rt	          d          t          d t=          |l|gj                  D                       }t          j        |g|          }g|+.                    |g           ~gnt          d          |%J |%\  }4}(|r$                    |4           |(|r                     |N|6|q|(z                        |r$                    |(           |$4|o}4|XD ].}|r                     |N|6|dk    r|4nd                     |4|z  }4/nD|$D ]!}4|r                     |N|6|4                     "n|r                     |N|6|o                     |*|ru|"s|&J |&\  }4}(|r$                    |4           |(7|r                     |N|6|q|(z                        |r$                    |(           |r                     |N|Yg|XR             |'y|'\  }4}(|(U|r$                    |4           |r                     |N|6|q|(z                        | j*                            |q|(z              n| j*                            |q|4z              |+,                                }n|+$                    |q           |+                    |r                                           |+                                 | j        dk     r|q|tz   | _        n |+$                    | j*        | j+                 | j        |7z  z              |+                     |N|6|q                     | j        dk    r| j)                            |q|tz              nV|+$                    | j)        | j+                            |+                     |N|6|q                     |q|tz   | j)        | j+        <   | xj+        dz  c_+        | xj+        t          | j*                  z  c_+        |+$                    |n           |pdk    rd |KD             }K	|odk    sJ dN|2z   | _        |.| _        |o| _        |X| _        |!| _         |r|K| _        | r|otM          |X          fS dS )a^>  Write multi-dimensional image to series of TIFF pages.

        Metadata in JSON, ImageJ, or OME-XML format are written to the
        ImageDescription tag of the first page of a series by default,
        such that the image can later be read back as an array of the
        same shape.

        The values of the ImageWidth, ImageLength, ImageDepth, and
        SamplesPerPixel tags are inferred from the last dimensions of the
        data's shape.
        The value of the SampleFormat tag is inferred from the data's dtype.
        Image data are written uncompressed in one strip per plane by default.
        Dimensions higher than 2 to 4 (depending on photometric mode, planar
        configuration, and volumetric mode) are flattened and written as
        separate pages.
        If the data size is zero, write a single page with shape (0, 0).

        Parameters:
            data:
                Specifies image to write.
                If *None*, an empty image is written, which size and type must
                be specified using `shape` and `dtype` arguments.
                This option cannot be used with compression, predictors,
                packed integers, or bilevel images.
                A copy of array-like data is made if it is not a C-contiguous
                numpy or dask array with the same byteorder as the TIFF file.
                Iterators must yield ndarrays or bytes compatible with the
                file's byteorder as well as the `shape` and `dtype` arguments.
                Iterator bytes must be compatible with the `compression`,
                `predictor`, `subsampling`, and `jpegtables` arguments.
                If `tile` is specified, iterator items must match the tile
                shape. Incomplete tiles are zero-padded.
                Iterators of non-tiled images must yield ndarrays of
                `shape[1:]` or strips as bytes. Iterators of strip ndarrays
                are not supported.
                Writing dask arrays might be excruciatingly slow for arrays
                with many chunks or files with many segments.
                (https://github.com/dask/dask/issues/8570).
            shape:
                Shape of image to write.
                The default is inferred from the `data` argument if possible.
                A ValueError is raised if the value is incompatible with
                the `data` or other arguments.
            dtype:
                NumPy data type of image to write.
                The default is inferred from the `data` argument if possible.
                A ValueError is raised if the value is incompatible with
                the `data` argument.
            photometric:
                Color space of image.
                The default is inferred from the data shape, dtype, and the
                `colormap` argument.
                A UserWarning is logged if RGB color space is auto-detected.
                Specify this parameter to silence the warning and to avoid
                ambiguities.
                *MINISBLACK*: for bilevel and grayscale images, 0 is black.
                *MINISWHITE*: for bilevel and grayscale images, 0 is white.
                *RGB*: the image contains red, green and blue samples.
                *SEPARATED*: the image contains CMYK samples.
                *PALETTE*: the image is used as an index into a colormap.
                *CFA*: the image is a Color Filter Array. The
                CFARepeatPatternDim, CFAPattern, and other DNG or TIFF/EP tags
                must be specified in `extratags` to produce a valid file.
                The value is written to the PhotometricInterpretation tag.
            planarconfig:
                Specifies if samples are stored interleaved or in separate
                planes.
                *CONTIG*: the last dimension contains samples.
                *SEPARATE*: the 3rd or 4th last dimension contains samples.
                The default is inferred from the data shape and `photometric`
                mode.
                If this parameter is set, extra samples are used to store
                grayscale images.
                The value is written to the PlanarConfiguration tag.
            extrasamples:
                Interpretation of extra components in pixels.
                *UNSPECIFIED*: no transparency information (default).
                *ASSOCALPHA*: true transparency with premultiplied color.
                *UNASSALPHA*: independent transparency masks.
                The values are written to the ExtraSamples tag.
            volumetric:
                Write volumetric image to single page (instead of multiple
                pages) using SGI ImageDepth tag.
                The volumetric format is not part of the TIFF specification,
                and few software can read it.
                OME and ImageJ formats are not compatible with volumetric
                storage.
            tile:
                Shape ([depth,] length, width) of image tiles to write.
                By default, image data are written in strips.
                The tile length and width must be a multiple of 16.
                If a tile depth is provided, the SGI ImageDepth and TileDepth
                tags are used to write volumetric data.
                Tiles cannot be used to write contiguous series, except if
                the tile shape matches the data shape.
                The values are written to the TileWidth, TileLength, and
                TileDepth tags.
            rowsperstrip:
                Number of rows per strip.
                By default, strips are about 256 KB if `compression` is
                enabled, else rowsperstrip is set to the image length.
                The value is written to the RowsPerStrip tag.
            bitspersample:
                Number of bits per sample.
                The default is the number of bits of the data's dtype.
                Different values per samples are not supported.
                Unsigned integer data are packed into bytes as tightly as
                possible.
                Valid values are 1-8 for uint8, 9-16 for uint16, and 17-32
                for uint32.
                This setting cannot be used with compression, contiguous
                series, or empty files.
                The value is written to the BitsPerSample tag.
            compression:
                Compression scheme used on image data.
                By default, image data are written uncompressed.
                Compression cannot be used to write contiguous series.
                Compressors may require certain data shapes, types or value
                ranges. For example, JPEG compression requires grayscale or
                RGB(A), uint8 or 12-bit uint16.
                JPEG compression is experimental. JPEG markers and TIFF tags
                may not match.
                Only a limited set of compression schemes are implemented.
                'ZLIB' is short for ADOBE_DEFLATE.
                The value is written to the Compression tag.
            compressionargs:
                Extra arguments passed to compression codec, for example,
                compression level. Refer to the Imagecodecs implementation
                for supported arguments.
            predictor:
                Horizontal differencing operator applied to image data before
                compression.
                By default, no operator is applied.
                Predictors can only be used with certain compression schemes
                and data types.
                The value is written to the Predictor tag.
            subsampling:
                Horizontal and vertical subsampling factors used for the
                chrominance components of images: (1, 1), (2, 1), (2, 2), or
                (4, 1). The default is *(2, 2)*.
                Currently applies to JPEG compression of RGB images only.
                Images are stored in YCbCr color space, the value of the
                PhotometricInterpretation tag is *YCBCR*.
                Segment widths must be a multiple of 8 times the horizontal
                factor. Segment lengths and rowsperstrip must be a multiple
                of 8 times the vertical factor.
                The values are written to the YCbCrSubSampling tag.
            jpegtables:
                JPEG quantization and/or Huffman tables.
                Use for copying pre-compressed JPEG segments.
                The value is written to the JPEGTables tag.
            iccprofile:
                International Color Consortium (ICC) device profile
                characterizing image color space.
                The value is written verbatim to the InterColorProfile tag.
            colormap:
                RGB color values for corresponding data value.
                The colormap array must be of shape
                `(3, 2\*\*(data.itemsize*8))` (or `(3, 256)` for ImageJ)
                and dtype uint16.
                The image's data type must be uint8 or uint16 (or float32
                for ImageJ) and the values are indices into the last
                dimension of the colormap.
                The value is written to the ColorMap tag.
            description:
                Subject of image. Must be 7-bit ASCII.
                Cannot be used with the ImageJ or OME formats.
                The value is written to the ImageDescription tag of the
                first page of a series.
            datetime:
                Date and time of image creation in ``%Y:%m:%d %H:%M:%S``
                format or datetime object.
                If *True*, the current date and time is used.
                The value is written to the DateTime tag of the first page
                of a series.
            resolution:
                Number of pixels per `resolutionunit` in X and Y directions
                as float or rational numbers.
                The default is (1.0, 1.0).
                The values are written to the YResolution and XResolution tags.
            resolutionunit:
                Unit of measurement for `resolution` values.
                The default is *NONE* if `resolution` is not specified and
                for ImageJ format, else *INCH*.
                The value is written to the ResolutionUnit tags.
            subfiletype:
                Bitfield to indicate kind of image.
                Set bit 0 if the image is a reduced-resolution version of
                another image.
                Set bit 1 if the image is part of a multi-page image.
                Set bit 2 if the image is transparency mask for another
                image (photometric must be MASK, SamplesPerPixel and
                bitspersample must be 1).
            software:
                Name of software used to create file.
                Must be 7-bit ASCII. The default is 'tifffile.py'.
                Unless *False*, the value is written to the Software tag of
                the first page of a series.
            subifds:
                Number of child IFDs.
                If greater than 0, the following `subifds` number of series
                are written as child IFDs of the current series.
                The number of IFDs written for each SubIFD level must match
                the number of IFDs written for the current series.
                All pages written to a certain SubIFD level of the current
                series must have the same hash.
                SubIFDs cannot be used with truncated or ImageJ files.
                SubIFDs in OME-TIFF files must be sub-resolutions of the
                main IFDs.
            metadata:
                Additional metadata describing image, written along
                with shape information in JSON, OME-XML, or ImageJ formats
                in ImageDescription or IJMetadata tags.
                If *None*, or the `shaped` argument to :py:class:`TiffWriter`
                is *False*, no information in JSON format is written to
                the ImageDescription tag.
                The 'axes' item defines the character codes for dimensions in
                `data` or `shape`.
                Refer to :py:class:`OmeXml` for supported keys when writing
                OME-TIFF.
                Refer to :py:func:`imagej_description` and
                :py:func:`imagej_metadata_tag` for items supported
                by the ImageJ format. Items 'Info', 'Labels', 'Ranges',
                'LUTs', 'Plot', 'ROI', and 'Overlays' are written to the
                IJMetadata and IJMetadataByteCounts tags.
                Strings must be 7-bit ASCII.
                Written with the first page of a series only.
            extratags:
                Additional tags to write. A list of tuples with 5 items:

                0. code (int): Tag Id.
                1. dtype (:py:class:`DATATYPE`):
                   Data type of items in `value`.
                2. count (int): Number of data values.
                   Not used for string or bytes values.
                3. value (Sequence[Any]): `count` values compatible with
                   `dtype`. Bytes must contain count values of dtype packed
                   as binary data.
                4. writeonce (bool): If *True*, write tag to first page
                   of a series only.

                Duplicate and select tags in TIFF.TAG_FILTERED are not written
                if the extratag is specified by integer code.
                Extratags cannot be used to write IFD type tags.

            contiguous:
                If *False* (default), write data to a new series.
                If *True* and the data and arguments are compatible with
                previous written ones (same shape, no compression, etc.),
                the image data are stored contiguously after the previous one.
                In that case, `photometric`, `planarconfig`, and
                `rowsperstrip` are ignored.
                Metadata such as `description`, `metadata`, `datetime`,
                and `extratags` are written to the first page of a contiguous
                series only.
                Contiguous mode cannot be used with the OME or ImageJ formats.
            truncate:
                If *True*, only write first page of contiguous series
                if possible (uncompressed, contiguous, not tiled).
                Other TIFF readers will only be able to read part of the data.
                Cannot be used with the OME or ImageJ formats.
            align:
                Byte boundary on which to align image data in file.
                The default is 16.
                Use mmap.ALLOCATIONGRANULARITY for memory-mapped data.
                Following contiguous writes are not aligned.
            maxworkers:
                Maximum number of threads to concurrently compress tiles
                or strips.
                If *None* or *0*, use up to :py:attr:`_TIFF.MAXWORKERS` CPU
                cores for compressing large segments.
                Using multiple threads can significantly speed up this
                function if the bottleneck is encoding the data, for example,
                in case of large JPEG compressed tiles.
                If the bottleneck is I/O or pure Python code, using multiple
                threads might be detrimental.
            buffersize:
                Approximate number of bytes to compress in one pass.
                The default is :py:attr:`_TIFF.BUFFERSIZE` * 2.
            returnoffset:
                Return offset and number of bytes of memory-mappable image
                data in file.

        Returns:
            If `returnoffset` is *True* and the image data in the file are
            memory-mappable, return the offset and number of bytes of the
            image data in the file.

        rT  )framesNz-missing required 'shape' or 'dtype' arguments__next__r~   reshaper  zdtype argument z does not match data dtype zshape argument z does not match data shape c              3  "   K   | ]
}|d k    V  dS )        Nr   )r   rw   s     r   r   z#TiffWriter.write.<locals>.<genexpr>  s'      88dtz!888888r   zinvalid data shaper   rW   rY  r   FT)r  r  r	  rW   )Nr   rW   r  r  r	  >   r  r  r	  rW   rZ  r~   z8the ImageJ format does not support non-contiguous seriesr~   r   storedshapez,SubIFDs cannot be used with truncated seriesz$SubIFDs in SubIFDs are not supportedz8contiguous mode cannot be used with compression or tilesz.ome.z7truncate can only be used with imagej or shaped formatsz<truncate cannot be used with compression, packints, or tilesr   r   z. writing zero-size array to nonconformant TIFFc              3  Z   K   | ]&}t          t          t          |                    V  'd S r   )r   r7   r!   )r   xs     r   r   z#TiffWriter.write.<locals>.<genexpr>2	  sE       ! !12GK++,,! ! ! ! ! !r   zpassing multiple values to the 'compression' parameter was deprecated in 2022.7.28. Use 'compressionargs' to pass extra arguments to the compression codec.ZLIB   阇        codecformatz(cannot use predictor without compressionzcannot use predictor with fr   iu      >   r  L  M     r   N  O  zcannot use z with z$ not writing description to OME-TIFFz$OME-TIFF does not support ImageDepthz' not writing description to ImageJ fileBHhfz-the ImageJ format does not support data type z-the ImageJ format does not support ImageDepthBz for RGBaxesrgbr  z1the ImageJ format does not support planar samples   r   r  )r      z!invalid colormap shape for ImageJHfz1 not writing colormap to ImageJ image with dtype=z and photometric=BHzinvalid colormap shapez$invalid data dtype for palette-imagez* not writing colormap with image of dtype=   c              3  "   K   | ]
}|d k     V  dS rW   Nr   r   is     r   r   z#TiffWriter.write.<locals>.<genexpr>	  s&      ++q1u++++++r   zinvalid tile shape c              3  4   K   | ]}t          |          V  d S r   r   r  s     r   r   z#TiffWriter.write.<locals>.<genexpr>	  s(      ..AQ......r   rW   r   )zcontiguous sampleszparameter is)zseparate component planesz!and 'planarconfig' parameters arez,<tifffile.TiffWriter.write> data with shape z and dtype 'z' are stored as RGB with zl. Future versions will store such data as MINISBLACK in separate pages by default, unless the 'photometric' z specified.
stacklevelznot a z imagezinvalid CFA imagez)<tifffile.TiffWriter.write> cannot write z using volumetric tiles >   r   rW   r  zinvalid SubfileType MASKzbitspersample=z must be 1 for bilevel         r    r   uint16   z invalid for JPEG compression   B  R  r  r  r  r  )rW   r  r  z out of range of datadtype=uz does not match datadtype=z  cannot be used with compressionzinvalid z for palette modeznot enough samples for z: expected z, got  does not match E  D        z    InfoLabelsRangesLUTsPlotROIOverlays
Propertiesinfolabelsrangeslutsplotroioverlayspropr  
colormapedz@                                                                )	truncatedz                asciiztifffile.py1     :zinvalid datetime string%Y:%m:%d %H:%M:%S2    G  r   deflatezstdzinvalid LERC compression   =  r    B  C         __len__J        r  )r  r  r  cS  @  s  r        zwrong number of extrasamples  != R  r   [  r  r  >   r  rW   rW   rW   r  r  rW   zinvalid subsampling factors ztile shape not a multiple of z'JPEG subsampling requires RGB(A) images  outcolorspacer   
colorspace  c              3  .   K   | ]}|d          dk    V  dS r     Nr   r   ets     r   r   z#TiffWriter.write.<locals>.<genexpr>  *      88r!u|888888r   r     )r   rW      rW      rW   r  rW   r  rW   r  rW   >   Nr  z cannot apply subsampling r  c              3  .   K   | ]}|d          dk    V  dS r  r   r  s     r   r   z#TiffWriter.write.<locals>.<genexpr>  r  r       zupassing a unit along with the 'resolution' parameter was deprecated in 2022.7.28. Use the 'resolutionunit' parameter.(  numtilesr   	bytecountr   Iterator[bytes]c              3  T   K   t          |          }t          |           D ]}|V  d S r   )bytesrange)r  r  chunk_s       r   	dataiter_z#TiffWriter.write.<locals>.dataiter_U  s?      
 !&i 0 0!&x ( (A"'KKKK( (r       i   z&cannot write non-contiguous empty filec                    h | ]
}|d          S r  r   r   ts     r   	<setcomp>z#TiffWriter.write.<locals>.<setcomp>  s    %%%1!A$%%%r   z not writing extratag c                    | d         S Nr   r   r  s    r   <lambda>z"TiffWriter.write.<locals>.<lambda>  s
    !A$ r   rn   ztype(iteritem)=z	 != byteszdtype of iterator z does not match dtype r   rb   axisr  c                R    t          j        | |                                          S Nr  r  packbitstobytes)r   r  s     r   compressionfunc1z*TiffWriter.write.<locals>.compressionfunc1  s%     !>$T:::BBDDDr   >   r    rY  P  ]  m  鲀  
compressorr   c                d    t          j        | |                                          }  || fi |S r  r  )r   r#  r  r   s       r   compressionfunc2z*TiffWriter.write.<locals>.compressionfunc2  s<     !>$T:::BBDDD%:d55f555r   zcannot compress bilevel imager  c                     || fi |S r   r   r   r#  r   s      r   compressionfuncz)TiffWriter.write.<locals>.compressionfunc      
 &:d55f555r   predictorfuncc                .     || |          }  || fi |S r  r   )r   r*  r#  r  r   s        r   r(  z)TiffWriter.write.<locals>.compressionfunc  s0     )=D999D%:d55f555r   c                     || fi |S r   r   r'  s      r   r(  z)TiffWriter.write.<locals>.compressionfunc$  r)  r   bpsc                0    t          j        | ||          S r  )imagecodecspackints_encode)r   r-  r  s      r   r(  z)TiffWriter.write.<locals>.compressionfunc3  s%    
 #2#D   r       r   c              3  &   K   | ]}|d          V  dS r  r   r  s     r   r   z#TiffWriter.write.<locals>.<genexpr>  s&      "6"6A1Q4"6"6"6"6"6"6r   z(iterator contains wrong number of bytes ztile is too largec              3  *   K   | ]\  }}d ||z
  fV  dS r   Nr   r   r  js      r   r   z#TiffWriter.write.<locals>.<genexpr>/  sB       $ $ $1 AJ$ $ $ $ $ $r   zunreachable codec                "    g | ]}|d          
|S rT  r   )r   tags     r   
<listcomp>z$TiffWriter.write.<locals>.<listcomp>  s!    ;;;3r7;;;;r   )r  r   r  r   r   r  )r   rb   r  r   r   r  )
r   rb   r#  rb   r  r   r   rb   r   r  )r   rb   r#  rb   r   rb   r   r  )r   rb   r*  rb   r#  rb   r  r   r   rb   r   r  )r   rb   r-  rb   r  r   r   r  )r0   r0  r/  r   r   r  r  r~   r  hasattrr\   ndarrayr   flagsf_contiguousAttributeErrorr   anyr%  rD   r  r   r   listr:  r<  r8  array_equal_write_remaining_pagesr3  r1  rE  rJ  r6  addimage_write_image_descriptionra  r  ri  rD  r5  rH  rG  rI  r]  write_emptywrite_arrayr2  	extensionr4  rm  rn  ro  tagnoformatrl  
offsetsizetagsizer&   
MINISBLACK
MINISWHITERGBYCBCRPALETTEr'   CONTIGSEPARATEr7   sequencer   r   upperr    valuer   IMAGE_COMPRESSIONSkindr(   
PREDICTORSr+   r   getimagej_shaperG   PHOTOMETRIC_SAMPLESDeprecationWarningcontig_sampleswidthlengthdepthseparate_samplessamplesr   CFAMASKrx  	page_sizeis_validRuntimeErrorr   rz  r@  _pack_addtagcopyimagesrB   r<   r;   r  shaped_descriptionr  encoder   rB  DateTimestrftimenowr   rw   maxru   allr=   warningr)   r  INCHrational_bytecount_format
iter_tilesmathceilr  iter_imagesTAG_FILTEREDsortedpeek_iteratortypeCOMPRESSORSNotImplementedErrorr   _maxworkersencode_chunksiter_strips
page_shaper  rC  ioBytesIOr   	enumeraterv   
startswithvalueoffsetSEEK_CURnextascontiguousarrayr  zippadr   	getbufferflushr=  r?  r9  sum)rp  r   r   r~   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rT   r   r   r   r   rt  r   r   r   r   r   rr   rs   r   r  	dataarraydataiterr$  dataoffsetsoffsetdatabytecountsoffsetsubifdsoffsetsrr  r*  r(  rq  r   	datashape	datadtypebilevelindexr  
inputshapepackintsrv   rI  rl  rJ  rK  rL  rM  rN  rO  rP  rQ  rR  compressiontagpredictortagijrgbr  ijshapendim	deprecatemsgphotometricsamplessamples_sets0tagstagbytecounts
tagoffsetsrk  addtag
ijmetadatar  lerc_compressionsampleformatmaxsamplingr  tilesr  databytecountsbytecountformatr
  count	numstripsrowsize
numstrips1	stripsizelaststripsizer  tagsetextratagcompressionaxis	bytesiter	tupleiteriteritemr  r  r%  r#  	tileshapetilesizefhposr!  	pageindexifdposifd	tagoffset	ifdoffsettagindexr9  coderU  ifdsizeskipbyteswrittenpagesize
chunkindex	tileindexr  rw   s                                                                                                                                    r   r  zTiffWriter.write  sF=   `
 $/b#9#9#9 *.	AE(,;?>B8< 3759
 XI'	<} C   IHeIE**77	BBIIT:&& -	} C   HeIE**77	BBIIT7## #	t,,DIDJ//<<YGGI4++ 
!M$	3??		z. H$)M$	3$G$G	%   D "IH U[%7%79%D%D .e . ."+. .    Uio%=%= 4e 4 4"+/4 4   E**77	BBIdIs;;I!IH88i88888 	31222.C' 	?#B-!++BBEy%011H!# 2Ie,1A55Ie,11y))I,>>Hq==IK M# 	  {D11	   #>>> ;66 ?  N&JJJ  K 	9d++	888I
 % 8!3a!77 	 ?&4?+F# =SIIII?122&)33?i//$)CN*x/C(dn  0D ++---< $0   <+)A--#0<<<#~999-- "&/"&/%)_Q%71%<%<! E E# )-(9(?  #n   )11333GGAr{+++= ~  (J   &&!+&&)T]::/1,/1,-/*())*  (B   #'!%  D  N   $(?1#5#9";i"G$NN8,,,,NN9i888 ,!8++t9"#r|3		!	> 	#T\ 	#!(^^DNN 	#I   #DN> 	{ 	h 	$ 	N   q==IMIII   i+y-Y)
)# +
 +
o!%$( "!+{;;K 	?"<>>L#  ! !6>|6L6L! ! !  L " O 	 +t}55 )   +s++  )//11&(("#KK..  $[+>>DNKKNKQ OO;;;-.OM**** !	 M !KLLL!888 7">227 7   )T** />S((#$LL^t++	0Ba0G0G#$LL$BYBB   $Iy99	Nd**!/@@@!*a//Nc))!/@@@$FiFFFF    )L59 A	5&CCC   #|###)88DLL#)#5#5H#5#5DL Id Is4yy1}} !GHHHJJ\ 1	5 &FFF   #~V++ * ~* *    d s4yy1}} C   J*5?K3&&4E~$$#%%$;%.; ; ;   #||FD11"9%dCCCGx'' G   r{f$$!$'INc,A,A")KK",K#%*466L }XY_EEEH%DN| & >X--$%HIII>S(([= . . #*KK^s**{g/E/E!$..'J
+CCC M @ @!*@ @1<@ @#  
  $H$4)?)?%#>ay/AA/E)F%GGG$%=>>> H''#>--$%KLLL>ay/AA/E)F%GGG$%=>>> H  < <&< <-8< <  
   	* D		%%%%A%%%%%8b= &8b= & ++d+++++ &
 !!=t!=!=>>>.......D #c$ii1nnd{TaJJDj))J$&&&&& $((Q 
 
 5zz 	$((JI$K !(''!88b	V 3 3"%K )d :I)) %$((uRyF/B/B"%K $IIAXX%)v"5"5"%K $IeBi611!%%N$6		 
! 
!(# !qU2Y&-@-@!' 		eBi611!' 	 6))>CCC +9 + +"++ +FI!f+ + 1v	+ + +
 '     &&&!5kB 	)CJJ
+A11BBL!A%%(!!5zzA~~ !?+!?!?!?@@@5zzA~~"
##%%#5q"9KK#5"6K9++#)LL3224CC#+LL2YZ'?rrR!@@@#+LL#)Lv%%-22Y*$)"I!%*2Y" 2(-b	K%$)"I!%*2Y" =(-b	K%389K00389K0"%777'*<< ( KO++5zzQ !4555JL %b	K!&rK  8	Cc%jj,BAACCv%%'3|+<+<q+@+@16rK.(-b	K%).rK&! 6,1"I)#'L12K.(-b	K%).rK&! 6,1"I)$)"I!%*2Y"'3|+<+<q+@+@! A,1"I)7<Ry447<Ry44#'L34K0! 6,1"I)'2':Q'>K$$  L~ #8 #x2~~%jj1nnra!#2#JE %jj1nnra ##e**q..U2Y!^^crc
5zzA~~"
 C$)"I!%*2Y" 2(-b	K%-22Y*$)"I!%*2Y" 2(-b	K%+6+>+B( 	d 	s4yyA~~$q'A++1K 1 1*.1 1  
 "{U':" ='1,,9,, !;<<<%*K 0	(]a-?-? !JM!J!J!JKKKMM333 $"o55$3O$DMM*3x*?*?BBQM++++++++ D}DDD   , III $"o55$3O$DMM$-$6$:MA! 3 3I4F GGG!Y%7!%;;; D}DD	DD   <
 "%.2MMNc!!Y%7!%;%;y1A555LLL	LLMMMaB//	0BCCC!3a!777MMMMMNNN 		 2Q 666 G}GGG   7 i01444H##&B&(Agg7:3F3F"3LKa<< 4<9+99:::'!!"a'';+Ca+G+G !LK!L!L!LMMM ,H #555L+ L L.L L6A6IL L   $(L88BB;BB    !))+*;<<I 	MJJMJ)zI"F4aK666 $,@<#4<&''1,,0"\ +	%# J( )Y?? ! !t a     ,.&8>5  .	 K ;&KK^ 	 	X^^~ 6%%%555,ZJJ4>JJK;&KK $k511 :)0099#*aa[!1!1;$ $D  K"DNN%,,W55KF4aK666#*aa[!1!1;$ $D  $H 	4F4aHd333 	4(C(( Hx==B&&(2,#*=*=$%>??? +>Hh// H#,,-@AA#<>>223FGGF4aHd333tS!Q///U""O33#$   /7#$   /9<<#$   /699#$   :&}5: :   F41q*:&;<<< 1F4aL111tS!Q 1222tS!Q 2333 	.F4aDH---F4aDH--- 	3F41k&7888 3tUAq$q'222"F4aK000 	t} 	$*<q*@*@} '-),, 'g,,g,,#DMFca22R1#-    		y~44!";;INKLF#+"55   F4a999!F43z??J???tS!Q 3444 	3"Q&&tS!Q(@AAA 1$$F4aK$<===F# ;#66    F4aM222#a'''+s</@/@@@$M&3M M9<\9J9JM M   tS!S%6%6EEEE##(@A(E(EtS!Q**** ,;33   !F4aZ*=== a(A--U|++ "$$DDD B;BB   k**Q.K PbK/ P48k3I P !N!N!NOOO'!++ !JKKKF4aK000#_00!DD M .9OM*,7,<OL)/</AOO,F4aM222%%88i88888 FF   .00  HHHH   KKFc1a!2   e##tS!Q///88i88888 FF   %$Wn==NN\ 	*Z/$\NN$\N!F4aHZ]$;$;<<<F4aHZ]$;$;<<<:"" :  
 F4aN3333F4aF+++F4aF+++F4aN333 &<<W=
 @	24yyA~~ '$q'1A5$q'A &a014a@
  5#*d1g55#)T!W4 
 !&a014a@ '$q'1A5$q'A &a014a@  5#)T!W45#*d1g55 $)T!W4	  u~~(DDH ::Y=OON #44 O Fm_h   F4\8aS8^LLL!)<?<<O +())T5AAHH% &#+ &/6 &
 )1;3E(E)7):( ( ( ( (  )y{{HLL H	2 LK4F$F$F0;3DDE"#$,- $%
 N #44 O F4OOOF4\51#+FFFF4aK$6777!&999O&-LII
 !,-$% 
 &&*1#  6#)W#4LL#.#5La* 222*1 !; Il[899KG   +++F4aL111 "\1A5J [99K<MM  %w.I'[94N%\)K,>>) M :>9jAA 2 2$1q!!"44 O Fm_i   F4\9qcIoNNN-	9O$Z$&y11JEFFF &%%%%d'(((! 	( 	(H{f$$  BBXa[BB    t'h'''''
 d///  "		 !.x!8!8Hh(E** D 	&.#)!(E22 D$%BX%B%B%BCCC"8U33I  =22)#2a77 r*a// ')O>&).88$>X^ > >09> >  
 H \	#"" ,;E E E E E
 #3#LLL '+&6~&F /"1	6 6 6 6 6 #3 **IJJJ B	#).9J&&*9'  "' '1"16 6 6 6 6 6 * *7&0 /"16 6 6 6 6 6 ! ' '1"16 6 6 6 6 6  !##", #' 	# )+      #O 5	) 5	0KI 2 K$>#@@	"9--	0BB'33{11"	 
 ){11#	 	 (33 22"	 
 '* 	  ) 22#$#)#2
   		 
 JFqqK4FGG y	< y	<IFz !!!!!A%%(((lF33444GGFOOO 1}}!%jll		$${CII66777HHJJ			#(("6"6"6"6"666777HHJJ			$$|Q//000%.t__ 16 16MHc&G);;a?*LFq6DFE -6!hhjj7 %IIg...1HC(((		$$|Vc\"B"BCCC		%(((:--06--!]22393;00!S[[ $ 4 @$($8$?1$D$D$)$4$4$($8$>%" %" %E %+Y$6G9K$K !% 4 ; DJC< 4 @!S[[-3S[N++,2DL))../5t|,, 0< $ 4 ;q @ @ $ 4 :c!fRSSk I I !' 2X5G G !07 !% 4 ;j H1 L !0< )/((**Q; !IIg&&&qLG GGGR[))) J}Z%/0E9DGGD"+&&&$J X7'#$L  )(0 ) )H(BHH (- - L !)) $/#89;M#M(0 	) 	)H'/ ,x0H0H H !-$,$-1" 1" !" !)#x//(<+< <19< <   0
 &NN8,,,,NN9i8888 77+++ c%DXX9E#"'D(Gi"H"H 	! 	!J*.eSj)4>>+ +'Hi 2;N:..4K
+c(mm+FHHX&&& 	!  '7+++"'D(Gi"H"H ! !J#E4>>::H14XN:.HHX&&& !  7+++ K$>#@@	"9--	0BB!&x ! !I#H~~H'45y1 $6xKKH(22
 $?X55",-@"A"AA# $ $(+Ix~(F(F$ $ $   $)9Xs#;#;NN8,,, +!0 ##5666 %000+KFCHHV		$$|Vc\::;;;&'F . ' '		 DvvqII   $	' #. > >		$$|V"<"<====> 		$$|Z88999*t*	8I+7772   ?IIdd<#>>???HHSMMM		$$@@@@AAA),?HHV$$$IIdd<#>>???(//====(//@@@GGIIEGGFOOOHHS]]__%%%HHJJJ!A%%"(9"4 (8(:56   lF33444 %**(//0BCCCCGGD0@AAAHHTT,77888;AI;MD(8!##d&:";";;GGENNN A~~;;t;;;A~~~~+#%-' 	7DJ 7!3~#6#666ts   %"F 
FFr   c                   | j         t          d          |                                  | j                             |d           d| _         dS )zOverwrite value of last ImageDescription tag.

        Can be used to write OME-XML after writing images.
        Ends a contiguous series.

        Nzno ImageDescription tag foundFerase)rB  r   rC  	overwriterp  r   s     r   overwrite_descriptionz TiffWriter.overwrite_description  sX     '<===##%%%&&{%&@@@#r   c                   	 | j         s|                                  |                                  	 | j                                         dS # t
          $ r Y dS w xY w# 	 | j                                         w # t
          $ r Y w w xY wxY w)z,Write remaining pages and close file handle.N)r5  rC  rE  r0  closer  rp  s    r   r  zTiffWriter.close  s    	> .++---))+++               s@   /A A 
AAB
 A:9B
:
BB
BB
c                    | j         S )zFile handle to write file.r0  r  s    r   
filehandlezTiffWriter.filehandle       xr   c                   | j         r| j        s| j        dS | j        J | j        J | j        J | j        j        | j        d         z  dz
  }|dk     rd| _         d| _        d| _        dS | j        }|                                }|dz  r|	                    d           |dz  }t          j        }| j        j        }| j        j        }| j        j        }| j        j        }| j        }	t#          | j                  }
d}t%          j                    }|	                     ||t)          | j                                        |                                }|	                    d                    d | j         D                                  |                                }|	                     ||d                     t-          | j                   D ]I\  }}|||z  z   |z   dz   }|d         }|d         }|r|                                }|dz  r|	                    d           |dz  }|                    |           	 |	                     ||||z                        nT# t0          $ rG}| j        r+t5          j        | d	t8                     d
| _        Y d}~ dS t;          d          |d}~ww xY w|                    |           |	                    |           || j        k    r||f}"|dk    r||f}.|| j        k    r|df}?|dk    r|df}K|                                }|dz  r|	                    d           |dz  }|dk     rH|||z  z   dk    r<| j        r&t5          j        | d	t8                     d
| _        dS t;          d          t%          j        t?          ||z                      }|}tA          |          D ]}|	|
z  }	|\  }}|                    |           |h|	                     ||||z                        |                    |           |	}| j        D ]&}|	                     |||                     ||z  }'n|	                     |||	                     |&|\  }}| j!        "                    |||n|z              | j#        dk     r{|>|\  }}|7|                    |           |	                     ||||z                        ||z  }|                    |           |	                     |||                     n|                    | j!        | j$                 | j#        |z  z              |	                     |||                     | j#        dk    r| j%        "                    ||z              nV|                    | j%        | j$                            |	                     |||                     ||z   | j%        | j$        <   | xj$        dz  c_$        | xj$        t)          | j!                  z  c_$        ||z  }|	                    |&                                           |||dz
  z  z  }|                    |           |	                     ||d                     |                    |           |	                    |&                                           | j#        dk     r|                                }|                    | j'                   |	                     |||                     |(                                 |                    |           ||z   | _'        d| _         d| _        d| _        dS )z(Write outstanding IFDs and tags to file.Nr   rW   r  r1  r   c              3  &   K   | ]}|d          V  dS r  r   r  s     r   r   z4TiffWriter._write_remaining_pages.<locals>.<genexpr>  s&      44A1Q4444444r   r  z truncating ImageJ fileTz#data too large for non-BigTIFF filer  rY  l    ))r9  r5  r:  rJ  r?  r=  rx  r0  r]  r  rj  rk  r/  rl  rJ  rI  rK  r  r  r  r   r   r  ra  r  r3  rm  rn  ro  r   r@  r  r  rG  r   rE  rI  rH  r  rC  r  )rp  pagenorq  r  rk  rl  rJ  rI  rK  r!  pagedatasizer  r  r  r  r  r9  rv   r  rU  rr  excr  r  ifdsr  r	  rw   s                               r   rC  z!TiffWriter._write_remaining_pages  s   z 	T^ 	t/FF ,,,#///+++'.1CCaGA::DJ#D#'D FXWWYY19 	HHWQJE{ I2).
90y(*
 4558< jll		$${C
OO44555HHJJ			#((4444444555HHJJ			$$|Q''(((&tz22 "	. "	.MHcG!33j@1DFq6DFE .hhjj7 IIg&&&1HC   IIdd<==>>>>  	 	 	|  #>>>   *.$= 	 		%   4///(.%%S[[%+S[N---$*DL!!!'((**Q; 	IIgqLG >>eg&66CC| @@@+NNN!%BCCC z%& 01122v 6	( 6	(A,&J+KFCHHV		$$|Vc\::;;;# 0 # #DIIdd<88999dNFF# 		$$|Z88999),$++S_cc&A   !A%%!-"0KFC(((		$$|Vc\"B"BCCC '!###		$$|V445555 (8(:56   lF33444 %**(//0BCCCCGGD0@AAAHHTT,77888;AI;MD(8!##d&:";";;'! JJs}}'''' 	W
++			)

44a(()))

!!"""!!''))CGGDO$$$HHTT,..///HHJJJGGCLLL#i/DO
#s   "I))
J:3+J5%J55J:c                   | j         | j        	d| _        dS | j        J | j        J | j        z| j        dk     rS| j        J  | j        j        d| j        | j         | j         d         dk    rdndd         | j        j        d| j         | j        	                    d          }n| j         d         dk    r	d| _        dS | j
        r;| j        J | j        du}| j        j        dv }t          | j         f||d| j        }n0| j        s	d| _        dS | j        J t          | j         fi | j        }| j                            |                                d	
           d| _        dS )z'Write metadata to ImageDescription tag.Nr   rW   r  Tdeclarationr  r  Fr  r   )r:  rB  rJ  r<  r1  rE  r6  rD  r   tostringr3  r8  rb  r;   r4  rl  r  rm  )rp  r   colormappedisrgbs       r   rE  z#TiffWriter._write_image_description\  s   ?"d&:&B#'D F ,,,***<#!A%%~111%% //!_Q/144!== !% 1 7  n   ,//D/AAKK_Q1$$#'D F \ 	P>---.4K%-7E,&  .	 KK  	P#'D F>---,T_OOOOK&&{'9'9';';5&III#r   r  +list[tuple[int, bytes, bytes | None, bool]]r  	int | strr  rU  rb   	writeoncec          	     T	   | j         }t          |t                    st          j        |         }	 t          t          |          }t          j        |         d         }	n|# t          $ ro}
	 t          t          |          }	|	d         dv r
|	dd         }	t          j	        |	         }n(# t          t          f$ r t          d|           |
w xY wY d}
~
nd}
~
ww xY w~|}|dk    rt          |t                    r9	 |                    d          }nF# t          $ r}
t          d	          |
d}
~
ww xY wt          |t                    st          d	          t          |          dk    s|dd         d
k    r|d
z  }t          |          }|dk    r\t          |                    d                    }|dk     r|}n3t#          | j        j        dz   |dz             }t)          ||          }n|}|f}nt          |t                    rJt+          j        |	          }t          |          |z  rt          d          t          |          |z  }|}n |t          d          t          |          }|dv r|dz  }|	d         }	 |d||           || j        j        |          g}d}t+          j        |	          |z  | j        j        k    r| j        j         d}t          |t                    r!|                     |||                     nj|dk    rZt          |t2          t4          t6          j        f          r|d         }|                     || ||	|                               n
|                     || || |	 g|R                       n|                     || j        j        d                     t          |t                    r|}nt          |t6          j                  rN|j        |k    rt=          d          |j        j         |	k    rt=          d          |!                                }n6t          |t2          t4          f          r || |	 g|R  }n ||	|          }|                    |d"                    |          ||f           dS )zAppend (code, ifdentry, ifdvalue, writeonce) to tags list.

        Compute ifdentry and ifdvalue bytes from code, dtype, count, value.

        rT  r   <>rW   Nzunknown dtype r  r   TIFF strings must be 7-bit ASCIIr1  r       invalid packed binary datazinvalid count   r  
   HHszvalue.size != countzvalue.dtype.char != dtyper   )#rh  r   r   r   TAGSr\   DATA_FORMATSKeyErrorr   DATA_DTYPESr   r   rm  UnicodeEncodeErrorr  r   findrq  r/  rJ  minrj  calcsizerl  r   r  rA  r  r<  rw   rg  r~   r%  r  r   )rp  r  r  r~   r  rU  r  rk  datatype
dataformatr  rawcountr  ifdentryifdvaluevalueformats                   r   ri  zTiffWriter._addtag  s!    z$$$ 	#9T?D
	DC''H*84R8JJ 	D 	D 	DD!#u--
a=D((!+ABBJ+J7i( D D D !9%!9!9::CD 	D q==%%% 	E!LL11EE)   $:   u-- E !CDDD5zzQ%*"7"7 JJEs{{uzz+6677a<<$HH  #49#7!#;X\JJH"5(33HH HEEu%% 	z22H5zzH$ ? !=>>>JJ(*EHH]_---JJEwQJE#BJ DtX&&D'22

 ?:&&.$)2FFF!Y1444K%'' 	[% 8 89999!eeT5=%ABB %!!HE[$$z52I2I J JKKKKDdde+AZ+A+A&JE&J&J&JKK   
 OODD!7;;<<<%'' 3 E5=11 	3:&&&'<===;#z11&'BCCC ==??EE4=11 345 6* 6 6????4
E22T388H--xCDDDDDsA   -A 
C);B%$C%%C

CC:D 
D/D**D/fmtvalr  c                X    |d         dvr| j         j        |z   }t          j        |g|R  S )z2Return values packed to bytes according to format.r   r  )r/  r   rj  rk  )rp  r  r  s      r   rh  zTiffWriter._pack  s8    q6)%+C{3%%%%%r   
bytecountsSequence[int]c                   t          |          dk    r| j        j        d         S |d         }|dk    r|dz  }|dk     rdS |dk     rdS | j        j        d         S )zReturn small bytecount format.rW   r   r     rZ  r|  I)r   r/  rl  )rp  r  r   r  s       r   rv  zTiffWriter._bytecount_format  sp     z??a9)!,,qM	??!BIu3u3y%a((r   	numchunks	chunksizec                   | | S |dk    s|dk     s|dk     s|dk    rdS |dk     r|dv rdS |dk     r|d	v rdS |d
k     r|dv rdS |dk     r|dv rdS |dk     r|dv rdS |dk    rt          |d          S t          |t          j                  S )z,Return number of threads to encode segments.NrW   r     r  i   >   r  r  r  r  r  i   >   r  rY  r  r   r"  i    >   RX  u  v     r  >   Q  r!  r  r  )r  r   
MAXWORKERS)rr   r	  r
  r   s       r   r  zTiffWriter._maxworkers  s    ! 11}}4e##1 v+ 2
 #
 #
 1u 1
 "
 "
 1t 0
 !
 !

 1t 0
 !
 !
 1t 0
 !
 !
 1%y!$$$9do...r   c                    | S r   r   r  s    r   	__enter__zTiffWriter.__enter__Q      r   exc_type	exc_value	tracebackc                .    |                                   d S r   r  rp  r  r  r  s       r   __exit__zTiffWriter.__exit__T      

r   c                >    dt          | j        j        d          dS )Nz<tifffile.TiffWriter     rj   )snipstrr  ru   r  s    r   __repr__zTiffWriter.__repr__W  s"    Mwt/CR'H'HMMMMr   )r   r   rt   r   r   r   r   r   r   rK  r   r   r   r   r   r   r   r  r   )Br   r   r   r   r~   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   ru  r   r   r   r   r   r   r   r   r   r   r   r   r   r   rT   r   r   r  r   r  r   r  r   r  rt  rv  r   r   r   r  r   r   r   r   r   r   rr   r   rs   r   r   r   r   r   )r   r   r   r  r   r  r   r.   F)r  r  r  r  r~   r  r  r   rU  rb   r  r   r   r  )r  r   r  rb   r   r  )r  r  r   r   r   r   )
rr   r   r	  r   r
  r   r   r   r   r   )r   r   r  rb   r  rb   r  rb   r   r  r   r   )r*  r+  r,  r-  __annotations__rs  r  r  r  propertyr  rC  rE  ri  rh  rv  staticmethodr  r  r  r!  r   r   r   r   r     s        C CJ ,OOOMMMOOOOOO$$$$++++4444&&&&''''%%%%####OOOMMMNNN$$$$ 04&*""e e e e e e^ u '+"&6:8<AE %)#'$(=A159=.2#'#'%)*.15 59-1.2.2*,/3  !%!%"Uu u u u u un=$ $ $ $
 
 
 
    Xj$ j$ j$ j$Z.$ .$ .$ .$n  pE pE pE pE pEd& & & &) ) ) ) ;/ ;/ ;/ \;/z      N N N N N Nr   r   c            	         e Zd ZU dZded<   	 ded<   	 ded<   ded	<   d ed
<   ded<   ded<   ded<   ddddddddddd"Zedd$            Zedd%            Zedd'            Z	e
dd)            Zdd*Z	 dddddddd+dd7Z	 dddd8dd;Ze
dd=            Zdd?Zdd@ZddAZddBZddCZddDZddEZddFZddGZddHZddIZddJZddKZddLZddMZddNZddOZ ddPZ!ddQZ"ddRZ#ddSZ$ddTZ%ddUZ&ddVZ'ddWZ(ddXZ)ddYZ*ddZZ+dd^Z,dd_Z-dd`Z.dddfZ/e
ddh            Z0e
ddi            Z1eddj            Z2eddk            Z3e
ddl            Z4e
ddm            Z5e
ddn            Z6eddo            Z7e
ddq            Z8eddr            Z9edds            Z:eddt            Z;eddu            Z<eddv            Z=eddx            Z>e
ddy            Z?e
ddz            Z@e
dd{            ZAedd|            ZBedd}            ZCedd~            ZDedd            ZEe
dd            ZFedd            ZGedd            ZHedd            ZIe
dd            ZJe
dd            ZKe
dd            ZLe
dd            ZMe
dd            ZNedd            ZOedd            ZPe
dd            ZQe
dd            ZRedd            ZSdS )r   aS  Read image and metadata from TIFF file.

    TiffFile instances must be closed with :py:meth:`TiffFile.close`, which
    is automatically called when using the 'with' context manager.

    TiffFile instances are not thread-safe. All attributes are read-only.

    Parameters:
        file:
            Specifies TIFF file to read.
            Open file objects must be positioned at the TIFF header.
        mode:
            File open mode if `file` is file name. The default is 'rb'.
        name:
            Name of file if `file` is file handle.
        offset:
            Start position of embedded file.
            The default is the current file position.
        size:
            Size of embedded file. The default is the number of bytes
            from the `offset` to the end of the file.
        omexml:
            OME metadata in XML format, for example, from external companion
            file or sanitized XML overriding XML in file.
        _multifile, _useframes, _parent:
            Internal use.
        **is_flags:
            Override `TiffFile.is_` flags, for example:

            ``is_ome=False``: disable processing of OME-XML metadata.
            ``is_lsm=False``: disable special handling of LSM files.
            ``is_ndpi=True``: force file to be NDPI format.

    Raises:
        TiffFileError: Invalid TIFF structure.

    r   r/  r	   r"  r.   r0  r   r   _parentzdict[str | None, TiffFile]_filesr   r1  zodict[int, Callable[..., tuple[NDArray[Any] | None, tuple[int, int, int, int, int], tuple[int, int, int, int]]]]	_decodersN)rt   ru   rv   rw   r   r   r   r+  r   r   rt   r   ru   rv   r   rw   r   r   r   TiffFile | Noner   r   r  c              	   |
                                 D ][\  }}|d d         dk    r7|dd          t          j        v r!|t          | |t	          |                     Jt          d|           |dvrt          d|          d | _        |r=|                                dd          dk    rt          d          || _        d	| _	        t          |||||
          }|| _        |d	nt	          |          | _        |j        | i| _        i | _        |	| n|	| _        	 |                    d           |                    d          }	 dddd|d d                  }n%# t&          $ r}t)          d|          |d }~ww xY wt+          j        |dz   |dd                   d         }|dk    rzt+          j        |dz   |                    d                    \  }}|dk    s|dk    rt)          d||f           |dk    rt          j        | _        nVt          j        | _        nC|dk    r|dk    rt          j        | _        n$|
                    d|j        dk              r:|
                    dd	          rt          j        | _        nt          j        | _        nt          j        | _        n|dk    rK|dk    rt)          d          t?                                           | d           t          j        | _        nh|dv rRt?                                           | d|dd            |dk    rt          j        | _        n$t          j        | _        nt)          d!|           tC          |           | _"        | j#        rR| j$        j%        d"k    s,| j"        d         j&        d#k    s| j"        d#         j&        d#k    r| '                                 d S | j(        rb| j)        s[	 | j"        *                                 d S # tV          $ r2}t?                                           | d$|d%           Y d }~d S d }~ww xY w| j,        rV	 | -                                 d S # tV          $ r2}t?                                           | d&|d%           Y d }~d S d }~ww xY w|rd	| j"        _.        d S d S # tV          $ r |/                                  w xY w)'Nr   r   zunexpected keyword argument: >   NrrN  r  rM  invalid mode r  OME>zinvalid OME-XMLT)rt   ru   rv   rw   r   r  rk   rj   )rU  rV  s   EPr  znot a TIFF file rZ  rX  r  rY  zinvalid BigTIFF offset size r[  is_ndpiz.ndpii1N  zinvalid NIFF filez NIFF format not supported>   RO  RS  U   z RAW format 0x04X not supportedzinvalid TIFF version r|  rW   z) <TiffPages._load_virtual_frames> raised .128z <_ndpi_load_pages> raised )0itemsr   
FILE_FLAGSsetattrr   r   r   r1  stripis_omer.   r0  r   ru   r,  r-  r+  ra  readr  r   rj  unpackrg  r/  re  rh  rY  rH  NDPI_LErf  r=   errorr	   r"  is_lsmr  rw   r   _lsm_load_pagesis_scanimager_  _load_virtual_framesr  r3  _ndpi_load_pages	useframesr  )rp  r   rt   ru   rv   rw   r   r   r   r+  r   rn   rU  rq  headerr   r  versionrJ  zeros                       r   rs  zTiffFile.__init__  s    #..** 	G 	GJC2A2w%CGt$>$>$D#tE{{333 E E EFFF5555T55666 	||~~bcc"f,, !2333!DLDK4d6MMM","4$$$z:J:Jwo&ttGS	GGAJJJWWQZZFL$'C@@L		 L L L#$Av$A$ABBKL mIOVAaC[AA!DG"}}#)=T1A2771::#N#N 
D199
a'K
D7IKK   ## $DII $DIIB## $DII\\)R\W-DEE 0||It44 4$(L		$(O		 $DIIF""##'(;<<<$DDDEEE O		222HHWHHHH   ## $DII $DII#$EG$E$EFFF #4DJ{ ,$--:a=,11:a=,11$$&&&&&" ,4? ,J3355555    HHNN / /"%./ /          	,))+++++    HHNNJJcJJJ        
  ,'+
$$$, ,  	 	 	HHJJJ	s   !*R4 E!  R4 !
F+E>>FIR4 R4 +P 
Q'P=7R4 =Q
R4 Q# #
R-'RR4 RR4 4 SLiteral['>', '<']c                    | j         j        S )zByteorder of TIFF file.)r/  r   r  s    r   r   zTiffFile.byteorder  s     y""r   c                    | j         S )zFile handle.r  r  s    r   r  zTiffFile.filehandle  r  r   r   c                    | j         j        S )zName of file handle.)r0  ru   r  s    r   r  zTiffFile.filename   s     x}r   rb   c                |    	 t          j        | j                                                  S # t          $ r Y dS w xY w)z+Status of file handle's descriptor, if any.N)r  fstatr0  filenor  r  s    r   rQ  zTiffFile.fstat%  sE    	8DHOO--... 	 	 	44	s   *- 
;;c                p    | j                                         D ]}|j                                         dS )zClose open file handle(s).N)r,  valuesr  r  )rp  r   s     r   r  zTiffFile.close-  s@    ;%%'' 	# 	#CN  """"	# 	#r   )ro   rp   rq   r   rr   rs   rn   r   ro   int | TiffPageSeries | Nonerp   rq   r   r   rr   rs   r   c               ~   | j         st          j        g           S ||d}|| j         n3t          |t                    s| j        |         }||j        |         }||n|                    |          nt          |t          t          j	        f          rt          |                   gnvt          |t                    r	|         nXt          |t                    r$t          |t                    sfd|D             nt          dt          |                     t                    dk    rt!          d          |||j        | j        |j        j        z   }|j        j        rRt          |t                    r=|dk    r7|                    |          }	| j                            ||	|j                  }
n|                    |          }	|t5          ||	|j                  }| j                            ||j        |j        |          }
nXt                    dk    r2d         }|t!          d	          |                    |||
          }
nt=          |||
          }
|
J ||J |                    |          }		 |	|
_        n# t           $ rl}	 tA                      !                    | d|
j         d|	 d|d           d|	z   |
_        n$# t           $ r d|j        j        z   |
_        Y nw xY wY d}~nd}~ww xY wt                    dk    r3|d}d         }|t!          d	          |r|j        n|j"        |
_        n]|d}	 tG          d D                       }n"# tH          $ r}t!          d          |d}~ww xY w|J d|r|j        n|j"        z   |
_        |
S )aR  Return images from select pages as NumPy array.

        By default, the image array from the first level of the first series
        is returned.

        Parameters:
            key:
                Specifies which pages to return as array.
                By default, the image of the specified `series` and `level`
                is returned.
                If not *None*, the images from the specified pages in the
                whole file (if `series` is *None*) or a specified series are
                returned as a stacked array.
                Requesting an array from multiple pages that are not
                compatible wrt. shape, dtype, compression etc. is undefined,
                that is, it may crash or return incorrect values.
            series:
                Specifies which series of pages to return as array.
                The default is 0.
            level:
                Specifies which level of multi-resolution series to return
                as array. The default is 0.
            squeeze:
                If *True*, remove all length-1 dimensions (except X and Y)
                from array.
                If *False*, single pages are returned as 5D array of shape
                :py:attr:`TiffPage.shaped`.
                For series, the shape of the returned array also includes
                singlet dimensions specified in some file formats.
                For example, ImageJ series and most commonly also OME series,
                are returned in TZCYXS order.
                By default, all but `"shaped"` series are squeezed.
            out:
                Specifies how image array is returned.
                By default, a new NumPy array is created.
                If a *numpy.ndarray*, a writable array to which the image
                is copied.
                If *'memmap'*, directly memory-map the image data in the
                file if possible; else create a memory-mapped array in a
                temporary file.
                If a *string* or *open file*, the file used to create a
                memory-mapped array.
            maxworkers:
                Maximum number of threads to concurrently decode data from
                multiple pages or compressed segments.
                If *None* or *0*, use up to :py:attr:`_TIFF.MAXWORKERS`
                threads. Reading data from file is limited to the main thread.
                Using multiple threads can significantly speed up this
                function if the bottleneck is decoding compressed data,
                for example, in case of large LZW compressed LSM files or
                JPEG compressed tiled slides.
                If the bottleneck is I/O or pure Python code, using multiple
                threads might be detrimental.
            buffersize:
                Approximate number of bytes to read from file in one pass.
                The default is :py:attr:`_TIFF.BUFFERSIZE`.

        Returns:
            Images from specified pages. See `TiffPage.asarray`
            for operations that are applied (or not) to the image data
            stored in the file.

        Nr   c                     g | ]
}|         S r   r   )r   r   r"  s     r   r:  z$TiffFile.asarray.<locals>.<listcomp>  s    +++!U1X+++r   z0key must be an integer, slice, or sequence, not zno pages selectedr   r   rW   zpage is None)r   rr   rs    <asarray> failed to reshape  to 	, raised r9  r8  Tc              3     K   | ]}||V  	d S r   r   r   ps     r   r   z#TiffFile.asarray.<locals>.<genexpr>  s"      ??1Q??r   zpages are all None)%r"  r  arrayr   r
   ro   r   _getlistr   integerslicerP   r   r   r~  r   r   r!  r   r~   r%  keyframer#  	get_shaper  memmap_arrayr6   
read_arrayrw   r   stack_pagesr   r=   rs  r   r  StopIteration)rp  rn   ro   rp   rq   r   rr   rs   typecoder   r  page0r  r"  s                @r   r   zTiffFile.asarray2  s   T z 	#;r??";6>F
 >JEEfn55 -V, u-E;^NN3''EEc5=122 		3s88_%EEU## 	#JEEX&& 	z#s/C/C 	++++s+++EEN499NN   =CJJ!OO0111 K"!-~(99H.sC(( 8OO ((1155eV%6 
 ((11?'UFLAAC33K%	 4   ZZ1__!HE} 000]]J: #  FF !3:*  F !!!;%%%$$W--EA$ 
A 
A 
A	AHH$$ J J!<J J-2J J=@IJ J  
 $)5=FLL! A A A#(6?+@#@FLLLA
A ZZ1__!HE} 000*1C5;;u|FLL@???????  @ @ @ !566C?@$$$ 7$LEKKMFLsN   J! !
L,<K)(L)L
L	L

LL%M? ?
N	NN)ro   rp   r   ZarrTiffStorec                  | j         st          d          || | j        d         j        dd|i|S || j         }nDt	          |t
                    s| j        |         }| |j        dd|i|S ||j        |         }|}t	          |t          t          j	        f          r||         } |j        di |S t          d          )a*  Return images from select pages as Zarr store.

        By default, the images from the first series, including all levels,
        are wrapped as a Zarr store.

        Parameters:
            key:
                Index of page in file (if `series` is None) or series to wrap
                as Zarr store.
                By default, a series is wrapped.
            series:
                Index of series to wrap as Zarr store.
                The default is 0 (if `key` is None).
            level:
                Index of pyramid level in series to wrap as Zarr store.
                By default, all levels are included as a multi-scale group.
            **kwargs:
                Additional arguments passed to :py:meth:`TiffPage.aszarr`
                or :py:meth:`TiffPageSeries.aszarr`.

        zempty Zarr arrays not supportedNr   rp   zkey must be an integer indexr   )r"  r  ro   rm   r   r
   r   r   r  r`  r   )rp  rn   ro   rp   r   r"  r  s          r   rm   zTiffFile.aszarr  s    : z 	I%&GHHH;6>(4;q>(??u???? >JEEfn55 -V,{$v};;5;F;;; u-EcC/00 	)).sD4;(((((6777r   list[TiffPageSeries]c                   | j         sg S | j         j        J | j         j        }| j         j        j        }d}dD ]c}t	          | d|z   d          rM t	          | d|z                         }|s.|dk    r!| j        r| j                                          Z|dk    ra nd|s|                                 }|| j         _        | j                             |           |J t          |          D ]\  }}||_
        |S )zSeries of pages with compatible shape and data type.

        Side effect: after accessing this property, `TiffFile.pages` might
        contain `TiffPage` and `TiffFrame` instead of only `TiffPage`
        instances.

        N)r   lsmmmstackr   r   ndtifffluoviewstksissvsscnqpindpibifavsphilips	scanimagenihmdgeluniformr   F_series_r   ro  )r"  rb  rH  r  getattr	is_imagej_clear_series_genericset_keyframer  _index)rp  rH  rb  ro   rW  r  r  s          r   ro   zTiffFile.series  sA    z 	Iz"...J(	:&,.2
 #	 #	D. tUT\511 9zD'899;; 	!u}}} 
))+++ y((   	,))++F(

))) !!!f%% 	 	DAqAHHr   list[TiffPageSeries] | Nonec                z   d| j         _        | j                             d           | j         j        }|j        p|j         }| j                             |          }t          |          dk    r|j        }|j	        }n"t          |          f|j        z   }d|j	        z   }|j
        }t          ||||d          gS )z+Return all images in file as single series.Tr   validaterW   r  r~  rW  )r"  rH  r  firstrE  is_nihr_  r   r   r  r~   r
   )rp  r  r  r"  r   r  r~   s          r   _series_uniformzTiffFile._series_uniform]  s    #

"""z)8T[9
##X#66u::??JE9DDZZMDJ.E?D
ueUDyIIIJJr   c           
     D   | j         }|                    d           d|_        |j        r|                                 g }g i dfd}|D ]} ||           |j        t          |j                  D ]\  }}|dk     r	 | j                            |           t          | |j
        |f          } ||           J# t          $ r1}t                                          | d	|d
           Y d}~d}~ww xY wD ]n}	|	         }
|
d         }t          |
          f|j        z   }d|j        z   }d|vr
|dz  }|dz  }|                    t%          |
||j        |d                     ot          |          dk    | _        | j        st-          |           |S )zgReturn image series in file.

        A series is a sequence of TiffPages with the same hash.

        Fr  TiffPage | TiffFramer   r  c                   | j         sd S | j        }|v r;|         D ]}|j        | j        k    r d S |                             |            d S                     |           | g|<   d S r   )r   hashrv   r   )r  rn   r]  keys
seriesdicts      r   addpagez)TiffFile._series_generic.<locals>.addpage}  s    : )Cj  #C 1 1Ax4;.. / sO**400000C   #'&
3r   NrY  z generic series raised r9  r   r  Sr  genericr  rW   )r  r  r   r  )r"  r  rH  cache_loadrt  r  r0  ra  r   r  r  r=   rs  r   r   r  r   r
   r~   
is_uniform
is_agilentpyramidize_series)rp  r"  ro   r  r  r  rv   subifdr  rn   pagelistr   r  r  r  s                @@r   r  zTiffFile._series_genericm  s1    
U; 	KKMMM<>
	) 	) 	) 	) 	) 	) 	)  	( 	(DGDMMM|'!*4<!8!8 ( (IAvzz (f---!)$Q!@!@   %   ((#JJcJJJ         	 	C!#HA;D]]$tz1E?D$MMeTZI      f++* 	&f%%%s   1C
C='C88C=c                     d fdd fdd j         _          j         g           }|dS t          |          dk     _        t	          |d           |S )z8Return image series in tifffile "shaped" formatted file.ro   rl  r"  !list[TiffPage | TiffFrame | None]r  r   r   r   rz  tuple[int, ...]ru   r   r  r   r   r  c               ,   t          |d         t                    sJ |d         }t          |j        |          s>t	                                          d|j         dt          |                      d}nd}|s||=|j        }|j        }t          |          dk    rt          |          f|z   }d|z   }|r|}t          |          }	t          |          }
|j
        r!|
|	k    r|
|	z  dk    r|d}d|z   }|
|	z  f|z   }	 t          |||          }|}n># t          $ r1}t	                                          d|d	           Y d }~nd }~ww xY w|                     t          |||j        ||d
t#          |          d                     d S )Nr   z2 shaped series metadata does not match page shape r  TFrW   Qz) shaped series failed to reshape, raised r9  r   )ru   rW  r  rq   )r   r   check_shaper   r=   rs  r  r  r   rD   is_contiguousrF   r   rB  r   r
   r~   r   )ro   r"  r  r   rz  ru   r  r  failedrw   resizer  rp  s               r   r   z'TiffFile._series_shaped.<locals>.append  s.    eAh111118Dtz733    C C"&*C C27..C C    $
yu::>> ZZME1E:D $#G5>>DW%%F! 2ftmm8J8J$ $ITz4)E1#D%99    + +!*+ +       
 MMJ!"9oo!	 	 	    s   D 
E$'EE-TiffPages | list[TiffPage | TiffFrame | None]r  c          	        g }t          |           }d}	 ||k    rnt          | t                    r0|                     |           t	          t
          | j                  }nt	          t
          | d                   }|j        &t                      	                    d           d S d }d }t          |j                  }|                    dd          }	|d         }
|j        d nd}|                    d|          }d	|v rdt	          t          |d	                   }t          |          t          |
          k    r|
}n&d}t                      	                    d
           |g}t          |
          }|dk    r&t          |t          |j                            \  }}nd}d}|r&t                      	                    d           d S d|cxk     r	||z
  k    rn n|j        J ||j        j        z  }|rd}nt| |dz            }|j        r||j        |z   |j        k     r
|j        d}nCd}t+          |dz   ||z             D ]*}| |         }|J ||_        |                    |           + |||||
|	|           ||z  }|j        rLt          |j                  }t/          |j                  D ]"\  }}|dk     rg }t/          |          D ]\  }}	 ||j        t          |j                  |k     rt1          |d          j                            |j        |                    |dk    rt          |j        |f          }|}nt9          |j        |f|          }nA# t:          $ r4}t                      	                    d|d           Y d }~  d S d }~ww xY w|                    |           |r ||          }| d S |}$|S )Nr   Tz1 invalid shaped series metadata or corrupted fileru    r   Fr  r  z& shaped series axes do not match shaperW   z. shaped series shape does not match page shaperY  z contains invalid subifdsrb  z shaped series raised r9  )r   r   r	   r  r\   r   rb  rl  r=   rB  shaped_description_metadatarY  rt  r   rD   divmodr   _dtyper  is_finalrv   r  r   r  r   r0  ra  r  r   r  )r"  ro   rt  lenpagesr  rb  r  r   r   ru   rz  r  spagesrw   npagesmodr  r6  subifds_sizer  rv   r  	keysubifdr  series_or_noner   detect_seriesrp  s                            r   r  z.TiffFile._series_shaped.<locals>.detect_series  s    :<G 5zzHEt4H$$eY// 8&&u---#Hen==HH  $HeAh77H.6HHNN K K K    46/   ||FB//"7+$,$4$<DD%	$LLi@@	X%%Xf%566D4yyCLL00 '!#MMM   >FJw''!88"(wx~/F/F"G"GKFCCFC  HHNN H H H    4v1111E!111111#?666HO44D  4!"$UQY/$-4 $ 0 ($ 6 D D ( 0 8(-II ).I%*519efn%E%E 4 4',Qx'+'7'7'708 &d 3 3 3 3vvtUGT9MMM # &4#&x'7#8#8L%.x/?%@%@ $4 $4	6!A::$"$'0'8'8 3 3GAt,$(L'+|';'*4<'8'8<'G'G*4+/(L(L(L+& +& %& !%dl1o > > >#$66-5dTZO-L-LF06II-6(,)-Q1:.& .& .&F
 $- , , , &'+ %; %;.1$:%; %;!" !" !" (,ttttttt, $NN62222" 4-:]7F-K-KN-5'+tt%3Fit4j Ms   "BM44
N2>'N--N2TNrW   )	isreduced)ro   rl  r"  r  r  r   r   r   rz  r  ru   r   r  r   r   r  )r"  r  ro   rl  r   r  )r"  rH  r   r  r  )rp  ro   r   r  s   ` @@r   _series_shapedzTiffFile._series_shaped  s    7	 7	 7	 7	 7	 7	rF	 F	 F	 F	 F	 F	 F	 F	P  $
tz2..>4f++*&D1111r   c                   | j         }|dS | j        }d|_        |                    d           | j        j        }|                    dd                                          }|                    dd          }|                    dd          }|                    d	d          }|                    d
d          }|dk     s|dk     s|dk     s|dk     r&t                                          | d           dS |dk    r||z  }nM|j	        d         dk    r|j	        d         |k    r||z  }n%|||z  k    r|j	        d         |k    rd}n||z  |z  }|dk    r|j
        rt          |          }||j        z  }	|j        sd}
nx|j        d         |	z   | j        j        k    r&t                                          | d           dS |dk    rd}
n+|j
        r"|j        d         |	z   |d         j        k    rd}
nd}
|
r|g}n
|dd         }|dv rd}|||f}ns|dk    rd}|||f}ne|dk    rd}|||f}nW|dk    rd}|||f}nI|dk    rd}|||f}n;|dk    rd}|||f}n-d}|||f}t                                          | d|           |t'          |          z  }|dk    r/t                                          | d           |f|z   }d|z   }|j	        d         dk    r3|d         dk    sJ |dd         |j        z   }||j        dd         z  }n||j        z  }||j        z  }d|vr
|d z  }|dz  }|
o|j
         o
|j        |	k    }d| _        t1          |||j        |d!|"          gS )#z#Return image series in ImageJ file.NTr   ordercztrx  rW   sliceschannelsrk  z1 ImageJ series metadata invalid or corrupted filer  F>   r  defaultTZCctzZTCzctTCZztcCTZtczZCTtzcCZTz  ImageJ series of unknown order z. ImageJ series contains unidentified dimensionr  rT  r  r  r  r   )rW  r  )imagej_metadatar"  rH  r  r  rY  lowerr=   rs  r   is_multipager   r  r  r$  r  rw   rB  rv   rD   debugr   r  r  r
   r~   )rp  metar"  r  r  rx  r  r  rk  r  	isvirtual	page_listr  r   remainr  s                   r   _series_imagejzTiffFile._series_imagej|  sx    #<4
1z%((..00(A&&(A&&88J**(A&&A::!vzzX\\HHLLL   4q==f_FF[^aDKNh$>$>f_FFv&&4;q>X+E+EHHf_x/FQ;;5-;ZZF$+%
 } 	IIa 6)DO,@@@HHNNLLL   4q[[II	 #f,uQx>> III  	!IIaaaI
 &&&DVX.EEe^^DVX.EEe^^DXv.EEe^^Dvv.EEe^^DXv.EEe^^Dvv.EEDVX.EHHDD5DD   75>>)A::HHNNIII   I%E:D;q>A8s????#2#J+EDIabbM!DDTZEDIDd??TMECKD Je00JT[F5J 	 
#  	
 		
r   c                J    |                                  }||D ]	}d|_        
|S )z5Return all images in NIH Image file as single series.Nr|  )r  rW  rp  ro   r  s      r   _series_nihzTiffFile._series_nih  s6    %%''  r   c                <   | j                             d          }| j         j        }|j        }d}| j        }|i }n|                    di           }d|v r	 |d         }	 t          |          }n# t          $ r d}Y nw xY wd}	 t          |d                   }	nM# t          $ r@}
d}t          |          |z  rt          d          |
t          |          |z  }	Y d}
~
nd}
~
ww xY w|#t          t          |          |	|z  z  d          }||	|f|j        z   }d	|j        z   }n># t          $ r1}
t                                          | d
|
d           Y d}
~
nd}
~
ww xY w|"t          |          f|j        z   }d|j        z   }t!          ||||d          gS )z&Return image series in ScanImage file.Fr  N	FrameDatazSI.hChannels.channelSaverW   zSI.hStackManager.framesPerSlicez"unable to determine framesPerSlicer  z ScanImage series raised r9  r  r{  r  )r"  r_  r  r~   scanimage_metadatarY  r   r   r   r  r   rq  r   r  r=   rs  r
   )rp  r"  r  r~   r   r  	framedatar  r  rx  r  r  s               r   _series_scanimagezTiffFile._series_scanimage  s%   
##U#33z
&<IIb11I%22 $%?@!"8}}HH  ! ! ! HHH! 	4 +L!MNNFF  4 4 4F5zzH, #(@ "# !ZZ83FFFFFF4 > U0A!BAFFF2TZ?ty(     DDDDD        =ZZMDJ.E?DueUD{KKKLLsf   D' "A2 1D' 2B>D'  BD' B D' 
C''6C"D' "C''?D' '
E"1'EE"c                ^   | j         }|dS | j                            d          }t          t	          |d                             }d                    d |D                       }t          d |D                       }d| _        t          |||d	         j	        ||d
         d          gS )z%Return image series in FluoView file.NFr  
Dimensionsr  c              3     K   | ]<}t           j                            |d                                          d          V  =dS )r   r  N)r   MM_DIMENSIONSrY  rT  r  s     r   r   z,TiffFile._series_fluoview.<locals>.<genexpr>L  sA      OOQt)--adjjllC@@OOOOOOr   c              3  @   K   | ]}t          |d                    V  dS r  r  r  s     r   r   z,TiffFile._series_fluoview.<locals>.<genexpr>M  s,      ..Ac!A$ii......r   Tr   	ImageNamerq  ru   rW  )
fluoview_metadatar"  r_  rA  reversedr   r  r  r
   r~   )rp  r  r"  mmhdr  r   s         r   _series_fluoviewzTiffFile._series_fluoviewE  s    %<4
##U#33HT,/0011wwOO$OOOOO.......a+&  	
 		
r   c                   | j         }|dS d| j        _        | j                            d           |d         dv rQt	          j        t          j                  }|d         d         d         z  |d         dk    rdfd}n	dfd}nd}| j        j        }d| _        t          |g|j
        ||j        |d          gS )z#Return image series in MD Gel file.NFr   FileTag>   r  r  
ScalePixelrW   r  ar   r   c               N    |                      t          j                  dz  z  S )Nr  r5   r  float32r  scales    r   	transformz)TiffFile._series_mdgel.<locals>.transformj  s!    88EM22a7%??r   c               H    |                      t          j                  z  S r   r  r  s    r   r  z)TiffFile._series_mdgel.<locals>.transformo  s    88EM22U::r   r}  )r  rW  )r  r   r   r   )mdgel_metadatar"  rH  r  r  r~   r  r  r  r
   r   r  )rp  r  r~   r  r  r  s        @r   _series_mdgelzTiffFile._series_mdgelZ  s    "<4$

"""	?h&&K..E&E!HuQx'EI!##@ @ @ @ @ @ @
; ; ; ; ; ; ; Iz
	#  	
 		
r   c                   |                                  }|dS |D ]}d|_        |j        d         dk    r-|                    |j        d|j        dd         z   dd           |j        r+|j        j                            d          }|d	n||_	        y|j        j                            d
          }||dk    rd|_	        |dk    rd|_	        d| _
        |S )z+Return pyramidal image series in NDPI file.Nrw  r   r  ZrW   T  Baseline  g      Macrog       MapF)r  rW  r  _set_dimensionsr   is_pyramidalrb  r  valueofru   r  )rp  ro   r  ru   mags        r   _series_ndpizTiffFile._series_ndpi  s    %%''>4 	# 	#AAFvayC!!!'3+;T4HHH~ z..u55'+|*/))%00C$;;$AFFD[["AFr   c                   |                                  }|dS t          |          dk    r3t                                          | dt          |                      |d         }d|_        |j        d         dk    r-|                    |j        d|j        dd         z   dd	           |j        rd
|_	        t          |          dk    r4d|d         _	        d|d         _        d|d         _	        d|d         _        d| _
        |S )z*Return pyramidal image series in AVS file.Nr   z# AVS series expected 3 series, got r   ry  r  r  rW   Tr  r  r  r  F)r  r   r=   rs  rW  r  r  r   r  ru   r  r  s      r   _series_avszTiffFile._series_avs  s	   %%''>4v;;!HHKKc&kkKK   1I6!9agsQVABBZ'7tDDD> 	 AFv;;!"F1IN"F1IN$F1IN"F1INr   c                v
   ddl m} g }| j        }d|_        d|_        |                    d           |                                 | j        }|J 	 |                    |          }n?# |j	        $ r2}t                                          | d|d           Y d}~dS d}~ww xY wd |                    d          D             }t          |          d	k     r6t                                          | d
t          |          d           dS i }g |d<   g |d<   |D ]}	t          |	t                    sJ |	j                            d          r|	g|d<   :|	j                            d          r|	g|d<   [|	j        s|d                             |	           ~|d                             |	           |                    d          }
t          |
          t          |          k    rEt                                          | dt          |
          dt          |                     dS |
d         j        }|
d         j        }|d         \  }}t/          |
dd         |dd                   D ]\  }\  }}|j        }	|t3          t5          ||z                      z  }|t3          t5          ||z                      z  }|	j        |	j        z
  |k    rWt                                          | d|	j        d|	j        d|	j        d|	           |	xj        |	j        dz
  z  c_        nI|	j        |k     r7t                                          | d|	j        d|	j        d|           n||	_        |	j        }|	j        |	j        z
  |k    rWt                                          | d|	j        d|	j        d|	j        d|	           |	xj        |	j        dz
  z  c_        n||	_        |	j        }|	j        d         dk    r|||	j         d         f|	_         n0|	j        d         dk    r|	j         d         ||f|	_         n	||f|	_         |	j        dd	         ||fz   |	j        dd         z   |	_        tC          |
d         gdd          g}tE          |
dd                   D ]<\  }}	|d         j#                            tC          |	gd|dz    d                     =|$                                D ]0\  }}|D ](}	|                    tC          |	g|d                     )1d| _%        |S )z1Return pyramidal image series in Philips DP file.r   ElementTreeFNz Philips series raised r9  c           	         g | ]M}|j         	t          d |j                             dd                                          D                       NS )Nc              3  4   K   | ]}t          |          V  d S r   )floatr   vs     r   r   z6TiffFile._series_philips.<locals>.<listcomp>.<genexpr>  s(      GGq%((GGGGGGr   "r  )textr  replacesplit)r   elems     r   r:  z,TiffFile._series_philips.<locals>.<listcomp>  sc     
 
 

 y$ GGDI$5$5c2$>$>$D$D$F$FGGGGG %$$r   z].//*/DataObject[@ObjectType="PixelDataRepresentation"]/Attribute[@Name="DICOM_PIXEL_SPACING"]r  z# Philips series len(pixel_spacing)=z < 2LevelOtherr  Labelz Philips series len(levels)=z != len(pixel_spacing)=rW   z Philips series page.index=z page.imagewidth=z-page.tilewidth=z >= imagewidth=z < imagewidth=z page.imagelength=z-page.tilelength=z >= imagelength=rT  r  rz  r  )&	xml.etreer  r"  r  rH  r  r  philips_metadata
fromstring
ParseErrorr=   rB  findallr   r   r   r   r  is_tiledr   pop
imagewidthimagelengthr  rb  r   round	tilewidthrs  r  
tilelengthr   r   r
   r  r   r:  r  )rp  etreero   r"  r  treer  pixel_spacingseries_dictr  r   imagewidth0imagelength0h0w0seriehrP  r  r  r  rn   rU  s                          r   _series_philipszTiffFile._series_philips  s   222222
1$	##D))DD 	 	 	HHNNdIISIIIJJJ44444	
 
: 
 
 
 }!!HHNNDD3}+=+=DDD   413!G!G 		2 		2DdH-----**733 2(,vG$$!,,W55 2(,vG$$] 2G$++D1111G$++D1111))v;;#m,,,,HHNN ; ;v;;; ;%(%7%7; ;   4 Qi*ay,q!B ]122->?? +	 +	ME6Aq>D %E!b&MM(:(::J&#eAFmm*<*<<K/:==   M Mtz M MM M*..M M?IM M   4>A#55:--   : :tz : :: :,6: :   
 #-J$/1[@@   P Ptz P P'P P+/?P PALP P     DOa$77    $/ *K{2""):tz"~F

Q!##"jm[*E

):6
BQB;
";;dk"##>NN KK !&):INNNO ,, 	 	GAt1I##vOAEOO)LLL    &++-- 	P 	PJC P PndV#INNNOOOOP  s   A) )
B%3'B  B%c                l   ddl m} |                                 }|t          |          dk    r|S 	 |                    | j        j        j                  }n@# |j        $ r3}t                      
                    | d|d           |cY d}~S d}~ww xY wd |                    d          D             }|D ]s}d	|_        |j        d         d
k    rK|j        d         t          |          k    r-|                    |j        d|j        dd         z   dd           |j        rd|_        td| _        |S )z1Return pyramidal image series in IndicaLabs file.r   r  NrW   z Indica series raised r9  c                (    g | ]}|j         d          S )ru   )attrib)r   channels     r   r:  z+TiffFile._series_indica.<locals>.<listcomp>8  s,     
 
 
'.GN6"
 
 
r   r+  indicar  r  Tr  F)r  r  r  r   r  r"  r  r   r  r=   rB  iterrW  r  r   r  r  ru   r  )rp  r  ro   r  r  channel_namesr  s          r   _series_indicazTiffFile._series_indica&  so    	322222%%''>S[[A--M	##DJ$4$@AADD 	 	 	HHNNdHHCHHHIIIMMMMMM	
 
26))I2F2F
 
 
  	$ 	$AAFvayCAGAJ#m2D2D$D$D!!!'3+;T4HHH~ $#s   $A 
B"(B
BBc                :   | j         }|dS | j                            d          }|d         }t          |          }d|v r%d|v r!|d         |j        z   }|d         |j        z   }n|f|j        z   }d|j        z   }d| _        t          |||j        |d	
          gS )z(Return image series in Olympus SIS file.NFr  r   r   r  r  Trs  r  )	sis_metadatar"  r_  r   r   r  r  r
   r~   )rp  r  r"  r  r  r   r  s          r   _series_siszTiffFile._series_sisE  s     <4
##U#33Qxu::d??v~~MDJ.E<$)+DDK$*,E?DueTZEJJJKKr   c           
     P   g }| j         }d|_        d|_        |                    d           |                                 | j         j        }g }d}d|j        z   }|j        }|j        }|t          |          k     rA||         }	|	j        |k    rn-|
                    |	           |dz  }|t          |          k     At          |          f|z   }
|
                    t          ||
||dd                     |t          |          k     rE||         }	|
                    t          |	g|	j        |	j        |	j        d	d                     |dz  }|j        r|t          |          k     r|d         d
z  |d         d
z  f|d
d         z   }g }|t          |          k     rA||         }	|	j        |k    rn-|
                    |	           |dz  }|t          |          k     At          |          t          |d         j                   k    rnYt          |          f|z   }
|d         j        
                    t          ||
||dd                     |t          |          k     |d         j        r|t          |          k     r||         }	|
                    t          |	g|	j        |	j        |	j        dd                     |dz  }|t          |          k     r@||         }	|
                    t          |	g|	j        |	j        |	j        dd                     d| _        |S )z,Return image series in PerkinElmer QPI file.TFr   r  rW   r  rv  r  	Thumbnailr  N
Resolutionr  r  )r"  r  rH  r  r  r  r  r~   r   r   r   r
   r  r   r  r  )rp  ro   r"  ri  r  r  r  r~   pshaper  r   s              r   _series_qpizTiffFile._series_qpiW  s~   
1
  UZc%jj  <DzV##KKQJE c%jj   Tv%eUDz  	
 	
 	
 3u::<DMMFJJI$  	 	 	 QJE> 	#e**$$ )q.&)q.9F122JFc%jj(( <DzV++KK%%%QJE c%jj(( t99F1IO 4 444Tv-q	 ''"eUD|%     #e**$$$ !9! 	ec%jj&8&8<DMMFJJI   	 	 	 QJEs5zz!!U|"

	$"  	 	 	  r   c                   | j         j        j        sdS g }d| j         _        d| j         _        | j                             d           | j                                          | j         j        }t          | j                   dk    r-d| _        t          |g|j
        |j        |j        dd          gS | j         d         }t          |g|j
        |j        |j        d	d          }|j
        |gi}d
}|t          | j                   k     rt          t          | j         |                   }|j        r|j        rnR|j
        |v r!||j
                                     |           n|g||j
        <   |dz  }|t          | j                   k     t          ||j
                           t#          fd|                                D                       s&t'                                          | d           dt          ||j
                 f|j
        z   |j        d|j        z   dd          }|                                D ]\\  }}	||j
        k    r|	d         }|j                            t          |	f|j
        z   |j        d|j        z   dd                     ]|                    |           |                    |           t/          d
          D ]}
|t          | j                   k    r nr| j         |         }t1          |t                    sJ |j        dk    rd}nd}|                    t          |g|j
        |j        |j        |d                     |dz  }d| _        |S )z'Return image series in Aperio SVS file.NTFr   rW   r  rt  r  r4  r  c              3  >   K   | ]}t          |          k    V  d S r   r   )r   rp   zsizes     r   r   z'TiffFile._series_svs.<locals>.<genexpr>  s.      DD53u::&DDDDDDr   z% SVS series focal planes do not matchr  r5  	   r  r  )r"  r  r  r  rH  r  r  r   r  r
   r   r~   r  r\   r   
is_reducedr   rr  rT  r=   rs  r:  r   r  r   r   )rp  ro   	firstpager  	thumbnailr   r  baseliner   rp   r	  ru   r;  s               @r   _series_svszTiffFile._series_svs  s   z( 	4
$

"""
 J$	tz??a#DOKOON#  	 	 z!}"FJJI
 
 
	 /I;/c$*oo%%$*U"344D= DO zV##tz"))$////&*Vtz"QJE c$*oo%% F9?+,,DDDDFMMOODDDDD 	HHMMMNNNE!9?#Hy&O). 
 
 
 #LLNN 	 	LE5	''8DO""Htz)J$)O%  	 	 	 	 	hi    q 	 	ADJ'':e$DdH-----1$$MMFJJI  	 	 	 QJEEr   c                z   ddl m} | j        j        j        }|                    |          }g }d| j        _        d| j        _        | j                            d           | j        	                                 |D ]6}|j
                            d          s|D ]}|j
                            d          s|j                            dd          }|D ]}|j
                            d	          si }	|D ]l}
|
j
                            d
          st          |j                            dd                    dk    rt          d          t          |
j        d                   }t          |
j        d                   }t          |
j                            dd                    }t          |
j                            dd                    }t          |
j                            dd                    }t          |
j        d                   }||	v r9|	|         }||d         k    r||d<   ||d         k    r||d<   ||d         ||f<   \||g||||f|id|	|<   n|	sg }t!          |	                                          D ]\  }}|d         dz   |d         dz   f}d}dgt%          |          z  }t!          |d                                                   D ]$\  \  }}}| j        |         |||d         z  |z   <   %|d         J ||d         j        z  }||d         j        z  }|d         j        }|                    t/          ||||| |d                     |d         j                            |dd                    |                    |d                    ِ8d| _        |S )z0Return pyramidal image series in Leica SCN file.r   r  TF
collectionimageru   Unknownpixels	dimensionsizeZrW   z@SCN series: Z-Stacks not supported. Please submit a sample file.sizeXsizeYr  zr0  r  r  sizezr  )rw   r  rL  r  CZNru  parentru   rW  )r  r  r"  r  r   r  r  rH  r  r  r9  endswithr*  rY  r   r  r|  r:  rD   r  r   r~   r   r
   r   extendr  )rp  r  scnxmlrootro   rC  rD  ru   rF  resolutionsrG  sizexsizeyr  rK  r0  r  rp   r   r   r  r  r~   s                          r   _series_scnzTiffFile._series_scn  sM    	322222!-''
$

"""
 H	- H	-J>**<88 # E- E-y))'22 |''	::# A- A-F!:..x88 ! =?K%+  	(}55kBB %$u|//;;<<q@@"5!?# #  !$I$4W$= > > #I$4W$= > >	 0 4 4S! < <==	 0 4 4S! < <==	 0 4 4S! < <==!)"25"9::++$/NE 5#44445j 1 5>1112g47E&M1a&11 */,-)**+Q	. .KNN ' ! F$*;+<+<+>+>$?$?  5!*-1!'NQ.2  $ !C#ENNC+ ,2%-2E2E2G2G+H+H E EKFQC59Z_DU1X!122#Aw222Q,a. $Q* $ % % $'+%)%*  
 
 
 
 1I$++F122J777MM&),,,,CA-	E-N  r   c                   g }d}d| j         _        d| j         _        | j                             d           | j                                          | j         D ]y}t          t          |          }|j        dd         dk    r9|                    t          |g|j
        |j        |j        dd                     d|j        d	k    s|j        dd
         dk    r9|                    t          |g|j
        |j        |j        d	d                     d|j        vr9|                    t          |g|j
        |j        |j        dd                     |=t          |g|j
        |j        |j        dd          }|                    d|           <|j                            t          |g|j
        |j        |j        dd                     {t                                          | d           d| _        |S )z.Return image series in Ventana/Roche BIF file.NTFr   r  r  rx  r  r4     Probabilityrp   rE  r  r5  z! BIF series tiles are not stiched)r"  r  rH  r  r  r\   r   r   r   r
   r   r~   r  insertr   r=   rs  r  )rp  ro   r@  r  s       r   _series_bifzTiffFile._series_bify  sV   *.
$

"""
J ;	 ;	D$''D#w.."

	$"  	 	 	 	  K//#CRC(M99"

	("  	 	 	 	  000"

	&"  	 	 	 	 !)FJJI#   a****&&"

	)"  	 	 	 	 	DEEEFFFr   c                   567 ddl m} | j        }|dS 	 |                    |          }n?# |j        $ r2}t                                          | d|d           Y d}~dS d}~ww xY wd}dMd} ||            |j                            dd          }|| i| _	        | j
        j        }d}	g }
i }g }|D ]}|j                            d          r't                                          | d            n|j                            d          rf|D ]b}|j                            dd                              d          s2i x||j        d         <   }|D ]}|D ]}|D ]}|j        dd                             d          s&|j        d         }|j                            dd          }t          j        |         }d|j        v rt#          |j                            dd                    }t#          |j        d                   }t#          |j        d                   |z   }t%          t'          j        |||                    }nt%          d |D                       }||f||<   d|j                            d          s|D ]+}|j                            d          r|j        d         } n,d}|j        55                    dd          }|D 	]}|j                            d          s|j        5d                    t-          5d                              }5fd!|D             6g }d7d"}|D ]}|j                            d#          r|j        5|rHd$}t/          5                    d%7                    77dk    r67fd&t1          |          D             6n6t/          5                    d%d                    7k    rt3          d'          |j                            d(          s|j        5t/          5                    d)d                    } t/          5                    d*d)5v rdnd                    }!t/          5                    d+|!                    }!5fd,|dd-         D             }"	 t/          t'          j        |"6dd-                             }#n?# t2          $ r2}t                                          | d.|d           Y d}~d}~ww xY w|D ]}$|$j                            d          s|u|$j        n|$j                            d/d                                          | j                                        k    r&|$j        }| j	        d         | j	        |<   | j	        d= nB|$j        | j	        vr3| j        s
g c c c c S |$j        d/         }%	 | j         j!        st2          tE          tF          j$                            ||%          | 0          }& ||&           n# tJ          tL          t2          f$ r}|	dk    r+t                                          | d1|%d2|dd3           |	dz  }	|!r|!}n|dk    rt3          d4          ||'                    dg||#z   t%          |          z
  z             Y d}~ nd}~ww xY w|&| j	        |$j        <   |&(                                 | j	        |$j                 j)        }'	 |!r|!nt%          |'          }|'                    dg||#z   t%          |          z
  z             tU          |          D ]}(|'| |(z            ||#|(z   <   n># tV          $ r1}t                                          | d5|d           Y d}~nd}~ww xY w n| j)        }'	 |!r|!nt%          |'          }|'                    dg||#z   t%          |          z
  z             tU          |          D ]}(|'| |(z            ||#|(z   <   # tV          $ r2}t                                          | d5|d           Y d}~d}~ww xY w|rtY          d6 |D                       rx|D ]&})|)"|)|)j-        k    rt]          t^          |)          }* n't1          |          D ]\  }(})|)|)j0        j         j1        }+|+r|)j0        j         2                                 |)j0        j)        3                    |)j4                   t]          t^          |)j0        j)        |)j4                           }*|*||(<   |+r|*j0        j         (                                  nd$},|D ]})|)r|)j0        |*j0        k    rd"}, n7dk    rH|*j5        dk    r67gz  6|d7z  }n16dd-         7gz   6d-d         z   6|dd-         d7z   |d-d         z   }d7|vr6dgz  6|d7z  }tm          to          6          |*j8        z  d          }|t%          |          k     rAt                                          | d8| d9t%          |                      |d|         }ns|t%          |          k    r`t                                          | d:|t%          |          z
   d;           |'                    dg|t%          |          z
  z             ts          6|          d         }-|*j:        tw          |-t%          |*j:                   d                   k    rZt                                          | d<|*j:         d=tw          |-t%          |*j:                   d                    d>           ~g|*j0        j         j<        |*i}.t1          |          D ]\  }(}/|/|/j0        j         }0|0j<        |.vr|/j-        |/k    rs|0j1        }+|+r|02                                 |/j0        j)        3                    |/j4                   |/j0        j)        |/j4                 }/|/||(<   |+r|0(                                 t]          t^          |/          |.|0j<        <   |/j-        |/k    r|.|0j<                 |/_-        |
=                    |           |=                    t}          |6|*j?        || ||,d?@                     ~	|	dk    r't                                          | d1|	 dA           t          ||
          D ]\  }1}||vr
t          |1B                    d$                    6|1C                    d$          }||         D                                D ]\  }\  }}|4                    |          }(6|(         |k    r|E                    ||d          }A6|(xx         |z  cc<   6F                    |(dz   |           |E                    |||z   d          }|1G                    6|d           |D ]C}1|1j-        }*|*jH        t%          | j	                  dk    r't                                          | dB            ntU          t%          |*jH                            D ]}2d$}3g }|1j)        D ]}/|/|/jH        |/jH        |2         dCk     r|=                    d           2|/j0        j         I                    |/jH        |2                    |/j-        |/k    rt_          | |/j4        |2dz   f          x})}*d"}3n-|3st          dD          t          | |/j4        |2dz   f|*E          })|=                    |)           tY          dF |D                       r,t                                          | dG|2dz    dH            nt          |1B                    d$                    6|1C                    d$          }t1          |          D ]&\  }(}4|4dIk    r|*jL        6|(<   |4dJk    r
|*jM        6|(<   '|1jN        =                    t}          |tw          6          |*j?        || dK|2dz    d?L                     ѐEt%          |          dk    ot%          |d         jN                  dk    | _O        |S )Nz(Return image series in OME-TIFF file(s).r   r  Nz OME series raised r9  rT  r   r   r   r  c                   d| j         _        d| j         _        | j                             d           | j                             d            d S )NTr   )r"  r  rH  r  r  )r   s    r   
load_pagesz(TiffFile._series_ome.<locals>.load_pages  sE    "CIO"&CII""1%%%IOOD!!!!!r   UUID
BinaryOnlyz6 OME series is BinaryOnly, not an OME-TIFF master fileStructuredAnnotations	Namespacer  moduloIDAlongTypeotherStartSteprW   Endc                F    g | ]}|j                             d           |S )r  )r9  rP  )r   labels     r   r:  z(TiffFile._series_ome.<locals>.<listcomp>  s>     )* )* )*05/4y/A/A'/J/J)*,1)* )* )*r   ImageAnnotationRefNamePixelsDimensionOrderc                @    g | ]}t          d |z                      S )Sizer  r   axattrs     r   r:  z(TiffFile._series_ome.<locals>.<listcomp>   s*    ???BT&2+.//???r   TChannelFSamplesPerPixelc                H    g | ]\  }}|d k    r|         z  n|         S )r  r   )r   r  rv  r   spps      r   r:  z(TiffFile._series_ome.<locals>.<listcomp>-  sE     )" )" )"(-2 8:SyyE!HOOeAh)" )" )"r   z2OME series cannot handle differing SamplesPerPixelTiffDataIFD	NumPlanes
PlaneCountc                \    g | ](}t                              d |z   d                    )S )Firstr   )r   rY  ru  s     r   r:  z(TiffFile._series_ome.<locals>.<listcomp>?  s3    OOOrC2q 9 9::OOOr   r}  z4 OME series contains invalid TiffData index, raised FileName)r+  z OME series failed to read rZ  z. Missing data are zeroedz*OME series missing NumPlanes or PlaneCountz0 OME series contains index out of range, raised c              3     K   | ]}|d u V  	d S r   r   r  s     r   r   z'TiffFile._series_ome.<locals>.<genexpr>  s&      ";";19";";";";";";r   r  z OME series expected z frames, got z OME series is missing z  frames. Missing data are zeroedz1 OME series cannot handle discontiguous storage (r  )r   )rO  ru   	multifilerW   filesz+ OME series cannot read multi-file pyramidsrY  zno keyframe foundr  c              3     K   | ]}|d u V  	d S r   r   )r   ifd_or_nones     r   r   z'TiffFile._series_ome.<locals>.<genexpr>H  s'      CC{{d*CCCCCCr   z OME series level z	 is emptyXYzlevel rN  )r   r   r   r  )Pr  r  ome_metadatar  r  r=   rB  r*  rY  r,  r0  dirnamer9  rP  r  r   
AXES_CODESr  r   r  aranger   r  r   r  r   ravel_multi_indexrs  r
  r  r  r   r  is_filer   r  pathrb  rc  rQ  r  r"  r  
IndexErrorrr  rb  r\   r   rO  closedopenr  r  r   rq  rD   rw   squeeze_axesr   r  ru   r   r
   r~   r  rA  rc  get_axesr:  r  r[  r  rt  ra  rg  r   r  r  r   r  )8rp  r  r   rS  r  rw   r_  	root_uuidr  files_missing	modulorefrd  ro   elementannotr  rU  	modulo_nsalongr  newaxisstepstartstopr  annotationrefru   rF  r  r  r  r   	ifd_indexnumidxsidxuuidfnamer   r"  r  r  rb  isclosedr  squeezed	keyframesr  rq  aseriesrp   found_keyframerv  rw  r   r{  s8                                                        @@@r   _series_omezTiffFile._series_ome  s    	322222">4	##F++DD 	 	 	HHNNdEEEEEFFF44444	 	" 	" 	" 	" 	
4KOOFD11	 $'("	8:') i	 i	G{##L11  2 2 2   {##$;<< >$ > >E <++K<<EE   ! !799F5<-.!& > >). > >I)2 > >',y"~'>'>w'G'G !-$,',y}*/,*:*:67*K*K*./'*B#*el#:#:+01A1A&!1L1L+M+MD,1%,w2G,H,HE+0e1D+E+E+LD-0(-UD$(G(G.& .&FF .1)* )*9>)* )* )*.& .&F .5f,=D		+>>>2 ;''00   % %9%%o66 $)L$6ME !%>D88FD))D! t tz**844 }wwx-=(>??@@????$???" u uDx((33 !#{  $)E"%dhh/@#&F&F"G"GC"Qww)" )" )" )" )"1:4)" )" )" !*;Q!?!?@@CGG",!2# #  !8,,Z88 ! ;D #DHHUA$6$6 7 7Idhh{$AAANNOOCdhh|S99::COOOOT#2#YOOOD	!!%"9$crc
"K"KLL% ! ! !((# 3 3&)23 3  
 !! !% P P#x0088 %$%- $	 5 $
B ? ? E E G G#'=#6#6#8#8!9 !9
 )-	I59[5FDK	2 $D 1 1!Ydk99#'? * (*									$(K
$;E&'+'> !5*4$4&.$&GLL%$@$@$'" '" '" !+
3 ' 1 *$ & & &
 $1A#5#5$*HH$4$4+/ )B )B+0)B )B=@(K)B )B )B%& %& %&
 !. 2 $' !/+.DD%)RZZ*4)B+& +& ,/%/ !%TFdSj3t996L,M N N N %-&. 69DK	2IIKKK $DI 6 <
*-#=333u::D KK$*s4yy2H(IJJJ%*4[[ E E05i!m0DS1WE)   "HH,,#' !7 !7*- 6!7 !7         !%

*-#=333u::D KK$*s4yy2H(IJJJ%*4[[ E E05i!m0DS1WE)   "HH,,#' !7 !7*- 6!7 !7         s";";d";";";;;    " "C3#,+>+>#'##6#6 #,D// " "3?'*z'<'CH' = #
 5 : : < < <J,99#)DDD'+ (#**:39*E( (H '/DG' C ( : @ @ B B B!E + "	  C szX_<<$(	77,11# %crc
cU 2U233Z ?#CRCy3bcc:d??aSLECKD 75>>X]:A>>#d))##HH$$ N N/3N NBEd))N N    ;DDCII%%HH$$ 3 315D		1A3 3 3  
 KK$T*: ;<<< (t44Q7>U8S5H5H4H4J4J+K%L%LLLHH$$ F F$,NF F 3x~+>+>*>*@*@!ABBF F F  
 
 O.3X2	  ) ; ;GAt| /Bwi//=D00')yH' * "			 K-::4:FFF#';#4TZ#@D&*DG' + "


-1(D-A-A	"'*},,(1"'(:  ///" #!"+"	 	 	   Ditl 1HHKKmKKK  
 '*&)&<&< 	7 	7"G]F****51122E##E**D)/)>)D)D)F)F A A%owJJt$$8t##<<gq99DD!HHH%HHHLLQ---<<dWna@@DD##E46666  :	 :	G'H'4;!##  JJJ   s8#34455 0 0!&#M % %D</<.22D))) K*//U0CDDD},,)1 4:uqy"9* * h *.+ *+>???' 4:uqy"9H   KK$$$$CCdCCCCC HH$$IIUQYIII   EW..u5566''..&t__ 8 8EArSyy#+#6as#+#7a%%"e #1eai11"  
 
 
 
 f++*Is6!93C/D/D/Isx   , 
A('A##A(*S
S=	'S8	8S=	AXZ3*A=Z..Z31A"]
^'^

^A"`  
`<	
'`7	7`<	c           
     	   | j         }|d|vsd|vrdS |d         |d         }||dddf                                                  }dvsdvrdS t          j        |ddddf         d          d	z                                   dd	d
dd                    dd          rdnd}|                    dd          rdndz  }dddddt          fd|D                       t                    }t          fd|D                       d0fd }||j        d         k    }|r| j	        j
        s3t                                          | d!| j	        j                   d"}nd#| j        vr't                                          | d$           d"}nmd%v rId%         }| j                            |          s&t                                          | d$           d"}n | j                            d#          d         }|rt"          j                            | j	        j        |d&z             }t+          j        |          }	t-          |	          d	k    rd"}ndg|z   || |          }
|	D ]}| j        t"          j                            |          d'         k    r1t/          |          5 }t1          |j	        dh          d         }||dddf                                                  }|
 |||          z  }
ddd           n# 1 swxY w Y   |rnE||j        d         k    r!}t          j        |ddddf         d          }t          j        |ddddf         d          }|                                }|ddddfxx         |z  cc<   t          d( t7          |                                |                                          D                       t          fd)D                       t                    }dg|z   || |          }
t                                          | d*d+|           ndg|z   || |          }
|
|k    r*t                                          | d,||
z
   d-           | j        j        }t=          |j        z   |j        ||j         z   | d.|d/          gS )1z-Return series in Micro-Manager stack file(s).NSummaryIndexMapr  MicroManagerVersionFramesr   r  rW   r  r   )r  r  TR	TimeFirstTTRRTSlicesFirstZCrM  ChannelsSlices	Positions)r  r  r  r  c           
   3     K   | ]G}t          |                  t                              |         d                               V  HdS r  )rq  r   rY  )r   rv  indexmap_indexindexmap_shaper  summarys     r   r   z+TiffFile._series_mmstack.<locals>.<genexpr>  sm       
 

 	 ~b12GKKR!,,-- 
 
 
 
 
 
r   c              3  (   K   | ]}|         V  d S r   r   )r   rv  r  s     r   r   z+TiffFile._series_mmstack.<locals>.<genexpr>  s(      AAb~b1AAAAAAr   r   r   indexmapr   r   r   c           	        d}|d d df                                          }t          j        |d d f         j                                                   }| j        j        }| j        j        |j        d         z
  dz
  }t          ||          D ]\\  }}||j
        k    r||<   |dz  }d|cxk     r|k    rn n|dz   f}	|j        }
|dz  }ndx}	}
d}t          | |||	|
|          |<   ]|S )Nr   r     rW   r  r  rv   r$  r  rb  )tolistr  r  r  r"  r  r  rw   r  r  rv   r   )r   r  
page_countoffsetsindicesrb  filesizer  rv   r$  r  indexmap_orderr"  r   s              r   add_filez*TiffFile._series_mmstack.<locals>.add_file  sI   Jqqq!tn++--G-N*+-  fhh	 
 yH~*X-DQ-GG#MH "%Wg!6!6  vX_,,#+E%L!OJv)))))))))#)C</K%-%<N!OJJ 487K.F(! +#1%     e r   z/ MMStack multi-file series cannot be read from F_MMStackz MMStack file name is invalidPrefixz_MMStack*.tifrT  c              3  ,   K   | ]\  }}||z
  d z   V  dS r  r   r5  s      r   r   z+TiffFile._series_mmstack.<locals>.<genexpr>  sB        Aq A	     r   c              3  (   K   | ]}|         V  d S r   r   r   r  r   s     r   r   z+TiffFile._series_mmstack.<locals>.<genexpr>  s'      ;;q%(;;;;;;r   z3 MMStack series is missing files. Returning subset z of z MMStack is missing z pages. Missing data are zeroedro  r   r~   r  rO  rW  r  rq   )r   r   r  r   r   r   )!micromanager_metadataargsortr  rq  r  rY  r  rD   r   r  r  r=   rs  r0  r  r  r  r  r  r   r  r   r   r   r   r  rj  r  r"  r  r
   r~   r  )rp  settingsr  r  rw   r  r  prefixrx   	filenamesr  r  r   	old_shape	min_index	max_indexrb  r  r  r  r  r"  r   r  s                    @@@@@@@r   _series_mmstackzTiffFile._series_mmstackf  se   -(())4
 9%J'HQQQTN22445 //873J3J4  )HQQQUO!<<<q@HHJJ qqq99 {{;55?tt4M488BdB 	
 
  
 
 
 
 
 
 

 
 
 
 
 
 u~~AAAADAAAAA#	 #	 #	 #	 #	 #	 #	 #	J 8>!,,	 	<?* <   / /*/ /   "		4=00  D!I!I!IJJJ!		W$$ *}//77 &HH$$%M%M%MNNN %I,,Z88; 	>gll'/)A G 	'**I9~~""!		%XdH55
& > >E}e(<(<R(@@@ !% >C#=NZL$ $$$& $,HQQQTN,B,B,D,D#E"hhsH&=&==
> > > > > > > > > > > > > > >  	2HN1%%%I	(111bqb5/:::I	(111bqb5/:::I}}HQQQUOOOy(OOO  	 0 0 2 2I4D4D4F4FGG    E ;;;;N;;;;;E5>>DFTME!$11JHH ? ?$)? ?1:? ?    FTME!$11JHH + +tj/@ + + +  
 :#hn,nHM) #  
 	
s   ALL"	%L"	c                n
   !" | j         j        s2t                                          | d| j         j                   dS t
          j                            | j         j        d          }t
          j        	                    |          s&t                                          | d           dS i }d}ddddd	d
dd}i }i }d}t          |          D ]m\
  }}	}
}}}}}}}|	|v r|dz  }||	         }t          |j        |d||
f|j                  }|j        dd         ||fk    r$t          d|j        dd          d||f           |dk    rt          d          |j        dk    rt          d|j                  ||vrt          d|           ||         \  }}|j        |k    rt          d|j         d|           n|	| j        k    rd}| j        j        }|||	<   nbd}t+          t
          j                            | j         j        |	                    5 }|j        j        }ddd           n# 1 swxY w Y   |||	<   |r>|                                D ]&\  }}t/          |t0                    r|di||<   d||<   'd}nq|ro|                                D ]Z\  }}||         }t/          |t0                    sJ ||vr't3          |                                          dz   ||<   ||         ||<   [||t7          |                                          <   t7          |                                          ot;          j        t?          |                                          t:          j                   }t;          j!        |d          "                                 t;          j        |d          "                                }t7          d tG           |          D                       "tI          |d          !t7          "fd!D                       "t7          fd!D                        !fd|                                D             }g }t;          j%        "          D ]+}|&                    |'                    |d                     ,tQ          d |                                D                       }"|j        z  "|j)        z  d                     d! D                       }d| _*        tW          |"|j        || d"tY          |          dk    d#          gS )$z(Return series in NDTiff v2 and v3 files.z NDTiff.index not found for NzNDTiff.indexz NDTiff.index not foundr   )uint8rY  )r  r  )r  r  )r  r  )r     )r  rY  )r   rW   r  r   r  r  r  TrW   rv   rb  r$  r  r  z'NDTiff.index does not match TIFF shape r  z4NDTiff.index compression {compression} not supportedz-NDTiff.index does not match TIFF compression z NDTiff.index unknown pixel type z1NDTiff.index pixeltype does not match TIFF dtype Fr~  r  c              3  ,   K   | ]\  }}||z
  d z   V  dS r  r   r5  s      r   r   z*TiffFile._series_ndtiff.<locals>.<genexpr>  s.      FFDAqa!eaiFFFFFFr   )rq   c              3  (   K   | ]}|         V  d S r   r   r  s     r   r   z*TiffFile._series_ndtiff.<locals>.<genexpr>  s'      ..1eAh......r   c              3  (   K   | ]}|         V  d S r   r   r   r  dimss     r   r   z*TiffFile._series_ndtiff.<locals>.<genexpr>  s'      ,,T!W,,,,,,r   c                R    i | ]"\  }t          fd D                       |#S )c              3  :   K   | ]}|         |         z
  V  d S r   r   )r   r  r  r  s     r   r   z5TiffFile._series_ndtiff.<locals>.<dictcomp>.<genexpr>  s0      99a%(Yq\)999999r   r  )r   rU  r  r  r  s     @r   
<dictcomp>z+TiffFile._series_ndtiff.<locals>.<dictcomp>  sP     
 
 
u 999995999995
 
 
r   c              3     K   | ]}|V  d S r   r   r  s     r   r   z*TiffFile._series_ndtiff.<locals>.<genexpr>  s"      66a666666r   r  c              3  z   K   | ]6}t           j                            |                                d           V  7dS )r  N)r   r  rY  r  r  s     r   r   z*TiffFile._series_ndtiff.<locals>.<genexpr>  s<      IIqt**17799c::IIIIIIr   rp  r  )-r  r  r=   rs  r0  r  r  r   r  existsr   r   rO  r  r   r   r   r~   r  r"  r  r   r:  r   r   rq  rT  r  r  r  r^  rA  int32r  r  r  
order_axesndindexr   rY  r  r  r  r
   r   )#rp  	indexfiler  r  pixel_typesr  rz   r  	axes_dictr  r!  r^  height	pixeltyper   
metaoffsetmetabytecountmetacompressionrb  r  r~   r	  r   r  r  rT  indices_arrayr  r"  r  r  r  r  r  r   s#                                  @@@@r   _series_ndtiffzTiffFile._series_ndtiff  s{    & 	HHNNt7JNN   4GLL!8.II	w~~i(( 	HH???@@@4)+	 	
 
 @B02
 y))O	+ O	+ 
9$$Q	$X. O%!+#+#:   :bqb>fe_44$A:bqb>A A06A A   !##$N   #q(($0+0 0   K//$F9FF   'y1q:&&$3:3 3+03 3   '
 T]**	z'&*	(## 	GLL!8(CC  +9?D+ + + + + + + + + + + + + + + '+	(#  4#,??#4#4 , ,KD%!%-- ,,11:
4(*+	$ 4$.$4$4$6$6 4 4LD&%dOE%eS11111F**(+FMMOO(<(<q(@u&,UmIdOO15GE)**,,--.))**DD D$8$8LLLIm!444;;==	Im!444;;==	FFC	9,E,EFFFFF =%888.........,,,,e,,,,,
 
 
 
 
 '
 
 

 46='' 	1 	1CLLS$//0000669#3#3#5#566666wwIIDIIIII0 n i..1,  
 	
s   #H<<I 	I 	c           	        | j         }|dS | j        j        }|d         }|                    dd          }|dk    rd|j        z   }d|j        z   }nt          j        |d         d	k              r|f|j        z   }d
|j        z   }n[t          j        t          j        |d                   d	k              r|f|j        z   }d|j        z   }n|f|j        z   }d|j        z   }d| _	        t          |g||j        |||dk    d          }|gS )zReturn series in STK file.NNumberPlanesrp  r  rW   r  r  	ZDistancer   r  TimeCreatedr  Trr  )ru   r  rW  )stk_metadatar"  r  rY  r   r  r  rr  diffr  r
   r~   )rp  r  r  planesru   r   r  ro   s           r   _series_stkzTiffFile._series_stk  s1    <4zn%xx##Q;;4:%E?DDYtK(A-.. 		#I
*E?DDYuz$}"566!;<< 	#I
*E?DD I
*E?DFJqj
 
 
 xr   c           
       
 | j         

dS t          j        
d                  }| j        j        j        dk    r+|                    dd                              dd          }nA| j        j        j        dk    rn+| j        j        j        dk    r|                    dd          }
                    d	d
          d
k    rd|z   }
                    dd
          d
k    rd|z   }t          
fd|D                       }
                    dd          }| j        
                    t          d
dd          d          }|d
         j        }t          |||||d          g}t          t          | j        d                   }|j        r| j        
                    t          ddd          d          }|j        }d}d
}	|t#          |          k     rO|	t#          |          dz
  k     r9|||	         z  }|	dz  }	|t#          |          k     r|	t#          |          dz
  k     9|d|	         |j        z   }|d|	         |j        z   }|                    t          |||||d                     d| _        |S )z-Return main and thumbnail series in LSM file.NScanTyperW   r  r  r  XCr  
DimensionPr   P
DimensionMMc              3  b   K   | ])}t          t          j        |                            V  *d S r   )r   r   CZ_LSMINFO_DIMENSIONS)r   r  lsmis     r   r   z'TiffFile._series_lsm.<locals>.<genexpr>  s8      MM1c$t9!<=>>MMMMMMr   rp  Fr  rn  r  )lsm_metadatar   CZ_LSMINFO_SCANTYPEr"  r  r   r  samplesperpixelrY  r  r_  ra  r~   r
   r\   r   r=  r   r   r  r   r  )rp  r  r   ru   r"  r~   ro   r  cpr  r  s             @r   _series_lsmzTiffFile._series_lsm  s    <4'Z(89:(A--<<R((00d;;DDZ*a//Z-22<<R((D88L!$$q((:D88L!$$q((:DMMMMMMMMMxx##
##E!T1$5$5#FFa5%4eLLL
 Hdjm,,? 	J''aq(9(9E'JJEJEBAs5zz//a#e**q.&8&8eAhQ s5zz//a#e**q.&8&8 "1"I
*E8di'DMM5%Du      r   c                   | j         }d|_        d|_        |                    d           |                    d           |                    d           |                                  |                                  | j         j        }|j        ddd         D ]	}||_	        
t          t          |d                   }|j        ddd         D ]	}||_	        
dS )z%Read and fix all pages from LSM file.TrW   r   Nr  )r"  r  rH  r  r  _lsm_fix_strip_offsets_lsm_fix_strip_bytecountsr  _pagesrb  r\   r   )rp  r"  rb  r  s       r   rD  zTiffFile._lsm_load_pages  s     
11D 	##%%%&&(((:#L1% 	% 	%D$DMM%(++LA& 	% 	%D$DMM	% 	%r   c                   | j         j        dk     rdS | j        }t          |          }| j        d         }|j        }d}dD ]!}|j        |         dv r||j        |         z  }"|dk    rd}dD ]}||         dk    r|j        |         } n|rt          |d	|z  |z            \  }}	|	dk    rt          d
          |||d	f}
t          j
        t          |
                                        |
          }t          j        |dd          }nQt          j
        |                              dd	          }n(t          j
        |                              dd	          }|d         j        d         |d         j        d         k    r|ddddf         }d}d}|j        D ]}|t!          |                   }g }t#          d |j        D                       r)t%                                          | d|             dS |j        D ]'}||k     r|dz  }|                    ||z              |}(t+          |          |_        dS )zUnwrap strip offsets for LSM files greater than 4 GB.

        Each series and position require separate unwrapping (undocumented).

        r|  Nr   rW   )r   rW   PMrW   r  r  r  zmod != 0rT  .c              3  "   K   | ]
}|d k    V  dS r4  r   r  s     r   r   z2TiffFile._lsm_fix_strip_offsets.<locals>.<genexpr>g  s&      44a16444444r   z" LSM file incompletely written at )r  rw   r"  r   ro   r  r   r  rg  r  r  rD   rz  moveaxisr$  flatr   rr  r=   rs  r   r  )rp  r"  r  ro   r  	positionsr  ntimesdivr  r   r  wrappreviousoffsetnpir  r$  currentoffsets                     r   r  zTiffFile._lsm_fix_strip_offsets5  s    ?%''F 
UQ{ 	 	- 	-A{1~%%V\!_,	 q==F  7c>>#\!_FE "  >!&!i-&*@AAS!88&z222"FC3,wu~~66>>uEE.!Q77,v..66r1==l6**222q99G 8"U1X%9!%<<<c44R4i(G < 	2 	2CS?DK444#344444   GGGG   !%!1 / / >11EMD""=4#7888!.$[11D	2 	2r   c                H   | j         j        j        dk    rdS t          | j         d           }t	          |          dz
  }t          |          D ]\  }}|j        dz  r|j        }|j        }||k     r||dz            j        d         }n,t          |d         d|d         z  z   | j
        j                  }t          |          }t          t	          |          dz
            D ]}	||	dz            ||	         z
  ||	<   ||d         z
  |d<   t          |          |_        dS )zSet databytecounts to size of compressed data.

        The StripByteCounts tag in LSM files contains the number of bytes
        for the uncompressed data.

        rW   Nc                    | j         d         S r  )r$  r]  s    r   r  z4TiffFile._lsm_fix_strip_bytecounts.<locals>.<lambda>}  s    q1A r   r  r  r   rT  )r"  r  r   r|  r   r  r  r$  r  r  r0  rw   rA  r  r  )
rp  r"  r  r  r  r  r  
lastoffsetbytecount_listr6  s
             r   r  z"TiffFile._lsm_fix_strip_bytecountss  sL    :'1,,Ftz'A'ABBBUa '' 	8 	8GAtzA~ &G,J6zz"1q5\5a8

 !BK!jn"44dhm 
 "*--N3z??Q.// @ @$+AENWQZ$?q!!!+gbk!9N2"'"7"7D!	8 	8r   c                   | j         }| j         j        j                            d          }||dk     rdS d|_        d|_        |                                 |D ]}t          |t                    sJ |j                            d          }||dk    rt          j
        |_        t          j        |_        d|_        d	|_        t#          j        t"          j                  x|_        |_        |j        d
         dk    r?|j        dd
         |_        |j        dd
         |_        |j        dd
         dz   |_        dS )a   Read and fix pages from NDPI slide file if CaptureMode > 6.

        If the value of the CaptureMode tag is greater than 6, change the
        attributes of TiffPage instances that are part of the pyramid to
        match 16-bit grayscale data. TiffTag values are not corrected.

          Nr  TFr  r   rW   r  rT  r  )r"  r  r  r  r  rH  r  r   r   r&   rL  r   r*   UINTr  r  r   r  r~   r  r  r   r  r   )rp  r"  capturemoder  r  s        r   rG  zTiffFile._ndpi_load_pages  s0    
j&+33E::+//F 	: 	:DdH-----)##E**C{cAgg#.#9 $0$5!'($%'"+0;u|+D+DD
T[;r?Q&& $	#2#DI!%CRCDJ"&+crc"2T"9DK	: 	:r   c                   |dd         t           j        v rC| j        sdS t          t	          | j        j        |                    }t          | ||           |S t          | j        j	        d|          )z,Return `is_flag` attributes from first page.r   NFz object has no attribute )
r   
PAGE_FLAGSr"  r   r  r  r<  r?  	__class__r*  )rp  ru   rU  s      r   __getattr__zTiffFile.__getattr__  s    8t&&: u!148899ED$&&&L~&KK4KK
 
 	
r   c                    | S r   r   r  s    r   r  zTiffFile.__enter__  r  r   r  r  r  c                .    |                                   d S r   r  r  s       r   r  zTiffFile.__exit__  r  r   c                >    dt          | j        j        d          dS )Nz<tifffile.TiffFile r  rj   )r   r0  ru   r  s    r   r!  zTiffFile.__repr__  s!    DWTX]B%?%?DDDDr   c                *    |                                  S r   _strr  s    r   __str__zTiffFile.__str__      yy{{r   r   O   detailr   r^  c                   dt          | j        j                  t          | j                  rdnddd| j                 g}| j        r|                    d           t          | j                  dk    r*|                    t          | j                   d           t          | j	                  dk    r*|                    t          | j	                   d	           t          | j
                  dk    r*|                    t          | j
                   d
           | j        }d|v r-t          | j                  dk    r|                    d           |                    d                    d t          |          D                                  d                    |          }|                    dd                              dd          }|                    t#          | j        j        t'          ddz   t          |          z
                                }dk    r|S |g}|                    d                    d | j	        D                                  dk    rs| j        D ]j}||                    |                                         |j        4|j        D ],}|                    |                                         -knj| j	        r(|                    fd| j	        D                        n;| j        r4|                    | j        j                                                 dk    r~t          | j                  D ]i}t/          | |dz             rTt1          | |dz             }	|	r?|                    |                                 dt5          |	dz                        jd                    |                              dd          S ) a  Return string containing information about TiffFile.

        The `detail` parameter specifies the level of detail returned:

        0: file only.
        1: all series, first page of series and its tags.
        2: large tag values and file metadata.
        3: all pages.

        zTiffFile '{}'r  zlittle-endianz
big-endian)rk   rj   BigTiffrW    Pagesz Seriesz Filesr~  rR  c              3  >   K   | ]}|                                 V  d S r   r  r   r  s     r   r   z TiffFile._str.<locals>.<genexpr>  s*      !C!C!''))!C!C!C!C!C!Cr     z       r  r  r   
c              3  4   K   | ]}t          |          V  d S r   r   r   r  s     r   r   z TiffFile._str.<locals>.<genexpr>  s(      "?"?a3q66"?"?"?"?"?"?r   r   Nr8  r^  c              3  |   K   | ]6}|j         j        j        j        |j                                        V  7dS )rE  N)rb  rO  r  r  r4  )r   r  r8  r^  s     r   r   z TiffFile._str.<locals>.<genexpr>  sZ        z(3:
vU;;     r   r6  z
_METADATA
   r^  r  

z


)r9   r0  rw   byteorder_isnativer   r_  r   r   r"  ro   r,  r=  discardr   r|  r  formatr   ru   rq  r4  rQ  r  r;  r  rT  rC   )
rp  r8  r^  	info_listr=  r  r  r  ru   ms
    ``       r   r4  zTiffFile._str  s.    && &dn55O*>>t~N
	 ? 	(Y'''tz??QDJ777888t{aDK 0 0999:::t{aDK 0 0888999
#dj//Q"6"6MM)$$$!C!CVE]]!C!C!CCCDDDyy##||FD))11%>>{{DHM3r519s4yy+@#A#ABB
 
 Q;;KF	"?"?4;"?"?"???@@@Q;;
  <  &!F!FGGG:)"&*  !(("KKvUKCC    [ 	P           
 Z 	PTZ-22&2NNOOOQ;;tz**  4!344 d[&899A !((#zz|| M M&qfrkJJJM M   {{9%%--h???r   set[str]c                4      fdt           j        D             S )z6Set of file flags (a potentially expensive operation).c                ^    h | ])}t          d |z             |                                *S r   r  r  r   ru   rp  s     r   r  z!TiffFile.flags.<locals>.<setcomp>  E     
 
 
tUT\**
JJLL
 
 
r   )r   r;  r  s   `r   r=  zTiffFile.flags  0    
 
 
 

 
 
 	
r   c                ~   | j         }	 | j         j        }n# t          $ r Y dS w xY w|j        rdS |j        s|j        rdS d}|j        }	 d|_        |j        }dD ]/}||                                         j        |k    r
 ||_        dS 0n# t          $ r |dk    cY ||_        S w xY w	 ||_        n# ||_        w xY wdS )z&File contains uniform series of pages.FTr   )rW   r  rT  rW   )	r"  r  r  rt  rE  r  rH  r  aspage)rp  r"  r  r  rH  r&  s         r   r  zTiffFile.is_uniform  s#    
	:#DD 	 	 	55	< 	5 	 	4O			(#EO	A ! !8??$$)Q..  (EOOO /!  	 	 	6MM'EOO	! (EOOiEO''''ts<    
$$
6B 	B 
B1 B%B1 $B%%B1 1	B:c                X    | j         p"| j        p| j        p| j        p| j        p| j         S )z1Pages can be appended to file without corrupting.)r>  rC  is_stkr  is_fluoviewis_micromanagerr  s    r   r^  zTiffFile.is_appendable2  sM    
 K ${${$ ~$ 	$
 #
 	
r   c                    | j         j        S )zFile has BigTIFF format.)r/  r_  r  s    r   r_  zTiffFile.is_bigtiff?  s     y##r   c                ^    | j         }|#|                    dd          dk    r	d| _        dS dS )zFile has NDTiff format.NMajorVersionr   r  TFr  rY  r  rp  r  s     r   	is_ndtiffzTiffFile.is_ndtiffD  s;     ) ; ;q @ @"DO4ur   c                n    | j         }|+d|v r'd|v r#|                    dd          dk    r	d| _        dS dS )	z$File has Micro-Manager stack format.Nr  r  r_  rW   r   TFr`  ra  s     r   
is_mmstackzTiffFile.is_mmstackN  sT     )T!!d""++q00 #DO4ur   c                    	 | j         j        j        p | j                             dd          j        }|rd| _        |S # t
          $ r Y dS w xY w)zFile has MD Gel format.rW   T)r  F)r"  r  is_mdgelrY  r  r  )rp  ismdgels     r   rf  zTiffFile.is_mdgel]  sl    		
 ) ::>>!4>009   ("'N 	 	 	55	s   <? 
AAc                    	 | j         j        j        o,| j                                                            d           S # t          $ r Y dS w xY w)zFile is Olympus SIS format.z.vsiF)r"  r  is_sisr  r  rP  r  r  s    r   ri  zTiffFile.is_sisl  sb    	
 ' ?++--66v>>>  	 	 	55	s   =A   
AA!tuple[dict[str, Any], ...] | Nonec                (   | j         sdS g }| j        D ]q}|j                                        dk    r |j        d         }t          |t                    r|j        J|                    t          |j                             rt          |          S )z<Tifffile metadata from JSON formatted ImageDescription tags.Nr   r   )	is_shapedro   rW  r  r"  r   r   rl  r   r  r  )rp  r  r  r  s       r   shaped_metadatazTiffFile.shaped_metadataw  s     ~ 	4 		P 		PAv||~~))71:DtX..*2MM5d6MNNOOOOV}}r   c                R    | j         sdS | j        r| j        S | j        j        j        S )z+OME XML metadata from ImageDescription tag.N)r>  r1  r"  r  r   r  s    r   r  zTiffFile.ome_metadata  s3     { 	4< 	 <z++r   c                6    | j         sdS | j        j        j        S )z1Leica SCN XML metadata from ImageDescription tag.N)is_scnr"  r  r   r  s    r   scn_metadatazTiffFile.scn_metadata  s!     { 	4z++r   c                6    | j         sdS | j        j        j        S )z2Philips DP XML metadata from ImageDescription tag.N)
is_philipsr"  r  r   r  s    r   r  zTiffFile.philips_metadata  s!      	4z++r   c                6    | j         sdS | j        j        j        S )z2IndicaLabs XML metadata from ImageDescription tag.N)	is_indicar"  r  r   r  s    r   indica_metadatazTiffFile.indica_metadata  s!     ~ 	4z++r   c                \    | j         sdS | j        j        j                            d          S )z&Argos AVS XML metadata from tag 65000.N  )is_avsr"  r  r  r  r  s    r   avs_metadatazTiffFile.avs_metadata  /     { 	4z$,,U333r   r   c                \    | j         sdS | j        j        j                            d          S )z!LSM metadata from CZ_LSMINFO tag.Nl  )rC  r"  r  r  r  r  s    r   r  zTiffFile.lsm_metadata  r{  r   c           
     r   | j         sdS | j        j        }|j        }i }|j        r|j                            d          |d<   |                    d          }|dn|j        |d<   |                    d          }||	                    |           |                    d          }||	                    |           |                    d	          }||	                    |           |                    d          }||d
         |d
<   |d         |d<   |d         |d<   dD ]}	 t          j        d t          |d|z            |d|z                      D             d          |d|z   <   J# t          $ r<}d|d|z   <   t                                          | d| d|d           Y d}~d}~ww xY w|S )zSTK metadata from UIC tags.N PlaneDescriptions]  rW   r  \  ^  _  r  r  TimeModified)CreatedModifiedc                     g | ]}t          | S r   )julian_datetime)r   dts     r   r:  z)TiffFile.stk_metadata.<locals>.<listcomp>  s-        " ,R0  r   DateTimezdatetime64[ns]r~  Datetimez STK Datetime raised r9  )rZ  r"  r  r  r   r  rY  r  r  r  r  r^  r  r  r=   rs  )	rp  r  r  r  r9  rU  uic2tagrn   r  s	            r   r  zTiffFile.stk_metadata  s4    { 	4zy!# 	I*.*:*@*@*H*HF&'hhuoo&)ksy~U##MM%   U##MM%   U##MM%   ,,u%%")+"6F;$+M$:F=!%,^%<F>".  /4{ &) ' 5wv|7L' '   /0 0 0F:+,, !   /3F:+,HH$$IIIISIII       
 s   'AE..
F482F//F4c                    | j         sdS | j        j        }|j        dS t	          |j                  }|j                            d          }|'	 |                    |           n# t          $ r Y nw xY w|S )z:ImageJ metadata from ImageDescription and IJMetadata tags.N  )	r  r"  r  r;   imagej_description_metadatar  r  r  r  )rp  r  r  rU  s       r   r  zTiffFile.imagej_metadata  s     ~ 	4z"*4,T-DEE	!!%((e$$$$   s   A& &
A32A3c                    | j         sdS i }| j        j        }|j                            d          }||                    |           |j                            d          }|||d<   |S )z3FluoView metadata from MM_Header and MM_Stamp tags.N9  :  Stamp)r[  r"  r  r  r  r  )rp  r  r  rU  s       r   r  zTiffFile.fluoview_metadata  s{      	4z	!!%((MM%   	!!%((#F7O r   c                \    | j         sdS | j        j        j                            d          S )z*NIHImage metadata from NIHImageHeader tag.N2  )r  r"  r  r  r  r  s    r   nih_metadatazTiffFile.nih_metadata  r{  r   c                &   | j         sdS | j        j        j        }i }	 |                    |                    d                     n# t          $ r Y nw xY w	 |                    |                    d                     n# t          $ r Y nw xY w|S )z&FEI metadata from SFEG or HELIOS tags.Nx  z  )is_feir"  r  r  r  r  r  rp  r  r  s      r   fei_metadatazTiffFile.fei_metadata  s     { 	4z$	MM$,,u--.... 	 	 	D		MM$,,u--.... 	 	 	D	s#   (A 
AA(B 
BBc                \    | j         sdS | j        j        j                            d          S )zSEM metadata from CZ_SEM tag.NF  )is_semr"  r  r  r  r  s    r   sem_metadatazTiffFile.sem_metadata%  r{  r   c                B   | j         j        j        sdS | j         j        j        }i }	 |                    |                    d                     n# t          $ r Y nw xY w	 |                    |                    d                     n# t          $ r Y nw xY w|r|ndS )z9Olympus SIS metadata from OlympusSIS and OlympusINI tags.N鿂    )r"  r  ri  r  r  r  r  r  s      r   r1  zTiffFile.sis_metadata,  s     z& 	4z$	MM$,,u--.... 	 	 	D		MM$,,u--.... 	 	 	D	)vvT)s#   (A 
AA"(B 
BBc                `   | j         sdS d| j        j        j        v r| j        j        j        }n3t	          t
          | j        d                   }d|j        v r|j        }ndS i }t          dd          D ]9}||vrt          j        |         }|	                    |          ||dd         <   :|S )z$MD-GEL metadata from MDFileTag tags.N饂  rW   i  r  )
rf  r"  r  r  r\   r   r  r   r  r  )rp  r  r  r  r  ru   s         r   r  zTiffFile.mdgel_metadata=  s     } 	4DJ$))):#(DD$*Q-00D	!!yt%'' 	2 	2D49T?D#||D11F48r   c                $    | j         j        j        S )zAndor metadata from Andor tags.)r"  r  
andor_tagsr  s    r   andor_metadatazTiffFile.andor_metadataR       z**r   c                $    | j         j        j        S )z&EPICS metadata from areaDetector tags.)r"  r  
epics_tagsr  s    r   epics_metadatazTiffFile.epics_metadataW  r  r   c                \    | j         sdS | j        j        j                            d          S )zTVIPS metadata from tag.NJ  )is_tvipsr"  r  r  r  r  s    r   tvips_metadatazTiffFile.tvips_metadata\  s/     } 	4z$,,U333r   c                P    | j         sdS t          | j        j        j                  S )z;MetaSeries metadata from ImageDescription tag of first tag.N)is_metaseriesmetaseries_description_metadatar"  r  r   r  s    r   metaseries_metadatazTiffFile.metaseries_metadatac  s*     ! 	4.tz/?/KLLLr   c                P    | j         sdS t          | j        j        j                  S )z+Pilatus metadata from ImageDescription tag.N)
is_pilatuspilatus_description_metadatar"  r  r   r  s    r   pilatus_metadatazTiffFile.pilatus_metadatak  s)      	4+DJ,<,HIIIr   c                <    | j         sdS t          | j                  S )z Non-TIFF Micro-Manager metadata.N)r\  r   r0  r  s    r   r  zTiffFile.micromanager_metadatar  s$     # 	4)$(333r   c                *    t          | j                  S )z"Non-TIFF GDAL structural metadata.)r   r0  r  s    r   gdal_structural_metadataz!TiffFile.gdal_structural_metadatay  s     -TX666r   c                    | j         sdS i }	 t          | j                  \  }}}||d<   ||d<   |                    |           n# t          $ r Y nw xY w|S )zScanImage non-varying frame and ROI metadata.

        The returned dict may contain 'FrameData', 'RoiGroups', and 'version'
        keys.

        Varying frame data can be found in the ImageDescription tags.

        NrJ  r  )rE  r   r0  r  r   )rp  r  r  roidatarJ  s        r   r  zTiffFile.scanimage_metadata~  s       	4!#	*A$(*K*K'Iw 'F9"+F;MM'"""" 	 	 	D	s   7A 
AAc                6    | j         sdS | j        j        j        S )zGeoTIFF metadata from tags.N)
is_geotiffr"  r  geotiff_tagsr  s    r   geotiff_metadatazTiffFile.geotiff_metadata  s!      	4z,,r   c                \    | j         sdS | j        j        j                            d          S )z)GDAL XML metadata from GDAL_METADATA tag.N逤  )is_gdalr"  r  r  r  r  s    r   gdal_metadatazTiffFile.gdal_metadata  s/     | 	4z$,,U333r   c                P    | j         sdS t          | j        j        j                  S )z-AstroTIFF metadata from ImageDescription tag.N)is_astrotiffastrotiff_description_metadatar"  r  r   r  s    r   astrotiff_metadatazTiffFile.astrotiff_metadata  s*       	4-dj.>.JKKKr   c                \    | j         sdS t          | j        j        j        | j                  S )z4Hamamatsu streak metadata from ImageDescription tag.N)	is_streakstreak_description_metadatar"  r  r   r  r  s    r   streak_metadatazTiffFile.streak_metadata  s4     ~ 	4*J($/
 
 	
r   c                    | j         sdS | j        j        j                            d          }|dn|                                S )z+EER AcquisitionMetadata XML from tag 65001.N  )is_eerr"  r  r  r  decoderp  rU  s     r   eer_metadatazTiffFile.eer_metadata  sD     { 	4
 %--e44}tt%,,..8r   )r   r   rt   r   ru   r   rv   r   rw   r   r   r   r   r   r   r   r+  r.  r   r   r   r  )r   rL  r#  r&  r   rb   r"  r   )rn   r   ro   rU  rp   r   rq   r   r   r   rr   r   rs   r   r   r   )
rn   r   ro   rU  rp   r   r   rb   r   rj  )r   rl  )r   r  )ru   r   r   r   )r   r   r%  r   r7  r8  r   r^  r   r   r   r   rO  r   r   )r   rj  r   r   r   r   )Tr*  r+  r,  r-  r'  rs  r(  r   r  r  rV   rQ  r  r   rm   ro   r  r  r  r  r  r  r  r  r  r   r'  r/  r2  r7  rA  rW  r\  r  r  r  r  r  rD  r  r  rG  r.  r  r  r!  r5  r4  r=  r  r^  r_  rb  rd  rf  ri  rm  r  rq  r  rv  rz  r  r  r  r  r  r  r  r1  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r   r   r   r   [  s`	        $ $L ))OOO&&&&
 
 
 
" +/!!"&"&#'z z z z z zx # # # X#    X    X    _# # # # 37v /3 #!%!%v v v v v vt 18 /3 18 18 18 18 18 18f = = = _=~K K K K @ @ @ @DK K K KZE
 E
 E
 E
N   8M 8M 8M 8Mt
 
 
 
*%
 %
 %
 %
N   0   .t t t tl   >L L L L$^ ^ ^ ^@e e e eNY Y Y YvH H H HTa a a aFv
 v
 v
 v
po
 o
 o
 o
b   B, , , ,\% % % %.<2 <2 <2 <2|8 8 8 8<: : : :>

 

 

 

      E E E E   D@ D@ D@ D@ D@L 
 
 
 _
    _4 

 

 

 X

 $ $ $ X$    _    _    _    X    _" , , , X, , , , X, , , , X, , , , X, 4 4 4 X4 4 4 4 X4 ) ) ) _)V    _     _2 4 4 4 X4    X  4 4 4 X4 * * * X*     _( + + + X+ + + + X+ 4 4 4 X4 M M M _M J J J _J 4 4 4 _4 7 7 7 _7    _* - - - X- 4 4 4 X4 L L L _L 
 
 
 _
 9 9 9 X9 9 9r   r   c                      e Zd ZU dZdZded<   	 ded<   	 ded<   	 ded	<   	 ded
<   	 ded<   	 ded<   	 ded<   	 ded<   	 ded<   	 ded<   ddZedd            Zedd            Z	ddZ
ddZddZdS )r   zTIFF format properties.)rJ  r   rJ  rl  	tagnosizerI  rK  
tagformat1
tagformat2tagoffsetthreshold_hashr   rJ  rL  r   rJ  r   rl  r  rI  rK  r  r  r  r  r   r  c                    || _         || _        || _        || _        || _        || _        || _        || _        |	| _        |
| _	        t          |||f          | _        d S r   )rJ  r   rJ  rl  r  rI  rK  r  r  r  r  r  )rp  rJ  r   rJ  rl  r  rI  rK  r  r  r  s              r   rs  zTiffFormat.__init__  sg     "$("&$$"47Iz:;;


r   r   c                    | j         dk    S )zFormat is 64-bit BigTIFF.rX  )rJ  r  s    r   r_  zTiffFormat.is_bigtiff  s     |r!!r   c                .    | j         dk    o
| j        dk    S )z7Format is 32-bit TIFF with 64-bit offsets used by NDPI.r[  rY  )rJ  rJ  r  s    r   r3  zTiffFormat.is_ndpi  s     |r!:do&::r   c                    | j         S r   )r  r  s    r   __hash__zTiffFormat.__hash__  s
    zr   c                l    | j         dk    rdnd}| j        dk    rdnd}| j        rdnd}d	| d
| d| dS )Nr[  3264rk   rS  bigz with 64-bit offsetsr  z<tifffile.TiffFormat z-bit z-endianrj   )rJ  r   r3  )rp  bitsendianrw  s       r   r!  zTiffFormat.__repr__  s_    |r))ttt!^s22)-=%%2HtHH&HHHHHHr   c                d     t          t                     g fdt          j        D             R  S )Nc              3  B   K   | ]}| d t          |          V  dS ): N)r  )r   rw  rp  s     r   r   z%TiffFormat.__str__.<locals>.<genexpr>  sO         2274..22     r   )indentreprr   	__slots__r  s   `r   r5  zTiffFormat.__str__  sQ    JJ
   &0  
 
 
 	
r   N)rJ  r   r   rL  rJ  r   rl  r   r  r   rI  r   rK  r   r  r   r  r   r  r   r   r  r  r   r   r&  )r*  r+  r,  r-  r  r'  rs  r(  r_  r3  r  r!  r5  r   r   r   r   r     sF        !!I LLL!    #OOO*NNN 0LLL0OOO7OOO8$JJJ< < < <2 " " " X" ; ; ; X;   I I I I
 
 
 
 
 
r   r   c                  
   e Zd ZU dZded<   	 ded<   	 ded<   	 ded	<   	 d
ed<   	 ded<   	 ded<   	 ded<   	 ded<   	 d
ed<   ded<   dZded<   	 dZded<   	 dZded<   	 dZded<   	 dZ	ded<   	 dZ
ded<   	 dZded<   	 dZded<   	 dZded<   	 dZded<   	 d Zded!<   	 dZded"<   	 dZded#<   	 dZded$<   	 dZded%<   	 dZded&<   	 d'Zded(<   	 d)Zd*ed+<   	 d)Zd,ed-<   	 d)Zd.ed/<   	 d)Zd.ed0<   	 d1Zded2<   	 d1Zded3<   	 d1Zded4<   	 dZd5ed6<   	 d)d7dd>Zedd@            Z d)d)d)dAd)d)dBddOZ!d)dPd)d)d)dQddVZ"ddZZ#dAd)d[dd_Z$	 	 dddcZ%dddZ&ddeZ'e(ddf            Z)e(ddg            Z*e(ddh            Z+e+j,        ddi            Z+e(ddj            Z-e(ddk            Z.eddm            Z/eddo            Z0eddq            Z1edds            Z2eddt            Z3eddu            Z4e(ddw            Z5e(ddx            Z6e(ddy            Z7	 	 dddZ8edd            Z9e(dd            Z:e(dd            Z;e(dd            Z<edd            Z=edd            Z>edd            Z?edd            Z@edd            ZAedd            ZBedd            ZCedd            ZDddZEddZFdddZGddZHedd            ZIedd            ZJedd            ZKedd            ZLedd            ZMedd            ZNedd            ZOedd            ZPe(dd            ZQe(dd            ZRe(dd            ZSe(dd            ZTe(dd            ZUe(dd            ZVe(dd            ZWe(dd            ZXe(dd            ZYe(dd            ZZe(dd            Z[e(dd            Z\e(dd            Z]e(dd            Z^e(dd            Z_e(dd            Z`e(dd            Zae(dd            Zbe(dd            Zce(dd            Zde(dd            Zee(dd            Zfe(dd            Zge(dd            Zhe(dd            Zie(dd            Zje(dd            Zke(dd            Zle(dd            Zme(dd            Zne(dd            Zoe(dd            Zpe(dd            Zqe(ddÄ            Zre(ddĄ            Zse(ddń            Zte(ddƄ            Zue(ddǄ            Zve(ddȄ            Zwe(ddɄ            Zxe(ddʄ            Zye(dd˄            Zze(dd̄            Z{e(dd̈́            Z|e(dd΄            Z}e(ddτ            Z~d)S )r   a  TIFF image file directory (IFD).

    TiffPage instances are not thread-safe. All attributes are read-only.

    Parameters:
        parent:
            TiffFile instance to read page from.
            The file handle position must be at an offset to an IFD structure.
        index:
            Index of page in IFD tree.
        keyframe:
            Not used.

    Raises:
        TiffFileError: Invalid TIFF structure.

    r   r  r   rO  r   rv   r  r   r;  r~   tuple[int, int, int, int, int]r   r   r  r$  r  r  r  r   r   r  r  rW   
imagedepthr  r  	tiledepthr  r   r      r   r   r   	fillorderr   r   r   r   Nr   r   r   rt  r   r   
jpegheaderr  r   r   description1int | floatnodatar  r  int | Sequence[int]rb  TiffPage | Noner   r  c              N   !" |j         }|| _        d| _        d| _        d x| _        | _        d| _        t                      x| _        }d| _	        d| _
        t          |t                    r	|f| _        nt          |          | _        |j        }|                                | _        	 t%          j        |j        |                    |j                            d         }|dk    rt/          d|           n*# t0          $ r}t3          d| j                   |d }~ww xY w| j        |j        z   }	|j        x}
}|                    |
|z             t7                     |
|z  k    rt3          d          |j        rid	}
|                    d
t<          j                   |                    d|z            !d                      !fdtC          |          D                        |
 }tC          |          D ]}||
z  } |||
z            }	 tD          #                    ||	||z  z   |          }n<# t2          $ r/}tI                      %                    d|d           Y d }~md }~ww xY w|&                    |           |sd S tN          j(        )                                D ]H\  }}|*                    |          ""|dv rt          "tV                    s7tY          | |"           I|*                    dd          "t          "tV                    r"| _-        | j.        dk    r1|*                    d          ""dk    rd| _.        nZ"dk    rd| _.        nLt          | j.        t                    s2tI                      /                    | d| j.                   d| _.        |*                    d          | _	        | j	        m|*                    d          | _	        | j	        L|*                    d          | _	        | j	        +d| _	        tI                      %                    | d           |*                    d          | _
        | j
        ;|*                    d          | _
        | j
        |*                    d          | _
        | j0        dk    r| j1        dk    r| j	        r| j
        r	 |                    | j	        d                    te          |                    tg          | j
        d         d                              \  }}}}|| _1        || _0        || _4        d |vr|d
k    rd
nd	| _5        d!|vr|dk    rtl          j7        | _8        d"|vrtr          j:        | _;        d#|vr|| _<        n# t0          $ r Y nw xY w| j;        d$k    red!|vrtl          j7        | _8        n| j8        dk    rtl          j7        | _8        d |vrd
| _5        d%|vr"| j8        d&v r	d| _4        n| j8        d'v rd| _4        nu| j=        s| j>        dk    rO| j        j=        rC|d          ?                                 | j;        dk    r| j@        dk    rt          jB        | _@        n| jC        s| j>        dk    r| j        jC        rd| _D        n| jE        s| j>        dk    r| j        jE        rd| _D        d| _F        n| jG        r|H                    d(          }|J |                    |jI                   |H                    d)          }	 t          ||jK        |j        |jL        d||jL        nd*          |_M        n># t0          $ r1}tI                      /                    | d+|d           Y d }~nd }~ww xY w|H                    d,          }|k	 t          |jM        |d-         jM        |jK                  |_M        n># t0          $ r1}tI                      /                    | d.|d           Y d }~nd }~ww xY w|*                    d           ""~| j5        dk    rnr|d          jL        dk    rt          "          | _5        nL"d | j4                 "t          "fd/"D                       r"| _5        nt          "d                   | _5        |*                    d0          ""|d0         jL        dk    r;	 t          "          | _Q        n# t.          $ r t          "          | _Q        Y nw xY w"d | j4                 "t          "fd1"D                       r:	 t          "          | _Q        n# t.          $ r t          "          | _Q        Y nw xY w	 t          "d                   | _Q        nd# t.          $ r t          "d                   | _Q        Y n>w xY w| j5        d2k    r/| jR        s| j>        dk    r| j        jR        rt          jS        | _Q        d3|v rd| _<        nDd4|v r@d#|vs|d#         jL        dk    r| j1        | _<        tg          | j<        | j1                  | _<        tN          jT        H                    | jQ        | j5        fd           }|t          j        |          }nd }|x| _        | _        | j1        }| j0        }| jD        }| j4        }| j8        dk    s|dk    ry| jV        dk    r7d||||f| _        |dk    r|||f| _        d5| _        n~||||f| _        d6| _        nk||||df| _        |dk    r|||f| _        d7| _        nG||||f| _        d8| _        n4d|||df| _        |dk    r||f| _        d9| _        n|||f| _        d:| _        | j
        sTt          | j                  | j5        d
z  z  f| _
        | j;        dk    r$tI                      %                    | d;           |r1| j<        r)| j=        s!t          t          jY        || j<        z   dz
            | j<        z            | jD        z  }| jV        dk    r
|| j4        z  }|t7          | j
                  k    rPtI                      %                    | d<t7          | j
                   d=| d>           | j
        d |         | _
        |t7          | j	                  k    rPtI                      %                    | d?t7          | j	                   d=| d>           | j	        d |         | _	        |*                    d@          ""|	 t          |Z                    d          [                                          }"\                    dAdB          " |"          | _]        t          j^        t          j_        | j]                  | j                  st/          | j]         dC| j                   nE# t0          $ r8}tI                      /                    | dD|d           d| _]        Y d }~nd }~ww xY w|*                    dE          }|| j        r|`                    t          ja                  }|*                    dF          }|F|`                    t          jb                  }|d2z  }||`                    t          ja                  z  }|                    | j	        d                    |                    |d                   }	 t          |          \  | _d        | _e        | _f        t          jg        || j
        d         G          }t          |h                                          | _
        || j	        d         z  }t          |h                                          | _	        d S # t.          $ r2}tI                      /                    | dH|d           Y d }~d S d }~ww xY wd S d S )INr   )r   r   r   r   r   r  r      suspicious number of tags corrupted tag list @zcorrupted IFD structurer  rY  r  r   c              3  f   K   | ]+}|d z  |d z  d z            |dz  |dz  dz            z   V  ,dS )r  r  Nr   )r   r  r   exts     r   r   z$TiffPage.__init__.<locals>.<genexpr>  sh         QVa"frk)*SQQ1B-CC     r   rv   rI  z<TiffTag.fromfile> raised r9  >   r  r  r  rW   r  r  r  r   z invalid self.subfiletype=r  r    z missing data offset tagr  r    r  r  r  r  r  r  >   r  r  >   r   rW   r  r  )
planecountz  <tifffile.read_uic1tag> raised r    z# <tifffile.imagej_metadata> raised c              3  .   K   | ]}|d          z
  V  dS r4  r   r   r  rU  s     r   r   z$TiffPage.__init__.<locals>.<genexpr>  +      33q58|333333r   r  c              3  .   K   | ]}|d          z
  V  dS r4  r   r  s     r   r   z$TiffPage.__init__.<locals>.<genexpr>  r  r   r  r  r  YXSZYXSSYXSZYXYXZYXz missing ByteCounts tagz" incorrect StripByteCounts count (r  r  z incorrect StripOffsets count (遤  ,.z is not castable to z  parsing GDAL_NODATA tag raised     )r   z" <tifffile.ndpi_jpeg_tile> raised )ir/  rO  r   r   r~   r  r  r   r  r$  r  r   r   r  r  r  r]  rv   rj  r@  rI  r?  r  r   r  r   rK  r   r3  ra  r  r  r   r  r   fromfiler=   rB  addr   TAG_ATTRIBUTESr:  r  r   r<  r  r   rs  r  r  
jpeg_shaper  r  r   r&   rO  r   r    OJPEGr   r   rC  r  _fix_lsm_bitspersampler   r(   r  is_vistar  rs  r  rZ  rY  r  read_uic1tagr   r  rU  r  r@  r*   r  ru  IEEEFPSAMPLE_DTYPESr  r   rD   rx  floorr~  itemr  r  can_castmin_scalar_typer5   int64uint64ndpi_jpeg_tiler  r  r  r  r  )#rp  rO  r  rb  r/  r  rq  tagnor  r  rK  tagsize_r  r  tagdatar9  r  ru   	precisionr  r  r  r  dtypestrr~   r  	maxstripspytype	mcustartshighr  r  r   r  rU  s#                                   @@@r   rs  zTiffPage.__init__  s    {
%#''
T[	#::%	D eS!! 	' (DKK,,DK ggii	O "''$."9"9 E t|| !Ee!E!EFFF  	O 	O 	O Dt{ D DEE3N	O K$.0	!\)(www''t99%'' 9:::< 	GGGAr{###''!e)$$C88     u    D
 8u 
	 
	AH8h&889G&&9q8|#;G '   !   HCHHHIII HHSMMMM 	F-3355 	' 	'JD$LL&&E}z!!*UC*@*@!D$&&&&S**eS!! 	& %Dq  LL%%Ezz#&  !#' D,c22 	!HHDD1ADDEEE D  <<,,##||C00D'#'<<#4#4 #+')D$HHNNd#F#F#FGGG"ll3//&"&,,s"3"3D"*&*ll3&7&7# Oq   A%%  &# &4(+,,, rwws4+>q+A4'H'HIIJJ#
 $/ ",'6$d??.71nn"D&d??!';';'2'8D$d??'2'8D$d??(3D%     ""$#.#4  !Q&&#.#4 $%&"$#v--+,D((%//+,D([ "	TZ1__1C_I,,...1$$1)<)<!*] 	tzQ4;3GDOO_ 	qT[5KDODNN[ 	((5//C???GGCO$$$hhuooG(NII070Cw}}  		      KKsKKK       
 hhuoo?	+IK%N 		
      NN#NNN        S!!!Q&&cA%%%(ZZ"" 4 4453333U33333 7).D&&),U1XD& S!!Cy!##3(4U(;(;D%%! 3 3 3(+E

D%%%3 4 4453333U33333 	:7,8,?,?))% 7 7 7,/JJ)))7:,8q,B,B))% : : :,/aMM))):2%%N &#zQ4;3H !- 3D$;; !DD[[$$s)/A"5"5$($4! #D$5t7G H HD %)) 23T
 
 K))EEE#((
T[ &_
_
.q  Oa$7$7 A%%# ??"-z?!KDJ %DII ##"'	"DJ !'DII $ ??"1;
!KDJ %DII ("#"	"DJ !'DIIj+z1EDKQ):6
 		(+zB
!	" 	C
##t'9Q'>?#D 1$$$AAABBB 	@4, 	@T[ 	@ J{T->>BCC'(  /	"   A%%T11	C 34444 C CD/00C C6?C C C   '+&9*9*&E#C 01111 @ @D,--@ @3<@ @ @   $(#3JYJ#? U##!2 ejjmm002233c3//$fUmm~)$+66
   %;HHDJHH           KKsKKK    	  LL''	 T\ !((55I<<&&D{{5<00T[[555	GGD$Q'(((1..J=
 #:..	ONO "'d&9!&<" " " ',N,A,A,C,C&D&D#T-a00	#()9)9););#<#<         MMMMM        # !   s   +AC< <
D#DD##H66
I/ %I**I/=A V 
VV2\: :
]5']00]5+^< <
_7'_22_78c c/.c/d2 2eee2 2$ff<B)v& &
w(0.w##w("}$ $
~ .'~~ dCallable[..., tuple[NDArray[Any] | None, tuple[int, int, int, int, int], tuple[int, int, int, int]]]c                    !"#$%&'()*  j          j        j        j        v r j        j        j         j                  S  fd} j         j         fd} ||          S d j        v rd } ||          S 	  j        dk    rdnt          j	         j                  j        dv r  j        j
        st           j                  n=# t          $ r0}t          |          dd         d	d
} ||          cY d}~S d}~ww xY w	  j        dk    rd(nt          j         j                 (n# t          $ rv} j        t          j        v r.t!                                           d j                    d(n+t          |          dd         d	d} ||          cY d}~S Y d}~nd}~ww xY w j                            d          H j        d         &&j        dk    r0t+          &fd&j        D                       r&fd} ||          S  j        r" j        dvs j        dk    rd } ||          S  j        dk    r j        dk    rdUd}	|	 j        r( j         j         j         j        dk    r j        ndf$n"d j         j         j        dk    r j        ndf$$\  "#%! j        \  }
! j        rA%z   dz
  %z  *#z   dz
  #z  "z   dz
  "z  dV"#$%*fddW!fd!dX fd#dYd$n(#z   dz
  #z  dV!"#%fd%dWd&dX #fd'dY#fd( j        dv rǉ j         dk    r$t!                      !                     d)           (r$t!                      !                     d*           d+ j        v r$t!                                           d,           tE           j#         j         j$         j%                  \  ddd-d.dZ fd6} ||          S  j        dv r j        d7k    rytM           j        '                    d8d9                     tM           j        '                    d:d                    tM           j        '                    d;d                    )n j        d<k    rd9 dd)nd= dd)ddd-d.dZ )fd>} ||          S  j        d?k    rddd-d.dZfd@} ||          S  j        t          j        v r} j         dk    r+t!                      !                     dA j                    (r+t!                      !                     dB j                    ddd-d.dZfdC} ||          S tQ          j         j        j)         j        j*        z              j+        dDk    rp(tY          dE          tQ          j         j        j)         dF j-        dGz             tQ          j         j        j)         dHj.        dz             d[fdJ'n j-        dKv rN j-        %z  !z  d=z  rt_          dL           j        dMv rtQ          j         j        j*                  d[ fdN'nYta           j-        tb                    rd[ fdO'n7 j-        dPk    r#j*        dHk    r(tY          dQ          d[ fdR'n	d[! %fdS'ddd-d.dZ '(f	dT} ||          S )\a>  Return decoded segment, its shape, and indices in image.

        The decode function is implemented as a closure and has the following
        signature:

        Parameters:
            data (Union[bytes, None]):
                Encoded bytes of segment (strip or tile) or None for empty
                segments.
            index (int):
                Index of segment in Offsets and Bytecount tag values.
            jpegtables (Optional[bytes]):
                For JPEG compressed segments only, value of JPEGTables tag
                if any.

        Returns:
            - Decoded segment or None for empty segments.
            - Position of segment in image array of normalized shape
              (separate sample, depth, length, width, contig sample).
            - Shape of segment (depth, length, width, contig samples).
              The shape of strips depends on their linear index.

        Raises:
            ValueError or NotImplementedError:
                Decoding is not supported.
            TiffFileError:
                Invalid TIFF structure.

        c               :    | j         j        j        j        <   | S r   )rO  r+  r-  r  )r  rp  s    r   r  zTiffPage.decode.<locals>.cache{  s    7=DK)$)4Mr   Nc                 D    t          dj         dj         d          )Nz&data type not supported (SampleFormat r   z-bit))r   r  r   )argsr   rp  s     r   decode_raise_dtypez+TiffPage.decode.<locals>.decode_raise_dtype  s?     1%)%61 1)1 1 1  r   r   c                      t          d          )Nzempty imager   r;  r   s     r   decode_raise_emptyz+TiffPage.decode.<locals>.decode_raise_empty  s     ///r   rW      rx  r    rT  )r  c                "    t          |            r   r>  r  r;  r   s      r   decode_raise_compressionz1TiffPage.decode.<locals>.decode_raise_compression  s     C***r   z ignoring predictor c                "    t          |            r   r>  rD  s      r   decode_raise_predictorz/TiffPage.decode.<locals>.decode_raise_predictor  s     %X...r   r  c              3  8   K   | ]}|j         d          z
  V  dS r4  rU  )r   r  r9  s     r   r   z"TiffPage.decode.<locals>.<genexpr>  s.      %J%J1a#)A,&6%J%J%J%J%J%Jr   c                 2    t          dj                   )Nzsample formats do not match )r   rU  )r;  r   r9  s     r   decode_raise_sampleformatz2TiffPage.decode.<locals>.decode_raise_sampleformat  s"    $BsyBB  r   r  r  c                      t          d          )Nz9chroma subsampling not supported without JPEG compressionr  r?  s     r   decode_raise_subsamplingz1TiffPage.decode.<locals>.decode_raise_subsampling  s    )O  r   r  r  c                0    t          j        | d|          S )NT)hasalphar   )r/  webp_decode)r   r   s     r   decompress_webp_rgbaz-TiffPage.decode.<locals>.decompress_webp_rgba  s    ".tdLLLLr   segmentindexr   r   @tuple[tuple[int, int, int, int, int], tuple[int, int, int, int]]c               ^    | z  z  z  | z  z  z  z  | z  z  z  | z  z  dffS r  r   )rS  r`  r_  stdepthstlengthstshapestwidthr^  s    r   r  z TiffPage.decode.<locals>.indices  sb     %%)?@%%&.9UBWL%.&88C$u,w6 	 	r   r   r   r  r  r   tuple[int, int, int, int]c          	        |d         |d         z  |d         z  |d         z  }| j         dk    r| j        |k    r
| d |         } | j        |k    r|                     |          S 	 |                     t          |d         z
  |d                   t          |d         z
  |d                   t          |d         z
  |d                   f          S # t          $ r Y nw xY w	 |                     t          |d         z
  |d                   t          |d         z
  |d                   |d         f          S # t          $ r Y nw xY wt          d| d| j         d|           )Nr   rW   r  r   zcorrupted tile @ z cannot be reshaped from rY  )r  rw   rz  r  r   r   r   )r   r  r   rw   imdepthimlengthimwidthrb  s       r   rz  z TiffPage.decode.<locals>.reshape  s    Qx%(*U1X5a@9>>di$&6&6;D9$$  <<...  <<'!* 4eAh??71: 5uQx@@'!* 4eAh??#	   "   D  <<'!* 4eAh??71: 5uQx@@!!H#	   "   D#/ / /z/ /',/ /  s&   &A/C 
C#"C#'AE   
EE.tuple[NDArray[Any], tuple[int, int, int, int]]c                   | j         |k    r| |fS d t          || j                   D             }t          j        | |j                  } | |fS )Nc                "    g | ]\  }}d ||z
  fS r  r   r5  s      r   r:  z0TiffPage.decode.<locals>.pad.<locals>.<listcomp>2   s$    JJJ41aQAJJJJr   constant_values)r   r  r  r  r  )r   r   padwidthrp  s      r   r  zTiffPage.decode.<locals>.pad,   s]     :&&;&JJ3udj3I3IJJJyxMMMU{"r   c                   | S r   r   r   s    r   pad_nonez!TiffPage.decode.<locals>.pad_none6   s	     r   c               ~    | z  z  | z  z  z  | z  z  ddf}t          |d         z
            	f}||fS )Nr   r  )r  )
rS  r  r   r\  r]  r_  rb  rV  rW  rY  s
      r   r  z TiffPage.decode.<locals>.indices@   sr     !Vg%56!V+w6@ 6)H4 (WQZ"788	 ~%r   c                  |d         |d         z  |d         z  |d         z  }| j         dk    r| j        |k    r
| d |         } | j        |k    r0	 || _        n%# t          $ r |                     |          } Y nw xY w| S | j        }	 |d         d|d         |d         f| _        | d d d |d         f         } || _        | S # t
          $ r Y nw xY wt          d| d|           )Nr   rW   r  r   rT  z(corrupted strip cannot be reshaped from rY  )r  rw   r   r?  rz  r   r   )r   r  r   rw   r  s        r   rz  z TiffPage.decode.<locals>.reshapeU   s?    Qx%(*U1X5a@9>>di$&6&6;D9$$3%*

) 3 3 3  $||E223  K J	!&q2uQxq!ADJ:U1X:.D!&DJK!   D#. . .&+. .  s$   A A:9A:9C 
CCc                   |d         |d         |d         f}| j         |k    r| |fS dd| j         d         z
  fddg}t          j        | |j                  } | |fS )Nr   r  r   r  rW   rb  )r   r  r  r  )r   r   rd  rp  rW  s      r   r  zTiffPage.decode.<locals>.padw   s}     q8U1XuQx@:&&;&4:a=01	 yxMMMU{"r   c               4    | d         | d         | d         fS )Nr   r  r   r   )r   rW  s    r   rg  z!TiffPage.decode.<locals>.pad_none   s      a(E!HeAh??r   z disabling LSB2MSB for JPEGz disabling predictor for JPEG p  z@ SonyRawFileType might need additional unpacking (see issue #95)F)r   r  	_fullsizer   r  r   r  rm  r   Utuple[NDArray[Any] | None, tuple[int, int, int, int, int], tuple[int, int, int, int]]c                   	|          \  }}| |r |          }| ||fS t          j        | j        ||
|dd                   } |||          }|r ||          \  }}|||fS )NrW   r   )r   tablesrI  r  r  r   )r/  jpeg_decoder   )r   r  r   r  rm  rS  r   
data_arrayr  r  r  r  rg  rz  rp  s           r   decode_jpegz$TiffPage.decode.<locals>.decode_jpeg   s     '.genn#e<  0 (u44+6+B"&"4%%)"/!*, , ,
 %WZuEE
 ?(+J(>(>%J!<66r   rB  i  r  i  i  r  rY  c                   
|          \  }}| |r |          }| ||fS  | |dd         	d          }|                     |          ||fS )NrW   r   F)r   rlebitshorzbitsvertbitssuperres)rz  )r   r  r   r  rm  rS  r   rr  
decompressrv  r  rg  ru  rw  s           r   
decode_eerz#TiffPage.decode.<locals>.decode_eer   s     '.genn#e<  0 (u44'Z!*#%%"  
 "))%00,EEr   r  c                   	|          \  }}| |r 
|          }| ||fS t          j        |t           j                  } | |           |                    |          ||fS )Nr   )r  zerosr  rz  )r   r  r   r  rm  rS  r   rr  ry  r  rg  s           r   decode_jetrawz&TiffPage.decode.<locals>.decode_jetraw   s     '.genn#e<  0 (u44"[==

4Z0000!))%00,EEr   z# disabling LSB2MSB for compression z% disabling predictor for compression c                   	|          \  }}| |r |          }| ||fS  |           } |||          }|r 
||          \  }}|||fS r   r   )r   r  r   r  rm  rS  r   rr  ry  r  r  rg  rz  s           r   decode_imagez%TiffPage.decode.<locals>.decode_image!  s     '.genn#e<  0 (u44'Z--
$WZuEE
 ?(+J(>(>%J!<66r   r  z+unpredicting complex integers not supportedr  r  r  r  c               z    t          j        |                                                                       S r   )r  
frombufferr5   view)r   r~   ftypeitypes    r   r@  zTiffPage.decode.<locals>.unpackH!  s2    'e44;;EBBGGNNNr   >   rY  r  r  @   r  zdata and sample size mismatchr  c                   	 t          j        |           S # t          $ r? j        dz  }t	          |           |z  |z  }t          j        | d |                   cY S w xY wNrY  )r  r  r   r   r   )r   r-  rw   r~   rp  s      r   r@  zTiffPage.decode.<locals>.unpackV!  s~    @ +D%888! @ @ @,1CII,3D +D$K?????	@s    AA! A!c               0    t          | j                  S r   )
unpack_rgbr   )r   r~   rp  s    r   r@  zTiffPage.decode.<locals>.unpackc!  s    !$t/ABBBr   rG  z"unpredicting float24 not supportedc               D    t          j        | j        j                  S )Nr   )r/  float24_decoderO  r   )r   rp  s    r   r@  zTiffPage.decode.<locals>.unpackm!  s'    "1DK$9   r   c               D    t          j        | j        z            S )N)runlen)r/  packints_decoder   )r   r~   rb  rp  rY  s    r   r@  zTiffPage.decode.<locals>.unpacku!  s.    "2%!3Gg<M   r   c                	  |          \  }}| |r |          }| ||fS j         dk    rt          j        |           } 	8|d         |d         z  |d         z  |d         z  } 	| |
j        z            }  |           } |||          }|                    d
j        z   d          } |d	|
          }|r ||          \  }}|||fS )Nr  r   rW   r   r   rQ  Frj  r}  r  r   )r  r/  bitorder_decoder  r5   r%  )r   r  r   r  rm  rS  r   rw   rr  ry  r~   r  r  rg  rz  rp  r@  	unpredicts            r   decode_otherz%TiffPage.decode.<locals>.decode_other{!  s-    #*'%..L%| ,$HUOOE\500~"""2  %Qx%(*U1X5a@!z$D5>,ABBBJ \5AAJ#**3+;%*HHJ$&Yz
KKK
 ;$'C
E$:$:!
E|U22r   r   )rS  r   r   rT  )r   r   r  r  r   rZ  r   r   )r   r   r   rZ  r   r_  )r   rZ  r   rZ  )r   r   r  r   r   r   r  r   rm  r   r   rn  )r   r  r   r   )2r  rO  r+  r-  r~   r  r   r   r   DECOMPRESSORSr  r  r   r   UNPREDICTORSrV  r=   rs  r  rY  r  r@  rU  is_subsampledr   r  r  r  r  r  r   r  r  r  jpeg_decode_colorspacer   r   is_jfifr   r  r  r   r%  r  r  r   r  r   r   r  )+rp  r  r<  r@  r  rE  rG  rK  rN  rR  r	  rs  rz  r}  r  r  r  ry  r`  r~   r  rv  r\  r]  r^  r  r  r_  r  r  rg  rz  ru  rb  rV  rW  rX  rY  r9  r@  r  rw  r^  s+   `               @@@@@@@@@@@@@@@@@@@@@@@@@@@r   r  zTiffPage.decodeP  s   P 9+555;&0;;	 	 	 	 	 :!4     5+,,,0 0 0 5+,,,	31$$!

!/0@A
 $999* : t/000 	3 	3 	347HHQrTN + + + + + 5122222222	3	5~"" 		 -dn=	 	5 	5 	54#:::  CC4>CC   !		
  #3xx"~/ / / / /
 u344444444 					5  9==))C.CyA~~#%J%J%J%J	%J%J%J"J"J~    
 u6777 
	3$888 A%%  
 51222u$$)=)B)BM M M M .J = 	(,(9Q(>(>$$A	GG !(,(9Q(>(>$$A	G /6+7G15.7Hgw= c	@w&*w6E)A-(:Fw&*w6E           ", , , , , , , , ,\# # # # # #     )A-(:F& & & & & & & & & & & &*       D# # # # # # # @ @ @ @ @ @ 333~""$EEEFFF I$GGGHHH	!!   0 0 0  
 )? !!	) )%J ,0+/"'7 7 7 7 7 7 7 7 7 7 7 7 7 7B 5%%%444 5((di//q99::ty00::;;ty00::;;!U** ,0+/"'F F F F F F F F F F F F F: 5$$$u$$ ,0+/"'F F F F F F F F F F. 5'''t666~"" L L9=9IL L     N N;?;KN N   ,0+/"'7 7 7 7 7 7 7 7 7 7 7 76 5&&&DK1DK4DDEE!!$)A   K;(EE4+=+CEE E K;(@@5>Q+>@@ EO O O O O O O O O #777 "W,w6!; B !@AAA~!222 DK$455	@ 	@ 	@ 	@ 	@ 	@ 	@ 	@ *E22 	C C C C C C C C 2%%%**;*;$)*NOOO               (,'+#$	3 $	3 $	3 $	3 $	3 $	3 $	3 $	3 $	3 $	3 $	3 $	3 $	3 $	3 $	3 $	3L u\"""s>   AC 
D%%D
DD%D? ?
F?	A&F:/F?:F?F)lockrr   funcr{   rs   rm  r  $threading.RLock | NullContext | Nonerr   r   r  Callable[..., Any] | Noner{   r   rs   rm  r   _Iterator[tuple[NDArray[Any] | None, tuple[int, int, int, int, int], tuple[int, int, int, int]]]c          	   #  Z  K   | j         }| j        j        }||j        }||j        }dt          |          i}	|j        dv r| j        |	d<   |j        |	d<   |	|j	        fd}
n|	|j	        ffd	}
||dk     r|j
        }|d	k     r7|                    | j        | j        |||d
          D ]} |
|          V  dS t          |          5 }|                    | j        | j        |||d          D ]}|                    |
|          E d{V  	 ddd           dS # 1 swxY w Y   dS )a  Return iterator over decoded tiles or strips.

        Parameters:
            lock:
                Reentrant lock to synchronize file seeks and reads.
            maxworkers:
                Maximum number of threads to concurrently decode segments.
            func:
                Function to process decoded segment.
            sort:
                Read segments from file in order of their offsets.
            buffersize:
                Approximate number of bytes to read from file in one pass.
                The default is :py:attr:`_TIFF.BUFFERSIZE`.
            _fullsize:
                Internal use.

        Yields:
            - Decoded segment or None for empty segments.
            - Position of segment in image array of normalized shape
              (separate sample, depth, length, width, contig sample).
            - Shape of segment (depth, length, width, contig samples).
              The shape of strips depends on their linear index.

        Nrm  r  r   r  c                     || i |S r   r   )r;  
decodeargsr  s      r   r  z!TiffPage.segments.<locals>.decode!  s    vt2z222r   c                &      || i |          S r   r   )r;  r  r  r  s      r   r  z!TiffPage.segments.<locals>.decode!  s"    tFFD7J77888r   rW   r  T)r  r{   rs   r  F)rb  rO  r  r  r  r   r   r   r  r  rr   read_segmentsr$  r  rS   map)rp  r  rr   r  r{   rs   rm  rb  rq  r  r  segmentexecutorsegmentss      `          r   r  zTiffPage.segments!  s     R =[#<7D )I&14	??%C
#777'+J|$'/':J|$<(28? 3 3 3 3 3
 )38? 9 9 9 9 9 9 a!,J>>++ #% ,   & & fWoo%%%%& & $J// 	>8 " 0 0$') !1 ! ! > >H  (||FH==========>	> 	> 	> 	> 	> 	> 	> 	> 	> 	> 	> 	> 	> 	> 	> 	> 	> 	>s   AD  D$'D$T)r   rq   r  rr   rs   r   r   rq   r   c               ^	   | j         }d|j        v s|j        t          j        d|j                  S t          | j                  dk    rt          d          | j	        j
        }||j        }t          |t                    r|dk    r|j        r|5  |j        }|r1t!          j        | dt$                     |                                 |                    |j	        j        |j        j        z   |j        | j        d                   }	ddd           n# 1 swxY w Y   n|j        r]|j        rt3          d          |t5          ||j        |j                  }|5  |j        }|r1t!          j        | dt$                     |                                 |                    | j        d                    |                    |j	        j        |j        j        z   t;          |j                  |	          }	ddd           n# 1 swxY w Y   |j        d
k    rt?          j         |	|		          }	|j!        dk    rGtD          j#        |j!                 }
|j!        dk    r |
|	d|	          }	n |
|	d|	          }||	dd<   n|j$         || u rd| j%        v r| j&        r| j'        dk    r| j(        dk    r|5  |j        }|r1t!          j        | dt$                     |                                 |                    | j%        d         j)        d                    |*                    | j%        d         j)        d                   }ddd           n# 1 swxY w Y   tD          j+        | j,                 } ||| j-        |          }	~n|5  |j        }|r1t!          j        | dt$                     |                                 |j.         ddd           n# 1 swxY w Y   t5          ||j        |j                  }	||	fd"d}| /                    ||||dd          D ]}|j        |	_0        |r\	 |j0        |	_0        nN# tb          $ rA}te                      3                    | d|	j0         d|j0         d |d!           Y d}~nd}~ww xY w|r|4                                 |	S )#a  Return image from page as NumPy array.

        Parameters:
            out:
                Specifies how image array is returned.
                By default, a new NumPy array is created.
                If a *numpy.ndarray*, a writable array to which the image
                is copied.
                If *'memmap'*, directly memory-map the image data in the
                file if possible; else create a memory-mapped array in a
                temporary file.
                If a *string* or *open file*, the file used to create a
                memory-mapped array.
            squeeze:
                Remove all length-1 dimensions (except X and Y) from
                image array.
                If *False*, return the image array with normalized
                5-dimensional shape :py:attr:`TiffPage.shaped`.
            lock:
                Reentrant lock to synchronize seeks and reads from file.
                The default is the lock of the parent's file handle.
            maxworkers:
                Maximum number of threads to concurrently decode segments.
                If *None* or *0*, use up to :py:attr:`_TIFF.MAXWORKERS`
                threads. See remarks in :py:meth:`TiffFile.asarray`.
            buffersize:
                Approximate number of bytes to read from file in one pass.
                The default is :py:attr:`_TIFF.BUFFERSIZE`.

        Returns:
            NumPy array of decompressed, unpredicted, and unpacked image data
            read from Strip/Tile Offsets/ByteCounts, formatted according to
            shape and dtype metadata found in tags and arguments.
            Photometric conversion, premultiplied alpha, orientation, and
            colorimetry corrections are not applied.
            Specifically, CMYK images are not converted to RGB, MinIsWhite
            images are not inverted, color palettes are not applied,
            gamma is not corrected, and CFA images are not demosaciced.
            Exception are YCbCr JPEG compressed images, which are converted to
            RGB.

        Raises:
            ValueError:
                Format of image in file is not supported and cannot be decoded.

        r   Nr  zmissing data offsetr   z reading array from closed filerv   z chroma subsampling not supportedr   r  rW   r}  r  r    r  )r   r   decoderesultrn  rb  r   r   r   r   r  c           	     &   | \  }\  }}}}}}	|1|j         |||||	d         z   |||	d         z   |||	d         z   f<   d S |d |j        |z
  d |j        |z
  d |j        |z
  f         |||||	d         z   |||	d         z   |||	d         z   f<   d S )Nr   rW   r  )r  r  r  r  )
r  rb  r   r  r  dr&  rP  r	  r   s
             r   r  zTiffPage.asarray.<locals>.func"  s     3?/!Q1a%? ! 1q58|+QU1X-=q1uQx<?OO    1(-112(.221(-113 1q58|+QU1X-=q1uQx<?OO  r   TF)r  r  rr   rs   r{   rm  rX  rY  rZ  r9  )r  rn  rb  r   r   r   r   r  )5rb  r   r  r  emptyr~   r   r$  r   rO  r  r  r   r   r#  r  rm  rn  ro  r  rd  r   r%  r  r  r  r6   ra  re  rD   r  r/  r  r   r   r  r  r  r  r  r  rU  r?  r  r   r   r  r  r   r   r=   rs  r  )rp  r   rq   r  rr   rs   rb  rq  r  r  r  r   ry  r  r	  r  s                   r   r   zTiffPage.asarray!  s}   n =8?#:;tX^444t  A%% 5666[#<7D sC  }	x'      MBBBK   GGIIIO-0DDO+A. )                 # j	% N)*LMMM#C(/JJ   MBBBK   GGIII(+,,,O-0DDHO,, '                 !Q&&$4VHHH!Q&& -h.@A	%**&YvBFCCCFF $)F@@@C #F111I +D  ty   ! 5(( E))  8 8 MBBBK   GGIII	#,Q/000wwty~3A6778 8 8 8 8 8 8 8 8 8 8 8 8 8 8 +D,<=JZ"0  F       MBBBK   GGIII                              #3IIF &.$*    4 ]]%% #      	'~      O O|O O)1O OBENO O         	HHJJJsd   A:DDD"BH

HH>BMM"MAO""O&)O&<Q	 	
R7RRr   rb   rj  c                     ddl m}  || fi |S )z~Return image from page as Zarr store.

        Parameters:
            **kwarg: Passed to :py:class:`ZarrTiffStore`.

        rW   rj  r   rj  rp  r   rj  s      r   rm   zTiffPage.aszarr"  .     	('''''}T,,V,,,r   )r  alphar  r  Container[int] | Nonec                   | j         di |}| j        }|j        t          j        k    r|j        }|t          d          |j        d         d|j        z  k     s|j	        |j	        j
        dvrt          d          |r<|                                dk    r|dz  }|                    t          j                  }d	|j        v r|j        dk    r|d
         n|d         }t#          ||          }n|j        t          j        k    r|j        r_|t(          }t+          |j                  D ]@\  }}|t(          v r2|j        dk    r|ddddd|z   gf         }n|dddddd|z   gf         } nAn|j        dk    r|dddf         }nj|ddddf         }n[|j        t          j        k    rt.          |j        t          j        k    rt.          |j        t          j        k    rt.          t.          |S )zWReturn image as RGB(A). Work in progress. Do not use.

        :meta private:

        Nzno colormaprW   r  r  zcannot apply colormapr  rY  r  .r   r   .r   r   )r   rb  r   r&   rP  r   r   r   r   r~   r%  rq  r5   r  r  r  r   apply_colormaprN  r   r!   r  rL  r  rM  	SEPARATED)	rp  r  r  r   r   rb  r   r  exss	            r   asrgbzTiffPage.asrgb"  s4    t|%%f%%=;#666(H ///q!Ax'=$===>)>&d22 !8999 8<<>>C''NH#??5;77hm##'/'<'A'AtF||tAw!$11DD![_44$ '='E'(=>>  FAsk))#0A55#'aAq1u-=(=#>DD#'Aq!QU+;(;#<D * (A--RaR=DD2A2;DD ![%;;;%%![%;;;%%![%:::%%%%r   threading.RLock | Nonecodeslist[tuple[int, TiffTag]]c               *    fd| j         D             S )zReturn list of (code, TiffTag).c                8    g | ]}	|j         v |j         |fS r   )r  )r   r9  r  s     r   r:  z%TiffPage._gettags.<locals>.<listcomp>#  s:     
 
 
}E 1 1 XsO 1 1 1r   r  )rp  r  r  s    ` r   _gettagszTiffPage._gettags#  s0    
 
 
 
y
 
 
 	
r   c                   | j         j        }| j         j        }|                    | j                   t          j        |j        |                    |j	                            d         }|                    | j        |j	        z   ||j
        z  z              t          t          j        |j        |                    |j                            d                   S )$Return offset to next IFD from file.r   )rO  r  r/  ra  rv   rj  r@  rI  r?  r  rK  r   rl  rJ  )rp  rq  r/  r.  s       r   _nextifdzTiffPage._nextifd##  s    [#{
d.0G0GHHK
dn,ut|/CCDDDM$+RWWT_-E-EFFqI
 
 	
r   c                    | S )zReturn TiffPage instance.r   r  s    r   rX  zTiffPage.aspage.#  s    r   c                    | j         d         S )zIndex of page in IFD chain.rT  r  r  s    r   r  zTiffPage.index2#       {2r   c                    | j         S )zIndex of page in IFD tree.r  r  s    r   	treeindexzTiffPage.treeindex7#       {r   c                    | S )zSelf.r   r  s    r   rb  zTiffPage.keyframe<#  s	     r   c                    d S r   r   rp  r  s     r   rb  zTiffPage.keyframeA#  s    r   c                d    t          | j                  dk    r| j        n| j        d         }d| S )zName of image array.rW   r   	TiffPage r   r  r  s     r   ru   zTiffPage.nameE#  s7      #4;//!33Q"5"""r   c                *    t          | j                  S )z$Number of dimensions in image array.r   r   r  s    r   r  zTiffPage.ndimK#       4:r   tuple[str, ...]c                \    t           j        t          fd| j        D                       S )#Names of dimensions in image array.c              3  (   K   | ]}|         V  d S r   r   )r   rv  namess     r   r   z TiffPage.dims.<locals>.<genexpr>T#  s'      332U2Y333333r   )r   
AXES_NAMESr  r  )rp  r  s    @r   r  zTiffPage.dimsP#  s1     3333333333r   dict[str, int]c                n    | j         t          j        fdt          | j                  D             S )*Ordered map of dimension names to lengths.c                4    i | ]\  }}|         |         S r   r   )r   r  rv  r  r   s      r   r  z"TiffPage.sizes.<locals>.<dictcomp>[#  s'    FFF2b	58FFFr   )r   r   r  r  r  )rp  r  r   s    @@r   sizeszTiffPage.sizesV#  s;     
FFFFF491E1EFFFFr   dict[str, NDArray[Any]]c                `   |                                  }i }t          | j        | j                  D ]\  }}t          j        |         }d}d}|dk    r	|d         }nJ|dk    r	|d         }n;|dk    r|                                 }n |dk    r|d         |d         k    r|d         }|t          j        |          ||<   nS|dk    s|dk    s|dk    rt          j	        |          ||<   n)t          j
        d||z  |dt          j        	          ||<   t          ||                   |k    sJ |S )
4Ordered map of dimension names to coordinate arrays.NrW   r  r   r  r  r  F)endpointr~   )get_resolutionr  r  r   r   r  _sample_namesr  r   r  linspacer  r   )rp  r   coordsrv  rw   ru   rU  r  s           r   r  zTiffPage.coords]#  sW    ((**
*,DItz22 	- 	-HB?2&DE !DSyy!!}s!!}s**,,s a=JqM11%a=D $}U33tdaii4199$|D11t$~td{D5     t vd|$$,,,,,r   dict[str, Any]c                    i S )z/Arbitrary metadata associated with image array.r   r  s    r   rw  zTiffPage.attr#  s	     	r   c                *    t          | j                  S )z"Number of elements in image array.rD   r   r  s    r   rw   zTiffPage.size#       tz"""r   c                <    | j         dS | j        | j         j        z  S )zNumber of bytes in image array.Nr   )r~   rw   r  r  s    r   r  zTiffPage.nbytes#  s#     :1y4:...r   r7  c                6    | j                             d          S )zValue of Colormap tag.r  r  r  r  s    r   r   zTiffPage.colormap#       y  %%%r   c                6    | j                             d          S )zValue of InterColorProfile tag.r  r  r  s    r   r   zTiffPage.iccprofile#  s     y  '''r   c                6    | j                             d          S )zValue of TransferFunction tag.-  r  r  s    r   transferfunctionzTiffPage.transferfunction#  r  r   unitr  r  float | int | Nonetuple[int | float, int | float]c                Z   dddddd}|t          t          |          }	 |$| j                            dd	
          }||         }||         }||z  dk    r||z  }nJ||z  }nD# t          $ r3}t                                          | d|d           d}Y d}~nd}~ww xY w|d}g }dD ]p}	 | j                            |d
          \  }	}
|
dk    r|	|z  }n|	|
z  dk    r	|	|
z  |z  }n|	|
z  |z  }n# t          $ r d}Y nw xY w|                    |           q|d         |d         fS )a  Return number of pixels per unit in X and Y dimensions.

        By default, the XResolution and YResolution tag values are returned.
        Missing tag values are set to 1.

        Parameters:
            unit:
                Unit of measurement of returned values.
                The default is the value of the ResolutionUnit tag.
            scale:
                Factor to convert resolution values to meter unit.
                The default is determined from the ResolutionUnit tag.

        rW   gz^C@d     i@B )rW   r  r   r  r  Nr  r  r  r   z <get_resolution> raised r9  )r  r   r  )r7   r)   r  r  r  r=   rs  r   )rp  r  r  scalesr   scale2r  r   r  nr  rU  s               r   r  zTiffPage.get_resolution#  s   ( 
 
 7D))D$=%)Y%6%6sA%6%F%FN">2E  6>Q&&f$EEVOEE      DDDDD   	 ]E(*
  	% 	%D	y((v(>>166IEEUaZZFUNEEEEME   e$$$$!}jm++s*   &A$ $
B!.)BB!/AC55DDtuple[float, float]c                ~    |                                  }t          |d                   t          |d                   fS )z:Number of pixels per resolutionunit in X and Y directions.r   rW   )r  r  )rp  r   s     r   r   zTiffPage.resolution#  s8    
 ((**
Z]##U:a=%9%999r   c                :    | j                             dd          S )z,Unit of measurement for X and Y resolutions.r  r  r  r  r  s    r   r   zTiffPage.resolutionunit#  s     y  a 000r   DateTime | Nonec                    | j                             d          }|dS 	 t          |          S # t          $ r Y nw xY wdS )z Date and time of image creation.r  N)r  r  rH   r  r  s     r   rT   zTiffPage.datetime#  sY     	!!#&&=4	E??" 	 	 	D	ts   / 
<<c                n    | j         sdS | j        dk    r| j        | j        | j        fS | j        | j        fS )zTile depth, length, and width.NrW   )r  r  r  r  r  s    r   r   zTiffPage.tile#  sB     } 	4>ANDOT^DD00r   c                b   g }| j         dk    r|                    | j                    | j        r"|                    | j        | j        f           n!|                    | j        | j        f           | j        dk    r%| j	        dk    r|                    | j	                   t          |          S )z#Shape of images in tiles or strips.rW   )r  r   r  rQ  r  r  r   r  r   r  r  rp  r   s     r   chunkszTiffPage.chunks$  s     >ALL(((= 	?LL$/4>:;;;;LL$+T_=>>>!!d&:Q&>&>LL-...U||r   c                   g }| j         dk    r%| j        dk    r|                    | j                   | j        r| j        dk    r-|                    | j        | j        z   dz
  | j        z             |                    | j        | j        z   dz
  | j        z             |                    | j        | j	        z   dz
  | j	        z             ng| j        dk    r|                    | j                   |                    | j        | j
        z   dz
  | j
        z             |                    d           | j         dk    r | j        dk    r|                    d           t          |          S )zShape of chunked image.r  rW   )r   r  r   r  r  r  r  r  r  r  r   r  r  s     r   chunkedzTiffPage.chunked$  s    !!d&:Q&>&>LL-...= 	""_t~59dnL   LL!DO3a7DOK   LL4>1A5$.H    ""T_---LL!D$559d>OO   LLOOO!!d&:Q&>&>LLOOOU||r   c                    t          | j        | j        j        | j        | j        | j        | j        | j        | j	        | j
        | j        | j        | j        | j        fz             S )a  Checksum to identify pages in same series.

        Pages with the same hash can use the same decode function.
        The hash is calculated from the following properties:
        :py:attr:`TiffFile.tiff`,
        :py:attr:`TiffPage.shaped`,
        :py:attr:`TiffPage.rowsperstrip`,
        :py:attr:`TiffPage.tilewidth`,
        :py:attr:`TiffPage.tilelength`,
        :py:attr:`TiffPage.tiledepth`,
        :py:attr:`TiffPage.sampleformat`,
        :py:attr:`TiffPage.bitspersample`,
        :py:attr:`TiffPage.fillorder`,
        :py:attr:`TiffPage.predictor`,
        :py:attr:`TiffPage.compression`,
        :py:attr:`TiffPage.extrasamples`, and
        :py:attr:`TiffPage.photometric`.

        )r  r   rO  r/  r   r  r  r  r  r   r  r   r   r   r   r  s    r   r  zTiffPage.hash+$  sj    * K !!" ! 
 
 	
r   TiffPages | Nonec                D    d| j         vrdS t          | | j                  S )zSequence of sub-pages, SubIFDs.r  Nr	  )r  r	   r  r  s    r   r"  zTiffPage.pagesR$  s+     di4TZ0000r   c                   | j         s| j        dS | j        t          j        v r,t          t          j        t          | j                            S t          | j
                  | j        j        z  }|dk     rdS | j        dk    r|dk     rdS t          | j                  dk     rdS | j        dk    s| j        dk    s| j        dk    r3t          ,t          t          j        t          | j                            S dS )	zMaximum number of threads for decoding segments.

        A value of 0 disables multi-threading also when stacking pages.

        Nr   r  r  i 8  r  rW   r  )r  r~   r   r   rV  r  r  r   r$  rD   r	  r  r  r   r/  )rp  r  s     r   rr   zTiffPage.maxworkersY$  s      	!31t666tD,<(=(=>>>DK((4:+>>	t1q  Y%6%61t  1$$1q  DNa$7$74>Q;N;N&4?C0@,A,ABBBqr   c                h   | j         dk    s| j        dk    s	| j        dvrdS d| j        v rh| j        | j        k    s#| j        | j        z  s| j        dz  s
| j        dz  rdS d| j        v r*d| j        v r!| j        | j        k    s| j        | j	        z  rdS | j
        | j        t                    d	k    rdS t                    dk    rd
S | j        s| j        rd
S t                    | j        k    rdS t#          fdt%          t                    dz
            D                       rd
S dS )zImage data is stored contiguously.

        Contiguous image data can be read from
        ``offset=TiffPage.dataoffsets[0]`` with ``size=TiffPage.nbytes``.
        Excludes prediction and fillorder.

        r  rW   >   rY  r  r  r  Fr  r  r  r  r   Tc              3  l   K   | ].}|         d k    o|         |         z   |dz            k    V  /dS )r   rW   Nr   r   r  r  r  s     r   r   z)TiffPage.is_contiguous.<locals>.<genexpr>$  s_       
 
 qMQO71:
1#=Q#O
 
 
 
 
 
r   )r  r   r   r  r  r  r  r  r  r  r$  r  r   rZ  rC  r  r  rr  r  )rp  r  r  s    @@r   r  zTiffPage.is_contiguousr$  s    ""1$$!885$)4>11#do5 2>B& 2 ?R' 2
 u""TY&&$777 8 u"(
w<<15w<<14; 	$+ 	4z??dk))5 
 
 
 
 
3w<<!+,,
 
 
 
 
 	 4ur   c                L    | j         o| j        dk    o| j        dk    o| j         S )z<Image data are stored in final form. Excludes byte-swapping.rW   )r  r  r   r  r  s    r   r  zTiffPage.is_final$  s=      '!#'!#' &&		
r   c                    | j         j        j        o-| j        o&| j        duo| j        d         | j        j        z  dk    S )z7Image data in file can be memory-mapped to NumPy array.Nr   )rO  r  r  r  r~   r$  r  r  s    r   r#  zTiffPage.is_memmappable$  sP     K"* ?? 
$&	?
  #dj&99Q>	
r   c                v    t          | j                  dk    r| j        n| j        d         }d| d| j         dS )NrW   r   z<tifffile.TiffPage  @rj   r   r  rv   r  s     r   r!  zTiffPage.__repr__$  sB    "4;//!33Q<U<<dk<<<<r   c                *    |                                  S r   r3  r  s    r   r5  zTiffPage.__str__$  r6  r   r7  r8  r^  c                P     j          k    rt                               ||          S d}dD ]-}t           d|z             }|r|                                } n.d&d' fd
}d                    d d                    d  j        D                       t           j                  j	          j
         d                    d t           j                  j	         j        rdnd j        rdnd j        rdnd |d           |d           |d           |d          f|fz   D                       d                    d t!           j                  D                       fD                       }t%           j                  dk    r j        n j        d         }d| d j         d| }|dk    r|S | j                            |dz   |          g}|dk    r\dD ]Y}|dz   }t           |d          }|r?|                    |                                 d t/          |||d!z  "                      Z|d#k    rQ	                                  }	|                    d$t/          |	||d!z  "                      n# t2          $ r Y nw xY wd%                    |          S )(z4Return string containing information about TiffPage.r  )memmappabler]   r   r   rW   r  r   ru   r   r   c                   t          |           }||k    rdS 	 t          |d          }n# t          $ r Y dS w xY wt          |          S )Nr  ru   )r  r?  r   )ru   r  objrU  rp  s       r   tostrzTiffPage._str.<locals>.tostr$  sd    $%%Cd{{rV,,!   rru::s   , 
::r?  c              3  B   K   | ]}||                                 V  d S r   r=  rD  s     r   r   z TiffPage._str.<locals>.<genexpr>$  sF       
 
( -
GGII
 
 
 
 
 
r   r  c              3  4   K   | ]}t          |          V  d S r   rC  r  s     r   r   z TiffPage._str.<locals>.<genexpr>$  (      44AQ444444r    c              3     K   | ]}||V  	d S r   r   r  s     r   r   z TiffPage._str.<locals>.<genexpr>$  s>              r   REDUCEDrd  TILEDr   r   r   r  rR  c              3  >   K   | ]}|                                 V  d S r   rT  r>  s     r   r   z TiffPage._str.<locals>.<genexpr>$  s*      ??q??????r   r   r  r  r^  )rw  r9  rA  rY  rH  r   zDATA
rI  r  )r  r   ru   r   r   r   )rb  r   r4  r  rT  r   r   r*   r  ru   r   r&   r   r=  is_maskr  r|  r=  r   r  rv   r  r   rC   r   r  )
rp  r8  r^  rw  ru   r  r  r  rM  r   s
   `         r   r4  zTiffPage._str$  sx   =D  >>fe   : 	 	D4..D zz||	 	 	 	 	 	 	 yy 
 
 4444444 1227M9KMM   $D$455:%)_<		""&,6B#'=8bm,,n--k**k**	 g
     ??F4:,>,>?????%
 
 
 
 
0  #4;//!33Q9599DK99499Q;;K49>>&1*E>BBC	A::!  g~tT2.. $$::<< K K"4uVaZHHHK K   A::||~~  Gt5!DDDG G       {{9%%%s   ?J 
JJlist[str] | Nonec                   d| j         vrdS | j        | j                             d                   }t          | j                  }|dk     s|dk    rdS | j        dk    rdg}nO| j        dk    rdg}n@| j        dk    rg d}n0| j        d	k    rg d
}n | j        dk    r| j        dv rg d}ng d}ndS |dk    r;|t          t          | j        d                   j	        
                                gz  }|dk    r;|t          t          | j        d                   j	        
                                gz  }t          |          |k    rdS |S )zReturn names of samples.r  NrW   r  r   WhiteIsZeroBlackIsZero)RedGreenBluer  )CyanMagentaYellowBlackr  r  )LumaCbCr)r  r   r  r   r   r   r   r7   r!   ru   title)rp  rb  r   r  s       r   r  zTiffPage._sample_names%  s   di4*TY^^C0014,--Q;;,**4q  "OEE"""OEE"",,,EE"":::EE""#777000,,,4!gk4+<Q+?@@EKKMMNNE!gk4+<Q+?@@EKKMMNNEu::  4r   rO  c                4      fdt           j        D             S )z+Set of ``is\_\*`` properties that are True.c                ^    h | ])}t          d |z             |                                *S rR  rS  rT  s     r   r  z!TiffPage.flags.<locals>.<setcomp>+%  rU  r   )r   r,  r  s   `r   r=  zTiffPage.flags(%  rV  r   r   c                    | j         sdS d| j        d         j        i}| j        D ]I}|j        }d|cxk     rdk     sn |j        }t          |          dk    r
|dd         n|}|j        ||<   J|S )z&Consolidated metadata from Andor tags.NId   i  r  )is_andorr  rU  r  ru   r   )rp  r  r9  r  ru   s        r   r  zTiffPage.andor_tags1%  s     } 	4	$-.9 	% 	%C8D$%%%%%%%%8D"4yy1}}488$D9F4LLr   c                   | j         sdS i }| j        D ]}|j        }d|cxk    rdk     sn |j        }|dk    rt	          |          |d<   9|dk    rt          |          |d<   R|dk    rt          |          |d<   k|d	k    rt          |          |d
<   |                    dd          \  }}t          |          ||<   |S )zConsolidated metadata from EPICS areaDetector tags.

        Use the :py:func:`epics_datetime` function to get a datetime object
        from the epicsTSSec and epicsTSNsec tags.

        Nrx  r  	timeStampr  uniqueIDrB  
epicsTSSeci  epicsTSNsecr  rW   )is_epicsr  r  rU  r  r   r  r5   )rp  r  r9  r  rU  rn   s         r   r  zTiffPage.epics_tagsA%  s     } 	49 	, 	,C8DD((((5((((IEu}} ',Ell{##%(ZZz""'*5zz|$$(+E

}%%"[[a00
U$Ummsr   c                   | j         sdS | j        }i }dD ]}||         j        ||<   t          j                                        D ]\  }}||v r||         j        ||<   d|v rb|d         }d|v rQ|d                             t          j                  }|dz  }|                    t          j                  }||z  }|d= ||d<   |S )z/Consolidated metadata from Hamamatsu NDPI tags.N)MakeModelSoftware	McuStartsMcuStartsHighBytesr  )	r3  r  rU  r   	NDPI_TAGSr:  r5   r  r,  )rp  r  r  ru   r  r5  r6  s          r   	ndpi_tagszTiffPage.ndpi_tagsa%  s     | 	4y1 	, 	,D:+F4LL...00 	0 	0JD$t||#Dz/t&  {+I#v--23::5<HH%,,U\::	T!	/0"+F;r   c           
        | j         sdS | j        }|                    d          }|t          |          dk     s|d         dk    r&t	                                          | d           i S |d         |d         |d         d}t          j        }t          j        }t          |d                   D ]}	 |d	|d	z  z   |d	z  d
z            \  }}}	}
n># t          $ r1}t	                                          | d|d           Y d}~Vd}~ww xY w|dk    r|
}n	 ||         j        |
|
|	z            }n}# t          $ r4}t	                                          | d| d|d           Y d}~d}~wt          $ r4}t	                                          | d| d|d           Y d}~d}~ww xY w|dk    r|	dk    r|d         dk    r
|dd         }|	dk    r|n|d         }||v r#	  ||         |          }n# t          $ r Y nw xY w	  ||          j        }n# t          $ r |}Y nw xY w|||<   |                    d          }|Kt!          j        |          }|j        dk    r'|                    d                                          }||d<   |                    d          }|)t!          j        |                                          |d<   |                    d          }|Pt!          j        |                              d                                                                          }||d<   |                    d          }|>t!          j        |                              d                                          }||d<   |                    d          }|i d |d         d!|d         d"|d         d#|d         d$|d	         d%|d&         d'|d(         d)|d*         d+|d
         d,|d-         d.|d/         d0|d1         d2|d3d4         d5|d4d6         d7|d6d8         d9|d8d         |d:<   |S );z(Consolidated metadata from GeoTIFF tags.N鯇  r  r   rW   z invalid GeoKeyDirectoryTag)KeyDirectoryVersionKeyRevisionKeyRevisionMinorr   r  rY  z% corrupted GeoKeyDirectoryTag raised r9  z corrupted GeoKeyDirectoryTag r  z GeoKeyDirectoryTag z not found, raised 鱇  rT  rR  逄  r  r  r  IntergraphMatrix  ModelPixelScale還  )rT  r  ModelTiepoint؅  ModelTransformation  ERR_BIASERR_RANDLINE_OFFSAMP_OFFLAT_OFFLONG_OFFr  
HEIGHT_OFFr  
LINE_SCALEr  
SAMP_SCALE	LAT_SCALEr<  
LONG_SCALEr  HEIGHT_SCALErY  LINE_NUM_COEFFr  !   zLINE_DEN_COEFF 5   SAMP_NUM_COEFFI   SAMP_DEN_COEFFRPCCoefficient)r  r  r  r   r=   rs  r   GEO_KEYS	GEO_CODESr  r  rU  r   r  ru   r   r  r^  rw   rz  r  rq   )rp  r  gkdr  geokeysgeocodesr  keyidtagidr  rv   r  rU  rn   rpccs                  r   r  zTiffPage.geotiff_tagsz%  s     	4yll5!!;#c((Q,,#a&A++HHCCCDDDI $'q6q6 #A
 
 ->3q6]] (	  (	 E	.1	MEAIM1/+ueVV       + +!*+ +    zz K-fv~.EFEE$   HH$$ / / / /"%./ /   HHHH   HH$$ / /u / /"%./ /   HHHH E>>eaiiE"I4D4D!#2#JE!&a  +HUOE22EE    Dgenn)   F3KKU##K&&EzRf--4466).F%&U##(-E(:(:(A(A(C(CF$%U##K&&..w77??AAHHJJE&+F?#U##K&&..v66==??E,1F()( ||E""(DG(DG( DG( DG	(
 47( DG( d1g( d1g( d1g( T!W( d2h( R( !$r"u+( "42;( !$r"u+(  !$rss)!(F#$$ s`   6C
D'DDD33
F-=*E,,F-9*F((F-'G99
HH
HH*)H*r   c                    | j         | j        fD ]3}|rd|v r dS |dd         dk    rd|v r|c S |dd         dk    r|c S 4dS )z8Description containing array shape if exists, else None.z"mibi.NrW   {z"shape":r  shape=r   r  r  s     r   rl  zTiffPage.shaped_description%  s     !,d.?@ 	# 	#K (k"9"9tt2A2#%%**C*C""""2A2(**"""" +tr   c                r    | j         | j        fD ]'}|s dS |dd         dk    s|dd         dk    r|c S (dS )z(ImageJ description if exists, else None.Nr  ImageJ=zSCIFIO=rz  r  s     r   r;   zTiffPage.imagej_description&  si     !,d.?@ 	# 	#K tt2A2)++{2A2)/K/K"""" 0Ltr   c                P   | j         dvsRt          | j                  dk     s:| j        d         dk    s)t          | j                  dk     s| j        d         dk     rdS | j        j        }|                    | j        d         dz              |                    d          }|dk    S )	z/JPEG compressed segments contain JFIF metadata.r  rW   r   rY  Fr  r  s   JFIF)r   r   r$  r  rO  r  ra  r?  )rp  rq  r   s      r   r  zTiffPage.is_jfif&  s     $8884#$$q(("a''4&''!++"1%**5[#
 #a'(((wwqzzwr   c                    dS ))Object is :py:class:`TiffFrame` instance.Fr   r  s    r   is_framezTiffPage.is_frame&  	     ur   c                    dS )z)Page does not have IFD structure in file.Fr   r  s    r   
is_virtualzTiffPage.is_virtual!&  r  r   c                2    t          | j                  dk    S )zPage is SubIFD of another page.rW   r  r  s    r   	is_subifdzTiffPage.is_subifd&&       4;!##r   c                0    t          | j        dz            S )z'Page is reduced image of another image.rW   r   r   r  s    r   r=  zTiffPage.is_reduced+&  s     D$s*+++r   c                0    t          | j        dz            S )z!Page is part of multi-page image.r  r  r  s    r   r  zTiffPage.is_multipage0&  s     D$t+,,,r   c                0    t          | j        dz            S )z,Page is transparency mask for another image.r  r  r  s    r   r(  zTiffPage.is_mask5&  s     D$u,---r   c                0    t          | j        dz            S )z%Page is part of Mixed Raster Content.rY  r  r  s    r   is_mrczTiffPage.is_mrc:&  s     D$v-...r   c                    | j         dk    S )zPage contains tiled image.r   )r  r  s    r   r  zTiffPage.is_tiled?&  s     ~!!r   c                <    | j         | j         dk    S | j        dk    S )z&Page contains chroma subsampled image.Nr  r  )r   r   r  s    r   r  zTiffPage.is_subsampledD&  s)     '#v--1$$r   c                    | j         duS )z*Page contains ImageJ description metadata.N)r;   r  s    r   r  zTiffPage.is_imagejO&       &d22r   c                    | j         duS )z%Page contains Tifffile JSON metadata.N)rl  r  s    r   rl  zTiffPage.is_shapedT&  r  r   c                &    d| j         vod| j         v S )zPage contains MDFileTag tag.E  r  r  r  s    r   rf  zTiffPage.is_mdgelY&  s"     " #"	
r   c                &    d| j         v od| j         v S )z(Page contains Agilent Technologies tags.  r  r  r  s    r   r  zTiffPage.is_agilenta&  s     di6ETY$66r   c                    | j                             d          }	 |duo|j        dd         dk    S # t          $ r Y dS w xY w)z'Page contains Media Cybernetics Id tag.p  Nr  s   MC TIFFF)r  rY  rU  r  )rp  r9  s     r   
is_mediacyzTiffPage.is_mediacyg&  s\     immE""	d?Bsy!}
'BB 	 	 	55	s   3 
A Ac                    d| j         v S )zPage contains UIC1Tag tag.r  r  r  s    r   rZ  zTiffPage.is_stkp&       	!!r   c                    d| j         v S )zPage contains CZ_LSMINFO tag.r}  r  r  s    r   rC  zTiffPage.is_lsmu&  r  r   c                    d| j         v S )z$Page contains FluoView MM_STAMP tag.r  r  r  s    r   r[  zTiffPage.is_fluoviewz&  r  r   c                    d| j         v S )z!Page contains NIHImageHeader tag.r  r  r  s    r   r  zTiffPage.is_nih&  r  r   c                    | j         dk    S )z0Page contains SGI ImageDepth tag with value > 1.rW   )r  r  s    r   is_volumetriczTiffPage.is_volumetric&  s     ""r   c                    | j         dk    S )zSoftware tag is 'ISS Vista'.z	ISS Vistar   r  s    r   r#  zTiffPage.is_vista&  s     }++r   c                    | j         dk    s| j        dk    rdS | j        }|                    d          o|                    d          S )z>Page contains MDS MetaSeries metadata in ImageDescription tag.r   
MetaSeriesF
<MetaData>z</MetaData>)r  r   r   r  rP  )rp  r  s     r   r  zTiffPage.is_metaseries&  sK     :??dm|;;5||L))Gajj.G.GGr   c                    | j         dk    s| j        sdS | j        dd                                                             d          S )z.Page contains OME-XML in ImageDescription tag.r   FNr2  r  r   r=  rP  r  s    r   r>  zTiffPage.is_ome&  sG     :??$"2?5%++--66v>>>r   c                    | j         dk    s| j        sdS | j        dd                                                             d          S )z4Page contains Leica SCN XML in ImageDescription tag.r   Fr  Nz</scn>r  r  s    r   rp  zTiffPage.is_scn&  sG     :??$"2?5%++--66x@@@r   c                    d| j         v S )z'Page contains MicroManagerMetadata tag.  r  r  s    r   r\  zTiffPage.is_micromanager&  r  r   c                    d| j         v S )z.Page contains Andor Technology tags 4864-5030.r<  r  r  s    r   r=  zTiffPage.is_andor&  s     ty  r   c                N    | j         dd         dk    o| j        dd         dk    S )zPage contains Pilatus tags.NrY  zTVX TIFFr  # r   r   r  s    r   r  zTiffPage.is_pilatus&  s0     }RaR J.O43CBQB3G43OOr   c                .    | j         dk    p
| j        dk    S )z&Page contains EPICS areaDetector tags.zEPICS areaDetector)r   r   r  s    r   rC  zTiffPage.is_epics&  s%      44 5} 44	
r   c                    d| j         v S )zPage contains TVIPS metadata.r  r  r  s    r   r  zTiffPage.is_tvips&  r  r   c                &    d| j         v pd| j         v S )z*Page contains FEI_SFEG or FEI_HELIOS tags.r  r  r  r  s    r   r  zTiffPage.is_fei&       	!7Udi%77r   c                    d| j         v S )zPage contains CZ_SEM tag.r  r  r  s    r   r  zTiffPage.is_sem&  r  r   c                (    | j         dd         dk    S )zPage contains Aperio metadata.Nr  Aperio r   r  s    r   is_svszTiffPage.is_svs&  s     #y00r   c                    	 d| j         v o<d| j        v p3| j        dd         dk    p | j        dk    p| j        dk    p
| j        dk    S # t          $ r Y d	S w xY w)
zPage contains Ventana metadata.  VentanaN   ScanOutputManagerzLabel ImageLabel_ImageProbability_ImageF)r  r   r   r  r  s    r   is_bifzTiffPage.is_bif&  s    	$)#  T]* ;="%)<<;#}4; #}4; #'::  	 	 	55	s   AA 
AAc                p    | j         dd         dk    p#| j        dd         dk    pd| j        dd         v S )z!Page contains ScanImage metadata.Nr   zSI.r  zstate.zscanimage.SIi r  r  s    r   rE  zTiffPage.is_scanimage&  sN     M"1"& 9#x/9!1$%%!88	
r   c                (    | j         dd         dk    S )z"Page contains IndicaLabs metadata.N   IndicaLabsImageWriterr  r  s    r   ru  zTiffPage.is_indica&  s     }SbS!%<<<r   c                    	 d| j         v o%| j                             d          dd         dk    S # t          $ r Y dS w xY w)z%Page contains Argos AVS XML metadata.rx  Nr  z<ArgosF)r  r  r  r  s    r   ry  zTiffPage.is_avs&  s]    	"Oty'8'8'?'?'Cx'O  	 	 	55	s   .1 
??c                (    | j         dd         dk    S )z1Page contains PerkinElmer tissue images metadata.N   zPerkinElmer-QPIr  r  s    r   is_qpizTiffPage.is_qpi&  s    
 }SbS!%666r   c                    d| j         v S )zPage contains GeoTIFF metadata.rM  r  r  s    r   r  zTiffPage.is_geotiff&  r  r   c                    d| j         v S )zPage contains GDAL metadata.r  r  r  s    r   r  zTiffPage.is_gdal'  s     	!!r   c                N    | j         dd         dk    o| j         dd         dk    S )z&Page contains AstroTIFF FITS metadata.Nr  zSIMPLE r  ENDr  r  s    r   r  zTiffPage.is_astrotiff	'  s6     RaR I- / %.	
r   c                J    | j         dd         dk    od| j         dd         v S )z(Page contains Hamamatsu streak metadata.NrW   [z],r  r  r  s    r   r  zTiffPage.is_streak'  s6     RaR C' /(2..	
r   c                    d| j         v S )zPage contains DNG metadata.  r  r  s    r   is_dngzTiffPage.is_dng'  r  r   c                    d| j         v S )zPage contains TIFF/EP metadata.  r  r  s    r   	is_tiffepzTiffPage.is_tiffep'  r  r   c                &    d| j         v pd| j         v S )z#Page contains Olympus SIS metadata.r  r  r  r  s    r   ri  zTiffPage.is_sis$'  r  r   c                &    d| j         v od| j         v S )zPage contains NDPI metadata.    r  r  s    r   r3  zTiffPage.is_ndpi)'  s     	!6cTY&66r   c                    | j         dd         dk    o3| j        dd                                                             d          S )z"Page contains Philips DP metadata.Nr  z
Philips DPiz</DataObject>)r   r   r=  rP  r  s    r   rs  zTiffPage.is_philips.'  sG     }SbS!\1 ,d6FDD7

%''((?++	,r   c                j    | j         j        o'| j        dv od| j        v o| j        d         j        dk    S )z'Page contains EER acquisition metadata.>   rW   rx  r  rB  r  r  )rO  r_  r   r  r~   r  s    r   r  zTiffPage.is_eer5'  sJ     K" , $<<,", 	% &!+		
r   )r  r   rO  r   rb  r  r   r  r   r7  )r  r  rr   r   r  r  r{   r   rs   r   rm  r   r   r  )r   r   rq   r   r  r  rr   r   rs   r   r   r   r   rb   r   rj  )r  r   r  r  r   rb   r   r   NNr  r  r  r  r   r  r  r   r   r   r  )r  r   r   r  r&  r   r  r   r  r   r  r   r  )r   r7  )r   r   )r  r  r  r  r   r  r   r  r   r  r   r   )r   r  r  r  r  )r   r)  r  r  r  )r*  r+  r,  r-  r'  r   r  r  r  r  r  r  r  r   r  r   r   r   r  r   r   r   r   rt  r   r  r   r   r  r  rs  rV   r  r  r   rm   r  r  r  rX  r(  r  r  rb  setterru   r  r  r  r  rw  rw   r  r   r   r  r  r   r   rT   r   r	  r  r  r"  rr   r  r  r#  r!  r5  r4  r  r=  r  r  rK  r  rl  r;   r  r  r  r  r=  r  r(  r  r  r  r  rl  rf  r  r  rZ  rC  r[  r  r  r#  r  r>  rp  r\  r=  r  rC  r  r  r  r  r  rE  ru  ry  r  r  r  r  r  r  r  ri  r3  rs  r  r   r   r   r   r   #  s         ( NNN!,KKK#'""""+**** III !   /####*#### K-J6K"J&I)J&I*O)M-L<!L!!!!#K<LJI:K7II$&L&&&&N*.K....>&*G****'#J####/#J####H(KL/FM %)`= `= `= `= `= `=D P	# P	# P	# _P	#j 6:!%*.!%!%X> X> X> X> X> X>z 59!%!%O O O O O Ob	- 	- 	- 	- '+	; ; ; ; ; ;~ (,'+	
 
 
 
 
	
 	
 	
 	
       X    X    X _   _ # # # X#
    X 4 4 4 _4
 G G G _G    _B    _
 # # # _# / / / _/ & & & X& ( ( ( X( & & & X& ,0$(=, =, =, =, =,~ : : : _: 1 1 1 X1 	 	 	 X	 1 1 1 X1    _    _6 $
 $
 $
 _$
L 1 1 1 _1    _0 . . . _.` 
 
 
 _
 	
 	
 	
 _	
= = = =   F& F& F& F& F&P   @ 
 
 
 _
    _    _>    _0 y y y _yv 	 	 	 _	    _    _    X    X $ $ $ X$ , , , X, - - - X- . . . X. / / / X/ " " " X" % % % X% 3 3 3 X3 3 3 3 X3 
 
 
 X
 7 7 7 X7
    X " " " X" " " " X" " " " X" " " " X" # # # X# , , , X, H H H XH ? ? ? X? A A A XA " " " X" ! ! ! X! P P P XP 
 
 
 X
 " " " X" 8 8 8 X8 " " " X" 1 1 1 X1    X 
 
 
 X
 = = = X=    X 7 7 7 X7 " " " X" " " " X"
 
 
 
 X
 
 
 
 X
 " " " X" " " " X" 8 8 8 X8 7 7 7 X7 , , , X, 
 
 
 X
 
 
r   r   c                     e Zd ZU dZdZdZded<   dZded<   d	ed
<   	 ded<   	 ded<   	 ded<   	 ded<   	 ded<   	 ded<   ded<   ddddddfdZ	 	 dgdhd#Z	did$Z
djd&Zdkd+Zdld-Zdkd.Zdmd0Zedid1            Zednd2            Zedod3            Zej        dpd5            Zedqd6            Zedqd7            Zedqd8            Zedqd9            Zedqd:            Zedqd;            Zedid<            Zednd=            Zedrd?            Zednd@            ZedndA            ZedsdB            Z edtdD            Z!edidE            Z"edudG            Z#edvdI            Z$edwdK            Z%edidL            Z&edidM            Z'edxdO            Z(edtdP            Z)	 	 dgdydVZ*edzdX            Z+edidY            Z,ed{d[            Z-edid\            Z.ed|d^            Z/dtd_Z0dtd`Z1d}d~deZ2dS )r   a  Lightweight TIFF image file directory (IFD).

    The purpose of TiffFrame is to reduce resource usage and speed up reading
    image data from file compared to TiffPage.
    Properties other than `offset`, `index`, `dataoffsets`, `databytecounts`,
    `subifds`, and `jpegtables` are assumed to be identical with a specified
    TiffPage instance, the keyframe.
    TiffFrame instances have no `tags` property.
    Virtual frames just reference the image data in the file. They may not
    have an IFD structure in the file.

    TiffFrame instances are not thread-safe. All attributes are read-only.

    Parameters:
        parent:
            TiffFile instance to read frame from.
            The file handle position must be at an offset to an IFD structure.
            Only a limited number of tag values are read from file.
        index:
            Index of frame in IFD tree.
        offset:
            Position of frame in file.
        keyframe:
            TiffPage instance with same hash as frame.
        dataoffsets:
            Data offsets of "virtual frame".
        databytecounts:
            Data bytecounts of "virtual frame".

    )rO  rv   r$  r  rt  r   	_keyframer  Fr   rf  Nr  r"  r   rO  r   rv   r  r$  r  r   rt  r   r   r  r  r  r  r  r   r   rb  c                 d | _         || _        |rt          |          nd| _        d | _        d | _        d| _        d| _        t          |t                    r	|f| _	        nt          |          | _	        |$|"|dn|| _        || _        || _        || _         d S ||j                                        | _        n|j                            |           |h d}n|j        rh d}|j        | _        nh d}|                     |          D ]t\  }}	|dv r|	j        | _        |dv r|	j        | _        '|dk    r|	j        | _        :|d	k    r|	j        | _        M||d
k    r|j        |	j        k    rt%          d          u| j        s%t'                                          | d           n;|9t+          | j                  t+          |j                  k    rt%          d          |	|| _        d S d S )Nr   r   >   r  r  r  r  r  r  >   r  r  r  r  >   r  r  r  r  r  r  r  >   r  r  >   r  r  r  r  r  incompatible keyframez is missing required tags)r  rO  r   rv   rt  r   r$  r  r   r  r  r  r]  ra  r  r  rU  r  rg  r=   rs  r   rb  )
rp  rO  r  rv   rb  r$  r  r  r  r9  s
             r   rs  zTiffFrame.__init__'  sK    %+2c&kkk eS!! 	' (DKK,,DK"~'A%~!!6DK*D"0D%DNF> +0022DKK""6***111DD# 	7'''D"*"9D666Dt,, 	< 	<ID#z!!#&9  ##&)i##"y"%)! 3sy @ @"#:;;; 	8HHAAABBBB!c$*:&;&;s @
 @
 '
 '
 6777$DMMM  r   r  r  r  r  r   r  c          
        | j         j        }| j         j        }t          j        }|t                      n|}g }|5  |                    | j                   	  ||j        |	                    |j
                            d         }|dk    rt          d|           n*# t          $ r}	t          d| j                   |	d}	~	ww xY w| j        |j
        z   }
|j        }| }|j        dd         }|	                    ||z            }t!          |          D ]}||z  } |||||dz                      d         }|r||vr+	 t"                              | j         |
|z   ||||z                      }n># t          $ r1}	t'                                          | d|	d	           Y d}	~	d}	~	ww xY w|                    ||f           	 ddd           n# 1 swxY w Y   |S )
z)Return list of (code, TiffTag) from file.Nr   r  r  r  r  r  z <TiffTag.fromfile> raised r9  )rO  r  r/  rj  r@  r2   ra  rv   rI  r?  r  r   r  r   rK  r  r  r   r  r=   rB  r   )rp  r  r  rq  r/  r@  rlockr  r.  r  r  rK  r  
codeformattagbytesr	  r  r9  s                     r   r  zTiffFrame._gettags'  s    [#{&*l[]]] !	) !	)GGDK   t/1H1HII!L4<<$%I%%I%IJJJ     #84;88 
 dn4IlGxH!,Jwww//H5\\ ) )G#vj(8hl3J*KLLQO T..
!**(83'8g3E(EF +  CC
 %   HHNNJJcJJJ   HHHH	
 T3K((((!)#!	) !	) !	) !	) !	) !	) !	) !	) !	) !	) !	) !	) !	) !	) !	)F sa   GABG
C)CCA=G0E54G5
F0?'F+&G+F00GGGc                6    t                               |           S )r  )r   r  r  s    r   r  zTiffFrame._nextifd'  s      &&&r   r   c                   | j         rt          d          | j        j        }|j        }|r1t          j        | dt                     |                                 	 |	                    | j
                   t          | j        | j                  }|r|                                 n# |r|                                 w w xY w|S )zSReturn TiffPage from file.

        Raise ValueError if frame is virtual.

        z#cannot return virtual frame as pagez" reading TiffPage from closed filer	  )r  r   rO  r  r  rm  rn  ro  r  ra  rv   r   r  r  )rp  rq  r  r  s       r   rX  zTiffFrame.aspage(  s     ? 	DBCCC[# 	 M==={   GGIII	GGDK   DKtz:::D 


  



s   5B* *Cr;  rb   r   r   c                ,    t          j        | g|R i |S )zReturn image from frame as NumPy array.

        Parameters:
            **kwargs: Arguments passed to :py:meth:`TiffPage.asarray`.

        )r   r   rp  r;  r   s      r   r   zTiffFrame.asarray(  s6     

 
 
!
 
 	
r   rj  c                     ddl m}  || fi |S )zReturn image from frame as Zarr store.

        Parameters:
            **kwarg: Arguments passed to :py:class:`ZarrTiffStore`.

        rW   r  r  r  s      r   rm   zTiffFrame.aszarr%(  r  r   c                ,    t          j        | g|R i |S )zbReturn image from frame as RGB(A). Work in progress. Do not use.

        :meta private:

        )r   r  r  s      r   r  zTiffFrame.asrgb0(  s$     ~d4T444V444r   r  c                ,    t          j        | g|R i |S )zReturn iterator over decoded tiles or strips.

        Parameters:
            **kwargs: Arguments passed to :py:meth:`TiffPage.segments`.

        :meta private:

        )r   r  r  s      r   r  zTiffFrame.segments8(  s6      

 
 
!
 
 	
r   c                    | j         d         S )zIndex of frame in IFD chain.rT  r  r  s    r   r  zTiffFrame.indexK(  r  r   c                    | j         S )zIndex of frame in IFD tree.r  r  s    r   r  zTiffFrame.treeindexP(  r  r   c                    | j         S )z,TiffPage with same properties as this frame.r  r  s    r   rb  zTiffFrame.keyframeU(       ~r   r  c                   | j         |k    rd S | j         t          d          t          | j                  t          |j                  k    rt          d          |j        r|j        | _        || _         d S )Nzcannot reset keyframer  )r  rg  r   r$  r  r  )rp  rb  s     r   rb  zTiffFrame.keyframeZ(  s|    >X%%F>%6777t  C(<$=$===6777! 	:"*"9D!r   c                    dS )r  Tr   r  s    r   r  zTiffFrame.is_framef(  s	     tr   c                    | j         dk    S )z*Frame does not have IFD structure in file.r   r  r  s    r   r  zTiffFrame.is_virtualk(  s     {ar   c                2    t          | j                  dk    S )z Frame is SubIFD of another page.rW   r  r  s    r   r  zTiffFrame.is_subifdp(  r  r   c                ,    | j         J | j         j        S r   )r  r  r  s    r   r  zTiffFrame.is_finalu(  s    ~)))~&&r   c                ,    | j         J | j         j        S r   )r  r  r  s    r   r  zTiffFrame.is_contiguousz(  s    ~)))~++r   c                ,    | j         J | j         j        S r   )r  r#  r  s    r   r#  zTiffFrame.is_memmappable(      ~)))~,,r   c                ,    | j         J | j         j        S r   )r  r  r  s    r   r  zTiffFrame.hash(      ~)))~""r   c                ,    | j         J | j         j        S r   )r  r   r  s    r   r   zTiffFrame.shape(      ~)))~##r   r  c                ,    | j         J | j         j        S r   )r  r   r  s    r   r   zTiffFrame.shaped(      ~)))~$$r   c                ,    | j         J | j         j        S r   )r  r	  r  s    r   r	  zTiffFrame.chunks(  r	  r   c                ,    | j         J | j         j        S r   )r  r  r  s    r   r  zTiffFrame.chunked(  s    ~)))~%%r   c                ,    | j         J | j         j        S r   )r  r   r  s    r   r   zTiffFrame.tile(  r  r   r   c                d    t          | j                  dk    r| j        n| j        d         }d| S )NrW   r   
TiffFrame r  r  s     r   ru   zTiffFrame.name(  s5    "4;//!33Q#E###r   c                ,    | j         J | j         j        S r   )r  r  r  s    r   r  zTiffFrame.ndim(  r  r   r  c                ,    | j         J | j         j        S r   )r  r  r  s    r   r  zTiffFrame.dims(  r  r   r  c                ,    | j         J | j         j        S r   )r  r  r  s    r   r  zTiffFrame.sizes(  r  r   r  c                ,    | j         J | j         j        S r   )r  r  r  s    r   r  zTiffFrame.coords(  r	  r   c                ,    | j         J | j         j        S r   )r  rw   r  s    r   rw   zTiffFrame.size(  r  r   c                ,    | j         J | j         j        S r   )r  r  r  s    r   r  zTiffFrame.nbytes(  r	  r   r;  c                ,    | j         J | j         j        S r   )r  r~   r  s    r   r~   zTiffFrame.dtype(  r  r   c                ,    | j         J | j         j        S r   )r  r  r  s    r   r  zTiffFrame.axes(  r  r   r  RESUNIT | int | Noner  r  r  c                J    | j         J | j                             ||          S r   )r  r  )rp  r  r  s      r   r  zTiffFrame.get_resolution(  s*    
 ~)))~,,T5999r   r  c                ,    | j         J | j         j        S r   )r  r   r  s    r   r   zTiffFrame.resolution(  s    ~)))~((r   c                ,    | j         J | j         j        S r   )r  r   r  s    r   r   zTiffFrame.resolutionunit(  r  r   r  c                ,    | j         J | j         j        S r   )r  rT   r  s    r   rT   zTiffFrame.datetime(  s     ~)))~&&r   c                ,    | j         J | j         j        S r   )r  r   r  s    r   r   zTiffFrame.compression(  s    ~)))~))r   r7  c                ,    | j         J | j         j        S r   )r  r  r  s    r   r  zTiffFrame.decode(  s     ~)))~$$r   c                v    t          | j                  dk    r| j        n| j        d         }d| d| j         dS )NrW   r   z<tifffile.TiffFrame r  rj   r  r  s     r   r!  zTiffFrame.__repr__(  sB    "4;//!33Q=e==t{====r   c                *    |                                  S r   r3  r  s    r   r5  zTiffFrame.__str__(  r6  r   r   r7  r8  r^  c                   | j         d}d}nsd                    d d                    d | j        D                       t          | j                  fD                       }| j                             |dz
            }|d	k    rEt          | j        |d
z
  |d	z
            }t          | j        |dz
  |d	z
            }d| d| d| }t          | j
                  dk    r| j
        n| j
        d         }d| d| j         d| S )z5Return string containing information about TiffFrame.Nr  r?  c              3     K   | ]}|V  d S r   r   rD  s     r   r   z!TiffFrame._str.<locals>.<genexpr>)  s6              r   r  c              3  4   K   | ]}t          |          V  d S r   rC  r  s     r   r   z!TiffFrame._str.<locals>.<genexpr>
)  s(      88SVV888888r   rY  r'  r   r<  rH  r  z
 Keyframe z

 Offsets z
 Bytecounts rW   r   r  r  )r  r   r   r   r~   r4  rC   r$  r  r   r  rv   )rp  r8  r^  r  kfofbcr  s           r   r4  zTiffFrame._str)  sE   >!DBB99   HH88TZ88888
OO    D $$52:$66BA::)6A:NNNB#52:fqj  B H"GGGG2GGD"4;//!33Q:E::T[::D:::r   )r  r   rO  r   rv   r   rb  r  r$  r   r  r   r  r  r  r  )r;  rb   r   rb   r   r   r  )r;  rb   r   rb   r   r  r  r   r  )rb  r   r   r  r  r   r  r  r&  r  r  r  )r   r;  )r  r  r  r  r   r  r  r  r  r  r  )3r*  r+  r,  r-  r  rf  r'  r"  rs  r  r  rX  r   rm   r  r  r(  r  r  rb  r  r  r  r  r  r  r#  r  r   r   r	  r  r   ru   r  r  r  r  rw   r  r~   r  r  r   r   rT   r   r  r!  r5  r4  r   r   r   r   r   @'  s         >	I H"E"""" -KKK$    /####*####'2 "$(.215D% D% D% D% D% D%P (,'+	0 0 0 0 0d' ' ' '   2	
 	
 	
 	
	- 	- 	- 	-5 5 5 5
 
 
 
&    X    X    X _	" 	" 	" _	"    X       X  $ $ $ X$ ' ' ' X' , , , X, - - - X- # # # X# $ $ $ X$ % % % X% % % % X% & & & X& # # # X# $ $ $ X$ # # # X# # # # X# $ $ $ X$ % % % X% # # # X# % % % X% $ $ $ X$ # # # X# &*$(: : : : : ) ) ) X) - - - X- ' ' ' X'
 * * * X* % % % X%> > > >   ; ; ; ; ; ; ;r   r   c                  4   e Zd ZU dZdZded<   	 ded<   ded<   d	ed
<   ded<   ded<   ded<   ded<   ded<   ded<   dddMdZedNd            ZedOd            Z	edPd             Z
edPd!            Zej        dQd#            ZedPd$            Zej        dQd%            ZedRd&            ZdSd'ZedTd(            Z	 dUd)d*d+d,dVd4ZdWdXd7ZdYd8ZdWdZd:Zd[d;Z	 	 	 d\d]d?Zd)d*d*d,d^d@Zed_dA            Zed`dC            ZdadFZdbdHZdPdIZdcdJZdddLZdS )er	   a  Sequence of TIFF image file directories (IFD chain).

    TiffPages instances have a state, such as a cache and keyframe, and are not
    thread-safe. All attributes are read-only.

    Parameters:
        arg:
            If a *TiffFile*, the file position must be at offset to offset to
            TiffPage.
            If a *TiffPage* or *TiffFrame*, page offsets are read from the
            SubIFDs tag.
            Only the first page is initially read from the file.
        index:
            Position of IFD chain in IFD tree.

    Nr.  rO   list[TiffPage | TiffFrame | int]r  r  r  z type[TiffPage] | type[TiffFrame]	_tiffpager   _indexed_cached_cacher   _offsetr   _nextpageoffsetr   r  r	  argTiffFile | TiffPage | TiffFramer  Sequence[int] | int | Noner   r  c              t   d | _         g | _        d| _        d| _        t          | _        d | _        d| _        d| _        d | _	        |d | _
        nKt          |t          t          j        f          rt          |          f| _
        nt          |          | _
        t          |t                     r|| _         | j         j        }|                                | _	        t'          j        | j         j        j        |                    | j         j        j                            d         }|dk    r-t3                                          |d           d| _        d S n|j        t|j        }|j         | _         | j         j        }t9          |          dk    s|d         dk    r-t3                                          |d           d| _        d S |d         }n	d| _        d S || _        ||j        k    r/t3                                          | d|           d| _        d S | j
        dn	| j
        dz   }|                    |           t	          | j         |          }| j                            |           || _        | j	        2| j                             |d	d                     d| _        d| _        d S d S )
NFr   z contains no pagesTz contains invalid SubIFDsz invalid offset to first page r  r	  rW   )!rO  r  r+  r,  r   r*  r  r-  r.  r/  r  r   r   r  r`  r  r   r  r]  rj  r@  r/  rl  r?  rJ  r=   rs  rt  r   rw   ra  r   rQ  )rp  r0  r  rq  rv   r  r  r  s           r   rs  zTiffPages.__init__9)  s    !#=DKKU]344 	'u::-DKK,,DKc8$$ 	DK'B#%7799D ] -(344  F {{  C!=!=!=>>> $  [$kG*DK'B7||q  GAJ!OO  C!D!D!DEEE $QZFF DMFRWHHCCCC   !DMF $AA$+*< 	
 	95554   'Kwqrr{+++ DMDLLL	 ('r   c                H    t          j        dt          d           | j        S )zSDeprecated. Use the TiffPages sequence interface.

        :meta private:

        z_<tifffile.TiffPages.pages> is deprecated since 2024.5.22. Use the TiffPages sequence interface.r  r  )rm  rn  r\  r  r  s    r   r"  zTiffPages.pages)  s2     	4		
 	
 	
 	
 {r   r   c                B    t          t          | j        d                   S )z8First page as TiffPage if exists, else raise IndexError.r   )r\   r   r  r  s    r   r  zTiffPages.first)  s     Hdk!n---r   c                T    	 |                      d           dS # t          $ r Y dS w xY w)z&IFD chain contains more than one page.rW   TF)_seekr  r  s    r   r  zTiffPages.is_multipage)  s=    	JJqMMM4 	 	 	55	s    
''c                    | j         S )z`Pages and frames are being cached.

        When set to *False*, the cache is cleared.

        )r-  r  s    r   r  zTiffPages.cache)  s     {r   rU  c               l    t          |          }| j        r|s|                                  || _        d S r   )r   r-  r  r  s     r   r  zTiffPages.cache)  s6    U; 	u 	KKMMMr   c                "    | j         t          k    S )z)Use TiffFrame (True) or TiffPage (False).)r*  r   r  s    r   rH  zTiffPages.useframes)  s     ~**r   c               0    |rt           nt          | _        d S r   )r   r   r*  r  s     r   rH  zTiffPages.useframes)  s    &+9r   c                    | j         S )z-TiffPage used as keyframe for new TiffFrames.r  r  s    r   rb  zTiffPages.keyframe)  r  r   c                  t          |t          t          j        f          st	          dt          |                     t          |          }|dk     r|t          |           z  }| j        | j        j        |k    rdS |dk    r't          t          | j        d                   | _        dS | j        s|t          | j                  k     rO| j        |         }t          |t                    r	|| _        dS t          |t                    r|j        | j        |<   | j        }t          | _        	 t          t          |                     |                    | _        || _        n# || _        w xY w| j        | j        |<   dS )zSet keyframe to TiffPage specified by `index`.

        If not found in the cache, the TiffPage at `index` is loaded from file
        and added to the cache.

        zindices must be integers, not r   N)r   r   r  r`  r   r~  r   r  r  r\   r   r  r+  r   rv   r*  _getitem)rp  r  r  r'  s       r   r  zTiffPages.set_keyframe)  sh    %#u}!566 	LJT%[[JJKKKE

199SYYE>%$.*>%*G*GFA::!(DKN;;DNF= 	1EC$4$444;u%D$)) !%$	** 1%)[E">!	&!(DMM%,@,@AADN%DNNXDN%%%%!^Es   0-E% %	E.c                H    | j         s|                     d           | j        S )z.Offset where offset to new page can be stored.rT  )r+  r7  r/  r  s    r   r`  zTiffPages.next_page_offset)  s&     } 	JJrNNN##r   r   FTr  r  rX  r  TiffPage | TiffFrame | Nonern   r  r  rX  r  c              `    	 |                      ||||          S # t          $ r | Y nw xY w|S )a  Return specified page from cache or file.

        The specified TiffPage or TiffFrame is read from file if it is not
        found in the cache.

        Parameters:
            key:
                Index of requested page in IFD chain.
            default:
                Page or frame to return if key is out of bounds.
                By default, an IndexError is raised if key is out of bounds.
            validate:
                If non-zero, raise RuntimeError if value does not match hash
                of TiffPage or TiffFrame.
            cache:
                Store returned page in cache for future use.
            aspage:
                Return TiffPage instance.

        r@  )r>  r  )rp  rn   r  r  r  rX  s         r   rY  zTiffPages.get)  s^    <	==heF !     	 	 	 	 s    ++rb  TiffPage | bool | Nonec                  | j         J | j        rdS | j        }|sdS | j        s|                     d           | j        sdS | j         j        }|| j        }t          |          D ]q\  }}t          |t          t          j        f          rK| j        |n
| j        |fz   }|                    |           |                     | j         ||          }|||<   rd| _        dS )z#Read all remaining pages from file.NrT  r  rb  T)rO  r,  r  r+  r7  r-  r  r  r  r   r   r  r`  r  ra  r*  )rp  rb  r"  rq  r  r  r  s          r   r  zTiffPages._load*  s   {&&&< 	F 	F} 	JJrNNN{ 	F[#~H '' 		  		 GAt$em 455  ,AA$+2D  ~~Ky8 &    ar   c                n   | j         J | j        }	 t          |          dk    rt          d          t	          t
          |d                   }|j        st          d          |                     d           t	          t          |d                   t	          t          |d                   z
  }t	          t          |d                   t	          t          |d                   z
  |k    s;t	          t          |d                   t	          t          |d                   z
  |k    rt          d	          | 	                    d|j
        
          }|j        d         |j        z
  }|dk     s||k    rt          d	          ||g}| j         j        j        |z
  }t          t!          |j        |z   ||                    D ]}\  }}|dz  }||z  t#          fd|j        D                       }	|dk     r|nd}
|                    t'          |j         | j        |n
| j        |fz   |
|	|j        |                     ~|| _        d| _        d| _        d| _        dS # t2          $ rM}| j         j        j        dk    r-t5                                          | d|d           Y d}~dS Y d}~dS d}~ww xY w)zCalculate virtual TiffFrames.NrW   zpages already loadedr   zdata not contiguousr  r  r   zpage offsets not equidistantr  c              3  "   K   | ]	}|z   V  
d S r   r   )r   r  r  s     r   r   z1TiffPages._load_virtual_frames.<locals>.<genexpr>I*  s'      #D#DaAE#D#D#D#D#D#Dr   r  T        z <_load_virtual_frames> raised r9  )rO  r  r   r   r\   r   r  r7  r   r>  r  r$  rv   r  rw   r  r  r  r   r   r  r  r-  r,  r+  r  r=   rs  )rp  r"  r  deltapage1offsetoffsetr  r  rv   r$  offset_or_noner  r  s               @r   rF  zTiffPages._load_virtual_frames+*  s   {&&&2	5zzA~~ !7888%(++D% 8 !6777JJqMMMeAh''$sE!H*=*==ES%(##d3a&9&99UBBU1X&&c58)<)<<EE !?@@@MM!diM88E ,Q/%,>La<%#7#7 !?@@@5ME{-2U:H!*elU*He<<" "  v 
EM##D#D#D#D43C#D#D#DDD+1I+=+=4  ${2 "E!%x!7-$/'+':!%       DKDKDL DMMM 	 	 	{%*j88  JJcJJJ         988888	s   II 
J4'<J//J4fullyc               r   | j         }|sdS t          t          |d                   | _        |rGt	          |dd                   D ].\  }}t          |t                    s|j        |j        ||dz   <   /n;t	          |          D ]+\  }}t          |t                    r|j        
|j        ||<   ,d| _	        dS )zADelete all but first page from cache. Set keyframe to first page.Nr   rW   F)
r  r\   r   r  r  r   r   rv   r   r,  )rp  rN  r"  r  r  s        r   r  zTiffPages._clearc*  s     	Fha11 		+$U122Y// / /4!$,, /1H#';E!a%L/
 %U++ + +4dI.. +4;3J#{E!Hr   c                  | j         J | j        }t          |          }|dk    rt          d          | j         j        }|j        rt          d          | j        sd|cxk    r|k     r>n n;||         }t          |t                    r|n|j
        }|                    |          S | j         j        }|j        }|j        }	|j        }
|j        }|j        }t$          j        }|d         }t          |t                    r|n|j
        }|dk     rk|                    |           	 t           ||
|                    |                    d                   }|dk    rt+          d|           nT# t,          $ rG}t/                                          | d	| d
| d|d           |d= |dz  }d| _        Y d}~nd}~ww xY w||z   ||z  z   | _        |                    | j                   	 t           |||                    |	                    d                   }nT# t,          $ rG}t/                                          | d|dz    d
| j         d|d           d| _        Y d}~nd}~ww xY w|dk    rd| _        n||j        k    r.t/                                          | d|           d| _        n|                    |           |dz  }d|cxk    r|k     rn nn|dk    rt9          |dd                   D ]m\  }}|t          |t                    r|n|j
        k    rF|}|d|dz            | _        d| _        t/                                          | d| d|            nn|dk     k||k    rt          d          ||         }|                    t          |t                    r|n|j
                  S )zASeek file to offset of page specified by index and return offset.Nr   zindex out of rangezseek of closed filerT  r|  r  r  z corrupted tag list of page r  r  r9  rW   Tz invalid offset to page z invalid page offset r  z# invalid circular reference to IFD z at offset=)rO  r  r   r  r  r  r   r+  r   r   rv   ra  r/  rl  rJ  rI  r  rK  rj  r@  r?  r   r  r=   rB  r/  rw   r   r  )rp  r  r"  r  rq  r  rv   r/  rl  rJ  rI  r  rK  r@  r.  r  r  r]  s                     r   r7  zTiffPages._seeku*  s   {&&&u::q==1222[#9 	42333= 	#A111111111<D'c22CTTF776??"{(_
&N	,Ry#D#..?DKGGFOOOFF;	0B0BCCAFGG4<<'(LU(L(LMMM      @ @@ @#)@ @36?@ @   "IA $ $*I#5#GD GGD()))	VVL"''*2E2EFFqIJJ    + +!|+ +'+';+ +!*+ +  
 !% {{ $  $IIvIIJJJ $LL   MHE$$$$H$$$$$ 3%eCRCj11 	 	DAqz!S'9'9"G!!qxHH !&+Ga!eGn(,# 0 0 0 0&,0 0    I_ r H1222U|wwz$44Ett$+FFFs1   'A
E2 2
G<<F>>G12H$ $
I5.<I00I5rH  r   list[TiffPage | TiffFrame]c          	     b  
 | j         
| j        }|+t          t          t	          |                               }nUt          |t          t          j        f          rDt          |          }d| _        |dk    r| j	        gS 	  
|          g|| _        S # || _        w xY wt          |t                    r|                    d          \  }}}| j        s;t          ||          t	          | j                  k    r|                     d           t          t          |                    t	          | j                                       }nDt          |t                     rt          |          }nt#          dt%          |                     | j        J | j        }|                     t+          |                     |r| j        j        nd|rd| _        	 
fd|D             }	|	                    d| j                   || _        |r|| _        n# || _        |r|| _        w xY w|	S )	zReturn specified pages as list of TiffPages or TiffFrames.

        The first item is a TiffPage, and is used as a keyframe for
        following TiffFrames.

        NFr   rH  rT  z0key must be an integer, slice, or iterable, not Tc                *    g | ]} |           S )r  r   )r   r  getitem	validhashs     r   r:  z&TiffPages._getlist.<locals>.<listcomp>+  s(    AAAWWQ333AAAr   )r>  rH  r-  r  r   r   r   r  r`  r  ra  r  r+  rq  r  r7  rP   r   r~  r  r  r  r  r[  )rp  rn   rH  r  r   r  r  r	  rb  r"  rT  rU  s             @@r   r_  zTiffPages._getlist*  s<    -^
;uSYY''((CCc5=122 	c((C"DNaxx
|#,~!+++++U## 
	 [[33NE4= Su%5%5DK8H8H%H%H

2uckk#dk*:*:;;<==CCX&& 	s))CCN499NN  
 ~)))>$s))$$$+3:DN''	 	"!DN	,AAAAASAAAELLDN+++ &DN ,!+ &DN ,!+++++s   B 	B *H H,c              T   | j         J t          |          }| j        }|dk     r|t          |           z  }n=| j        r6|t          |          k    r#t          d| dt          |           d          |rt          n| j        }|t          |          k     r||         }| j        rB|s@t          |t          t          j        f          s|r||j        k    rt          d          |S n5t          |t          |f          r|r||j        k    rt          d          |S | j        |n
| j        |fz   }|                     |            || j         || j                  }t          |t          t"          f          sJ |r||j        k    rt          d          | j        s|r|||<   |S )z)Return specified page from cache or file.Nr   zindex z out of range(r  zpage hash mismatchrE  )rO  r   r  r   r+  r  r   r*  r-  r   r  r`  r  rg  r  r7  r  r   )	rp  rn   r  r  rX  r"  r'  r  r  s	            r   r>  zTiffPages._getitem
+  s    {&&&#hh773t99CC] 	Hsc%jj00FcFFUFFFGGG%9884>U:D{ 6 !$em(<==   AH	$9$9*+?@@@K  D8X"677  = DI--&';<<< ;&CCDK3&,@ 	 	

3x9t~NNN$9 566666 	5DI--3444; 	% 	E#Jr   c                   d S r   r   rp  rn   s     r   __getitem__zTiffPages.__getitem__;+  s    @Cr   slice | Iterable[int]c                   d S r   r   rX  s     r   rY  zTiffPages.__getitem__>+  s	     &)Sr   int | slice | Iterable[int]1TiffPage | TiffFrame | list[TiffPage | TiffFrame]c               |   | j         }| j        t          |t          t          j        f          r;t          |          }|dk    rt          t          ||                   S  |          S t          |t                    r|	                    d          \  }}}| j
        s6t          ||          t          |          k    r|                     d           fdt          |	                    t          |                     D             S t          |t                    rfd|D             S t!          d          )Nr   rH  rT  c                &    g | ]} |          S r   r   )r   r  rT  s     r   r:  z)TiffPages.__getitem__.<locals>.<listcomp>S+  s!    HHH1GGAJJHHHr   c                &    g | ]} |          S r   r   )r   r   rT  s     r   r:  z)TiffPages.__getitem__.<locals>.<listcomp>V+  s!    ,,,1GGAJJ,,,r   *key must be an integer, slice, or iterable)r  r>  r   r   r  r`  r\   r   ra  r  r+  rq  r   r7  r  rP   r   )rp  rn   r"  r  r  r	  rT  s         @r   rY  zTiffPages.__getitem__C+  s+    -cC/00 	 c((CaxxHeCj11173<<c5!! 	I [[33NE4= Su%5%5E

%B%B

2HHHHs{{3u::/F/F(GHHHHc8$$ 	-,,,,,,,,DEEEr   Iterator[TiffPage | TiffFrame]c              #     K   d}	 	 |                      |          V  |dz  }n# t          $ r Y nw xY w/| j        r	d| _        d S d S )Nr   TrW   )r>  r  r-  r,  )rp  r  s     r   __iter__zTiffPages.__iter__Z+  s~      	mmA&&&&&Q   		 ; 	 DLLL	  	 s   $ 
11c                2    t          | j                  dk    S )z'Return True if file contains any pages.r   )r   r  r  s    r   __bool__zTiffPages.__bool__e+  s    4;!##r   c                b    | j         s|                     d           t          | j                  S )zReturn number of pages in file.rT  )r+  r7  r   r  r  s    r   r  zTiffPages.__len__i+  s+    } 	JJrNNN4;r   r   c                    d| j          dS )Nz<tifffile.TiffPages @rj   )r.  r  s    r   r!  zTiffPages.__repr__o+  s    6t|6666r   )r0  r1  r  r2  r   r  )r   r)  r  r  rU  r   r   r  r&  )r  r   r   r  r   r   r   )r  rA  rn   r   r  r   r  r   rX  r   r   r  T)rb  rC  r   r  r"  )rN  r   r   r  )r  r   r   r   )NTT)rH  r   r  r   rn   r   r   rQ  )
rn   r   r  r   r  r   rX  r   r   r  )rn   r   r   r  )rn   rZ  r   rQ  )rn   r\  r   r]  )r   rb  r  r&  )r*  r+  r,  r-  rO  r'  rs  r(  r"  r  r  r  r  rH  rb  r  r`  rY  r  rF  r  r7  r_  r>  r^   rY  rd  rf  r  r!  r   r   r   r	   r	   )  s         " #F""""-,,,,////NNNMMMLLLLLL"""" -1I  I  I  I  I  I V    X . . . X.    X    X \   \ + + + X+ : : : :    X!, !, !, !,F $ $ $ X$ 04	% % % % % % %N    66 6 6 6p    $ZG ZG ZG ZG| 377 7 7 7 7| / / / / / /b CCC XC) ) ) X)F F F F.	  	  	  	 $ $ $ $       7 7 7 7 7 7r   r	   c                     e Zd ZU dZdZded<   	 ded<   	 ded<   	 ded<   	 ded	<   	 ded
<   	 ded<   d3dZeddddd4d            Ze	d5d            Z
e	d6d            Zed7d            Zej        d8d            Zed9d!            Zed9d"            Zed9d#            Zed:d$            Zd;d&Zddd'd<d*Zd=d+Zd9d,Zd9d-Zd>d?d2ZdS )@r   a  TIFF tag structure.

    TiffTag instances are not thread-safe. All attributes are read-only.

    Parameters:
        parent:
            TIFF file tag belongs to.
        offset:
            Position of tag structure in file.
        code:
            Decimal code of tag.
        dtype:
            Data type of tag value item.
        count:
            Number of items in tag value.
        valueoffset:
            Position of tag value in file.

    )rO  rv   r  r~   r  _valuer  TiffFile | TiffWriterrO  r   rv   r  r~   r  r  rb   rm  DATATYPE | intrU  r   r  c                  || _         t          |          | _        t          |          | _        t          |          | _        || _        || _        	 t          |          | _        d S # t          $ r t          |          | _        Y d S w xY wr   )
rO  r   rv   r  r  rm  r  r   r~   r   )rp  rO  rv   r  r~   r  rU  r  s           r   rs  zTiffTag.__init__+  s     &kkII	ZZ
&	$!%DJJJ 	$ 	$ 	$UDJJJJ	$s   A) )B
BNT)rv   rI  r  r   r   rI  r   r  r   c         
        |j         }|j        }|G||                                }n|                    |           |                    |j                  }n||                                }||j        z   |j        z
  }t          j        |j	        |j
        dd         z   |          \  }}	}
}	 t          j        |	         }nf# t          $ rY}d| d| d|	}|rt          |          |t                                          |            | ||||	|
dd          cY d}~S d}~ww xY w|
t          j        |          z  }||j        k    s|t          j        v rt          j        |j        |          d         }|r/|t          j        v r!t*                              ||||	|
|          }n|dk     s||z   |j        k    r@d| d| d| }|rt          |          t                                          |           d}n|t          j        v r t*                              ||||	|
|          }nd}n|	d	v r|d|         }n{|j        r.|
dk    r(|	d
v r$|dd         dk    rt          j        d|          }nF|j         |
t7          |d                   z   |d          }t          j        ||d|                   }t*                              |||	|          } | ||||	|
||          S )a_  Return TiffTag instance from file.

        Parameters:
            parent:
                TiffFile instance tag is read from.
            offset:
                Position of tag structure in file.
                The default is the position of the file handle.
            header:
                Tag structure as bytes.
                The default is read from the file.
            validate:
                Raise TiffFileError if data type or value offset are invalid.

        Raises:
            TiffFileError:
                Data type or value offset are invalid and `validate` is *True*.

        NrW   <tifffile.TiffTag r  > invalid data type r   rY  > invalid value offset    rW   r  r  >   r  r<  r  r  s       <Q)r/  r  r]  ra  r?  rK  r  rj  r@  r  r  r   r  r  r   r=   rB  r  TAG_READERSrl  TAG_LOADr   _read_valuerw   rs  r3  r   r   _process_value)clsrO  rv   rI  r  r/  rq  r  r  r~   r  rU  r   r  r  	valuesizer  s                    r   r  zTiffTag.fromfile+  s   : {>~WWT\**FF^WWYYFt|+d.EE$*MOdoabb116%
 %
!eUE
	D+E2KK 	D 	D 	D/T / /V / /%*/ /   2#C((c1HHNN33vvtUE4CCCCCCCC	D FOK888	///t''' -(95AA!DK DDM11++FD%  qK)$;bg$E$E: : : : :,7: :   -',,,  %%%&&++FD%  i*9*%EEL	:

##abb	000 M$..EE > $3{1~...$q>$ $ 
 M#uZiZ'899E&&udE6BBs664ukJJJs   0C 
D&AD!D&!D&c          
        	 t           j        |         }n+# t          $ r}t          d| d| d|          |d}~ww xY w| j        }| j        j        }	| j        j        }
|t          j	        |          z  }|dk     s||z   |j
        k    rt          d| d| d|           |                    |           |t           j        v rft           j        |         }	  |||	|||
          }|S # t          $ r5}t                                          d| d| d|d           Y d}~nd}~ww xY w|d	v rQ|                    |          }t#          |          |k    r(t                                          d| d| d
           nr|t           j        vr|dk    rt'          ||	|||
          }nJt          j        |	 |t+          |d                   z   |d          |                    |                    }|S )zRead tag value from file.rr  r  rs  NrY  rt  	> raised r9  ru  z> could not read all valuesr  r   rW   )r   r  r  r   r  r/  r   rJ  rj  r  rw   ra  rw  r  r=   rs  r?  r   	TAG_TUPLE
read_numpyr@  r   )rO  rv   r  r~   r  r  r   r  rq  r   rJ  r|  readfuncrU  s                 r   ry  zTiffTag._read_value',  s   	+E2KK 	 	 	/T / /V / /%*/ /  	 K)	[+
FOK888	??kI5??6T 6 6V 6 6(36 6   	4###'-H YujII       NNNNN#NNN        IGGI&&E5zzY&&  0 0 0 0 0 0   ''EDLLr9eUJGGEEMKec+a.&9&99K;q>KK	"" E s(    
=8=C) )
D(3+D##D(c               b   | <|dk    s6|dk    s0|t           j        v s"t          | t          t          t
          f          s| S |dk    r|                     d          } 	 |                     d                                          } n{# t          $ rn 	 |                     d                                          } nB# t          $ r5}t                                          d| d	| d
|d           Y d}~nd}~ww xY wY nw xY w| S |t           j        v rut           j        |         	 t          fd| D                       } nF# t          $ r9}|dvr+t                                          d| d	| d|d           Y d}~nd}~ww xY wt          |           dk    r|t           j        vr| d         } | S )zProcess tag value.NrW   r  r  r1  utf-8cp1252rr  r  z*> coercing invalid ASCII to bytes, due to r9  c              3  .   K   | ]} |          V  d S r   r   r   r  r  s     r   r   z)TiffTag._process_value.<locals>.<genexpr>,  s+      22qaadd222222r      r  r  r~  r   )r   rw  r   r  r   r  rstripr  r=  UnicodeDecodeErrorr=   rs  TAG_ENUMr   r   r  )rU  r  r~   rv   r  r  s        @r   rz  zTiffTag._process_valueg,  s?    Mzzzzt'''eeS%%899 ( LA:: LL))E	W--3355%   !LL2288::EE)   HH$$PT P PV P PCFOP P        L4=  d#A2222E22222   z))HH$$/T / /V / /"%./ /   u::??t4>99!HEsT   'B 
C>'B98C>9
C8+C3.C>3C88C>=C>$E   
F
/E>>Fc           	     .   | j         | j        j        }|j        5  |j        }|r1t          j        | dt                     |                                 	 t          
                    | j        | j        | j        | j        | j        | j                  }|r|                                 n# |r|                                 w w xY wddd           n# 1 swxY w Y   t                              || j        | j        | j                  | _         | j         S )z2Value of tag, delay-loaded from file if necessary.Nz reading value from closed file)rm  rO  r  r  r  rm  rn  ro  r  r   ry  rv   r  r~   r  r  r  rz  )rp  rq  r  rU  s       r   rU  zTiffTag.value,  s_    ;
 'B # #  MBBBK   GGIII##//	

( E  #


  #



#'# # # # # # # # # # # # # # #* "00	
	 DK {s)   ;C=B,C,CCCCc                   || _         d S r   )rm  r  s     r   rU  zTiffTag.value,  s    r   r   c                P    	 | j         j        S # t          $ r d| j          cY S w xY w)zName of data type of tag value.TYPE)r~   ru   r?  r  s    r   
dtype_namezTiffTag.dtype_name,  sB    	':?" 	' 	' 	'&$*&&&&&	's    %%c                p    t           j                            | j        t	          | j                            S )z0Name of tag from :py:attr:`_TIFF.TAGS` registry.)r   r  rY  r  r   r  s    r   ru   zTiffTag.name,  s$     y}}TYDI777r   c                0    t           j        | j                 S )z"Data type as `struct.pack` format.)r   r  r~   r  s    r   r  zTiffTag.dataformat,  s      ,,r   c                d    | j         t          j        t          j        | j                           z  S )z%Number of bytes of tag value in file.)r  rj  r  r   r  r~   r  s    r   valuebytecountzTiffTag.valuebytecount,  s%     zFOD,=dj,IJJJJr   TagTuplec                   t          | j        t                    r	| j        }n| j        j        }t
          j        | j                 }| j        t          |d                   z  }|j
         | |d          }	 | j        dk    rHt          j        || j                            d                    }t          |          |k    rt          nR|dk    r5t          | j        t                     st          j        || j                  }nt          j        |g| j        R  }n# t"          $ r}|j        r|dk    rt          d          || j        j        }|                                }|                    | j                   |                    t          j        |                    }|                    |           Y d}~nd}~ww xY w| j        t          | j                  | j        |dfS )zvReturn tag code, dtype, count, and encoded value.

        The encoded value is read from file if necessary.

        r   rW   r  r  z-cannot pack 64-bit NDPI value to 32-bit dtypeNT)r   rU  r  rO  r/  r   r  r~   r  r   r   rj  rk  rm  r   r   r  r  r3  r  r]  ra  r  r?  r  r  )	rp  rU  r/  r  r  r  r  rq  rr  s	            r   astuplezTiffTag.astuple,  s    dj%(( 	JEE;#D*4:6JJZ]!3!33E^;U;JqM;;C:??"KTZ->->w-G-GHHE5zzU**(( +aZZ
4:u(E(EZ"KTZ88EE"K9dj999E 	 	 	< EQJJ$G  [+ggii())) 4 455	 y#dj//4:udBBs   8B%D 
G(BG  G)r~   r  DATATYPE | int | str | Noner  c         
     .   | j         dk     s| j        dk     rt          d| j          d          t          |d          rt	          d          | j        j        }| j        j        }|j        rd| j	        dk    rM| j
        dv rDt          | j        t                    r| j        d         }n| j        }|d	k    rt          d
          t          j        }|d}|| j
        }nt          |t                     r`t#          |          dk    r|d         dv r
|dd         }	 t          j        |         }n:# t&          $ r}t          d|          |d}~ww xY wt)          t*          |          }d}	 t          j        |         }	n%# t&          $ r}t          d|          |d}~ww xY w|dk    rt          |t                     r9	 |                    d          }nF# t0          $ r}t          d          |d}~ww xY wt          |t2                    st          d          t#          |          dk    s|dd         dk    r|dz  }t#          |          }
|f}nt          |t2                    rMt5          j        |	          }t#          |          |z  rt          d          t#          |          |z  }
|}|f}nI	 t#          |          }
n# t          $ r |f}d}
Y nw xY w|dv r|
dk     s|
dz  rt          d          |
dz  }
|9t5          j        |j         |
t=          |	d                   z   |	d          g|R  }t#          |          }| j	        t5          j        t          j        | j
                           z  }| j        }|                                }	 || j
        k    rM|                     | j         dz              |!                    t5          j        |j        dz   |                     ||j"        k    r:||j"        k    rM|                     | j         dz              |!                    t5          j        |j#        |
|                     np|                     dtH          j%                   |                                }|dz  r|!                    d           |dz  }|                     | j         dz              |!                    t5          j        |j#        |
t5          j        |j&        |                               |                     |           |!                    |           n||j"        k    r| j         dz   t5          j        |j#        dd                   z   }|                     | j         dz              |!                    t5          j        |j#        |
|                     |r2|                     | j                   |!                    d|z             n||k    s| j        |z   |j'        k    r|                     | j         dz              |!                    t5          j        |j#        dd         |
                     |                     | j                   |!                    |           |r$||z
  dk    r|!                    d||z
  z             n|                     dtH          j%                   |                                }|dz  r|!                    d           |dz  }|                     | j         dz              |!                    t5          j        |j#        |
t5          j        |j&        |                               |                     |           |!                    |           |r2|                     | j                   |!                    d|z             |                     |           n# |                     |           w xY wtQ          | j        | j         | j)        ||
||          S )a|  Write new tag value to file and return new TiffTag instance.

        Warning: changing tag values in TIFF files might result in corrupted
        files or have unexpected side effects.

        The packed value is appended to the file if it is longer than the
        old value. The file position is left where it was.

        Overwriting tag values in NDPI files > 4 GB is only supported if
        single integer values and new offsets do not exceed the 32-bit range.

        Parameters:
            value:
                New tag value to write.
                Must be compatible with the `struct.pack` formats corresponding
                to the tag's data type.
            dtype:
                New tag data type. By default, the data type is not changed.
            erase:
                Overwrite previous tag values in file with zeros.

        Raises:
            struct.error:
                Value is not compatible with dtype or new offset exceeds
                TIFF size limit.
            ValueError:
                Invalid value or dtype, or old integer value in NDPI files
                exceeds 32-bit range.

        rY  zcannot rewrite tag at offset z < 8r  zGTiffTag.overwrite got an unexpected TiffFile instance as first argumentrW   >   r  r  r   r  zcannot patch NDPI > 4 GB filesNr   z<>|=zunknown data type r  r  r  rT  r1  r  r  zinvalid RATIONAL valuerZ  r  )*rv   r  r   r;  r   rO  r  r/  r3  r  r~   r   rU  r  r   rf  r   r   r  r  r7   r   r  rm  r  r  rj  r  rk  r   r   r]  ra  r  r  r  r  ri  rl  rw   r   r  )rp  rU  r~   r  rq  r/  r  r  packedvaluer  r  dtsizenewsizeoldsizer  rr  s                   r   r  zTiffTag.overwrite,  sP   L ;??d.22NT[NNNOOO5,'' 	 $  
 [#{< 		#zQ4:#8#8dj%00 #
1AA
Az>>$%EFFF?D=E=JEEs## 	-5zzA~~%(f"4"4abb	J(/ J J J !?e!?!?@@cIJ He,,E$(	F*51JJ 	F 	F 	F;%;;<<#E	F A::%%% 	E!LL11EE)   $:   u-- E !CDDD5zzQ%*"7"7 JJEHEEu%% 	_Z00F5zzF" ? !=>>>JJ&(EKHEEE

    199	9$%=>>>! +>N53z!}+=+=#=Nz!}NN  K k""*vt/@/LMMM&ggiiK	
""a(((T^c%95AABBB$111d555GGDK!O,,,HHV[%MMNNNN GGAr{+++"$''))K"Q ))))#q(GGDK!O,,,HH O!"K(9;GG    GGK(((HH[))))D333 K!Ofodobqb6I&J&JJ  a(((T_e[IIJJJ 0GGD,---HHWw.///G##t'7''ARW'L'La(((T_RaR%8%@@AAA()))%%% <Ww.22HHW'(9:;;; 2;''' ggii? %HHW%%%1$Ka(((KD$5{CC    $$$%%% 0GGD,---HHWw./// GGCLLLLBGGCLLLLKKI
 
 	
sg   D/ /
E9EE,E? ?
F!	FF! G 
G5 G00G58K KKP,_ _0c                   | j         dk    s| j        dk    rdS t                                          | d           t	          j        dg| j        R  }t	          j        d|          d         | _        | j	        j
                            | j                   t	          j        d| j	        j
                            d                    | _        dS )	zCorrect LSM bitspersample tag.

        Old LSM writers may use a separate region for two 16-bit values,
        although they fit into the tag value element of the tag.

        r  r  Nz! correcting LSM bitspersample tag<HH<Ir   r  )r  r  r=   rs  rj  rk  rU  r@  r  rO  r  ra  r?  r  s     r   r"  zTiffTag._fix_lsm_bitspersample-  s     9tzQFDEEEFFFE/DJ///!=u55a8##D$4555]5$+*@*E*Ea*H*HII


r   c                    d                     t          j                            | j        g                     }|rd|z   }d| j         | d| j         dS )NrR  r!  rr  r  rj   )r   r   r  getallr  rv   )rp  ru   s     r   r!  zTiffTag.__repr__-  sZ    xx	((B7788 	:DEDIEtEEt{EEEEr   c                *    |                                  S r   r3  r  s    r   r5  zTiffTag.__str__-  r6  r   r   r7  r8  r^  c                V   |dk    rdnd|z  }| j         }| j        dk    r|d| j         dz  }d                    t          j                            | j        g                     }|r| j         d| d| j         }n| j         d| j         }d	| d| d| j         d}|d
|         }	 | j	        }	 | j        dk    rt          |          }n&t          t          d |D                                 }n# t          $ rk t          |t          t          f          sn9|dk    r|d
d         }n(t!          |          dk    r|d
d         |dd
         z   }t          |||          }Y nw xY w# t"          $ r d}Y nw xY w|dk    r|dz  }||d
|         z  }|d
|         }n|d|z   z  }|S )z3Return string containing information about TiffTag.r   rW   rY  r  ]rR  r!  r  zTiffTag Nc              3  4   K   | ]}t          |          V  d S r   )r8   r  s     r   r   zTiffTag._str.<locals>.<genexpr>.  s(      )D)D'!**)D)D)D)D)D)Dr   r  r  r  i rH  	CORRUPTEDz= rA  )r  r  r   r   r  r  r  rv   r  rU  r8   rC   r  r  r   rA  r   r   )rp  r8  r^  r  r~   ru   linerU  s           r   r4  zTiffTag._str-  s,   kkq6z:>>&&&&&Exx	((B7788 	1i77$77$+77DDi004;00D=$====$*:===FUF|	CJEC:??#ENNEE#E)D)De)D)D)D$D$DEEE 	C 	C 	C!%%77 q[[!$3$KEEZZ$&&eteuUVV}4   U6BBB	C  	  	  	 EEE	 $ Q;;DLDE&5&M!D<DDD5L Ds&   *E, 2AC4 4A2E)(E),E;:E;)rO  rn  rv   r   r  r   r~   ro  r  r   rU  rb   r  r   r   r  )
rO  r   rv   r   rI  r   r  r   r   r   )rO  rn  rv   r   r  r   r~   r   r  r   r  r   r   rb   )
rU  rb   r  r   r~   r   rv   r   r   rb   r  )rU  rb   r   r  r&  r  )r   r  )rU  rb   r~   r  r  r   r   r   r"  r  r  )r*  r+  r,  r-  r  r'  rs  classmethodr  r)  ry  rz  r(  rU  r  r  ru   r  r  r  r  r"  r!  r5  r4  r   r   r   r   r   s+  s         (I "!!!#KKK,IIIJJJ1JJJ'(KKK$ $ $ $,  "#gK gK gK gK gK [gKR = = = \=~ + + + \+Z # # # X#J \   \ ' ' ' X' 8 8 8 X8 - - - X- K K K XK!C !C !C !CP .2W
 W
 W
 W
 W
 W
rJ J J J F F F F   ' ' ' ' ' ' 'r   r   c                      e Zd ZU dZdZded<   ded<   d3d	Zd4dZd5dZd6dZ	d7dZ
	 	 d8d9dZ	 	 d8d:dZ	 d;d<dZd=dZd>d"Zd?d#Zd@d'ZdAd)ZdBd*ZdCd,ZdCd-ZdDdEd2ZdS )Fr   aS  Multidict-like interface to TiffTag instances in TiffPage.

    Differences to a regular dict:

    - values are instances of :py:class:`TiffTag`.
    - keys are :py:attr:`TiffTag.code` (int).
    - multiple values can be stored per key.
    - can be indexed by :py:attr:`TiffTag.name` (`str`), slower than by key.
    - `iter()` returns values instead of keys.
    - `values()` and `items()` contain all values sorted by offset.
    - `len()` returns number of all values.
    - `get()` takes optional index argument.
    - some functions are not implemented, such as, `update` and `pop`.

    _dict_listzdict[int, TiffTag]r  zlist[dict[int, TiffTag]]r  r   r  c                .    i | _         | j         g| _        d S r   r  r  s    r   rs  zTiffTags.__init__,.  s    
j\


r   r9  r   c               x    |j         }| j        D ]}||vr|||<    dS | j                            ||i           dS zAdd tag.N)r  r  r   )rp  r9  r  r  s       r   r  zTiffTags.add0.  sZ    x 	+ 	+A1}}$  JtSk*****r   rF  c                N    t          | j                                                  S )zReturn codes of all tags.)rA  r  r  r  s    r   r  zTiffTags.keys:.  s    DJOO%%&&&r   list[TiffTag]c                H    d | j         D             }t          |d           S )z1Return all tags in order they are stored in file.c              3  H   K   | ]}|                                 D ]}|V  d S r   )rT  )r   r  r  s      r   r   z"TiffTags.values.<locals>.<genexpr>@.  s7      ::aqxxzz::!:::::::r   c                    | j         S r   r  )r  s    r   r  z!TiffTags.values.<locals>.<lambda>A.  s    !( r   r  r  r|  rp  r  s     r   rT  zTiffTags.values>.  s.    ::4::::d 2 23333r   r  c                H    d | j         D             }t          |d           S )z>Return all (code, tag) pairs in order tags are stored in file.c              3  H   K   | ]}|                                 D ]}|V  d S r   r:  r   r  r  s      r   r   z!TiffTags.items.<locals>.<genexpr>E.  s7      ::q		::1:::::::r   c                    | d         j         S NrW   r  r  s    r   r  z TiffTags.items.<locals>.<lambda>F.  s    1Q4; r   r  r  rp  r:  s     r   r:  zTiffTags.itemsC.  s.    ::DJ:::e!6!67777r   Nr  rb   r  r   rn   r  c               n    |                      |d|          }||S 	 |j        S # t          $ r |cY S w xY w)a  Return value of tag by code or name if exists, else default.

        Parameters:
            key:
                Code or name of tag to return.
            default:
                Another value to return if specified tag is corrupted or
                not found.
            index:
                Specifies tag in case of multiple tags with identical code.
                The default is the first tag.

        N)r  r  )rY  rU  r   )rp  rn   r  r  r9  s        r   r  zTiffTags.valueofH.  sV    ( hhsDh66;N	9 	 	 	NNN	s   % 44rA  c                  |B|| j         v r | j         t          t          |                   S t          |t                    s|S d}	 | j        |         }n# t          $ r |cY S w xY w||v r|t          t          |                   S t          |t                    s|S |                                D ]}|j        |k    r|c S |S )a  Return tag by code or name if exists, else default.

        Parameters:
            key:
                Code or name of tag to return.
            default:
                Another tag to return if specified tag is corrupted or
                not found.
            index:
                Specifies tag in case of multiple tags with identical code.
                The default is the first tag.

        Nr   )	r  r\   r   r   r   r  r  rT  ru   )rp  rn   r  r  r  r9  s         r   rY  zTiffTags.getd.  s    ( =dj  z$sC..11c3'' E	:e$DD 	 	 	NNN	$;;S#''#s## 	N;;== 	 	Cx3


 s   A A#"A#list[TiffTag] | Nonec               P   g }| j         D ]5}||v r/|                    |t          t          |                              5 |r|S t	          |t
                    s|S | j         D ]?}|                                D ]$}|j        |k    r|                    |            n%|s n@|r|n|S )zReturn list of all tags by code or name if exists, else default.

        Parameters:
            key:
                Code or name of tags to return.
            default:
                Value to return if no tags are found.

        )r  r   r\   r   r   r   rT  ru   )rp  rn   r  r  r  r9  s         r   r  zTiffTags.getall.  s     !#J 	 	Dd{{d4S>>23333 	M#s## 	NJ 	 	D{{}}  8s??MM#&&&E #  ,vvW,r   c                  || j         v r | j         t          t          |                   S t          |t                    st          |          | j                                         D ]}|j        |k    r|c S t          |          )z>Return first tag by code or name. Raise KeyError if not found.)r  r\   r   r   r   r  rT  ru   )rp  rn   r9  s      r   rY  zTiffTags.__getitem__.  s    $*:d3nn--#s## 	 3--:$$&& 	 	Cx3


 smmr   r  r   c               J    |j         |k    sJ |                     |           dS r  )r  r  )rp  r  r9  s      r   __setitem__zTiffTags.__setitem__.  s(    x4r   c               >   d}| j         D ]}||v rd}|t          t          |          =  |rdS t          |t                    st          |          | j         D ]2}|                                D ]}|j        |k    r||j        = d} n n3|st          |          dS )z Delete all tags by code or name.FTN)	r  r\   r   r   r   r  rT  ru   r  )rp  rn   foundr  r9  s        r   __delitem__zTiffTags.__delitem__.  s    J 	 	Dd{{c3(( 	F#s## 	 3--J 	 	D{{}}  8s??SX EE #
    	 3--r   r(  objectr   c                   || j         v rdS t          |t                    sdS | j                                         D ]}|j        |k    r dS dS )zReturn if tag is in map.TF)r  r   r   rT  ru   )rp  r(  r9  s      r   __contains__zTiffTags.__contains__.  sf    4:4$$$ 	5:$$&& 	 	Cx4tt  ur   Iterator[TiffTag]c                D    t          |                                           S )zReturn iterator over all tags.)r-  rT  r  s    r   rd  zTiffTags.__iter__.  s    DKKMM"""r   c                B    d}| j         D ]}|t          |          z  }|S )zReturn number of tags.r   r  r   rp  rw   r  s      r   r  zTiffTags.__len__.  s.     	 	ACFFNDDr   r   c                *    dt          |           ddS )Nz<tifffile.TiffTags @0x016Xrj   idr  s    r   r!  zTiffTags.__repr__.  s    8488888r   c                *    |                                  S r   r3  r  s    r   r5  zTiffTags.__str__.  r6  r   r   r7  r8  r^  c           
        g }g }g }| D ]E}|                     |dz             }|                    |d|                                                    |dk    rt          |          |k    r	 |j        }n# t
          $ r Y yw xY w|j        dv rO|dk     r|dd         }n(t          |          dk    r|dd         |d	d         z   }t          |||d
z            }nt          |||dz            }|j        dk    r1|                    |j	         d|j
         d|j         d|            &|                    |j	         d|            G|                    d                    |                     |dk    r?|r=|                    d           |                    d                    |                     d                    |          S )z.Return string with information about TiffTags.rW   r'  Nr   >   r  r  r  r  r  r     i r   rH  rY  r!  r  z]
rA  rI  )r4  r   r=  r   rU  r  r  rC   r  ru   r  r   )rp  r8  r^  r  tlinesvlinesr9  rU  s           r   r4  zTiffTags._str.  s    	: 	:CHH519H--EMM%---//000zzc%jj500IEE    H 8333zz %dsdUd** %dsdeDEEl :#EvzJJJEE#EvzJJJE9q==MM8LLcnLLsyLLULL    MMSX"8"8"8"8999DIIf%%&&&A::&:KKKKF++,,,yys   .A66
BBr"  )r9  r   r   r  )r   rF  )r   r  )r   r  r  )r  rb   r  r   rn   r  r   rb   )r  rA  r  r   rn   r  r   rA  r   )r  rb   rn   r  r   r  )rn   r  r   r   )r  r   r9  r   r   r  rn   r  r   r  )r(  r  r   r   )r   r  r  r&  r  r  )r*  r+  r,  r-  r  r'  rs  r  r  rT  r:  r  rY  r  rY  r  r  r  rd  r  r!  r5  r4  r   r   r   r   r   .  s           #I####" " " "+ + + +' ' ' '4 4 4 4
8 8 8 8      @ #' % % % % %V 	 -  -  -  -  -D	 	 	 	   
   2	 	 	 	# # # #   9 9 9 9                r   r   c                  \   e Zd ZU dZdZded<   ded<   d3dZd3dZd4dZd5dZ	e
d6d            Ze
d7d            Ze
d8d            Z	 d9d:dZe
d;d             Ze
d<d"            Ze
d=d$            Z	 d9d>d&Ze
d?d'            Ze
d@d(            ZdAd)ZdBd*ZdCd-ZdDd/ZdEd0ZdFd1ZdFd2ZdS )Gr   a4  Registry of TIFF tag codes and names.

    Map tag codes and names to names and codes respectively.
    One tag code may be registered with several names, for example, 34853 is
    used for GPSTag or OlympusSIS2.
    Different tag codes may be registered with the same name, for example,
    37387 and 41483 are both named FlashEnergy.

    Parameters:
        arg: Mapping of codes to names.

    Examples:
        >>> tags = TiffTagRegistry([(34853, 'GPSTag'), (34853, 'OlympusSIS2')])
        >>> tags.add(37387, 'FlashEnergy')
        >>> tags.add(41483, 'FlashEnergy')
        >>> tags['GPSTag']
        34853
        >>> tags[34853]
        'GPSTag'
        >>> tags.getall(34853)
        ['GPSTag', 'OlympusSIS2']
        >>> tags.getall('FlashEnergy')
        [37387, 41483]
        >>> len(tags)
        4

    r  zdict[int | str, str | int]r  z list[dict[int | str, str | int]]r  r0  <TiffTagRegistry | dict[int, str] | Sequence[tuple[int, str]]r   r  c               X    i | _         | j         g| _        |                     |           d S r   )r  r  r  )rp  r0  s     r   rs  zTiffTagRegistry.__init__8/  s.    
 
j\
Cr   c                  t          |t                    r!| j                            |j                   dS t          |t                    r!t          |                                          }|D ]\  }}|                     ||           dS )zuAdd mapping of codes to names to registry.

        Parameters:
            arg: Mapping of codes to names.

        N)r   r   r  rQ  dictrA  r:  r  )rp  r0  r  ru   s       r   r  zTiffTagRegistry.updateA/  s     c?++ 	Jci(((Fc4   	$syy{{##C 	! 	!JD$HHT4    	! 	!r   r  r   ru   r   c                   | j         D ]*}||v r||         |k    r dS ||vr||vr|||<   |||<    dS +| j                             ||||i           dS )zAdd code and name to registry.N)r  r   )rp  r  ru   r  s       r   r  zTiffTagRegistry.addT/  s     	8 	8AqyyQtW__1}}Q$$JtT4677777r   list[tuple[int, str]]c                H    d | j         D             }t          |d           S )z*Return all registry items as (code, name).c              3  ~   K   | ]8}|                                 D ]!}t          |d          t                    |V  "9dS r4  )r:  r   r   r  s      r   r   z(TiffTagRegistry.items.<locals>.<genexpr>b/  se       
 
17799
 
&'
1Q48M8M

 
 
 
 
 
 
r   c                    | d         S r  r   r  s    r   r  z'TiffTagRegistry.items.<locals>.<lambda>e/  s
    1Q4 r   r  r  r  s     r   r:  zTiffTagRegistry.items`/  s9    
 
z
 
 
 e0000r   r  rn   r   c                   d S r   r   rp  rn   r  s      r   rY  zTiffTagRegistry.getg/      =@Sr   r   c                   d S r   r   r  s      r   rY  zTiffTagRegistry.getj/  r  r   c                   d S r   r   r  s      r   rY  zTiffTagRegistry.getm/  s    58Sr   Nr  str | int | Nonec               6    | j         D ]}||v r
||         c S |S )zReturn first code or name if exists, else default.

        Parameters:
            key: tag code or name to lookup.
            default: value to return if key is not found.

        r  )rp  rn   r  r  s       r   rY  zTiffTagRegistry.getp/  s5      	 	Aaxxv r   r)  c                   d S r   r   r  s      r   r  zTiffTagRegistry.getall/      FIcr   r>  c                   d S r   r   r  s      r   r  zTiffTagRegistry.getall/  r  r   	list[str]c                   d S r   r   r  s      r   r  zTiffTagRegistry.getall/  s    DGCr   list[str] | list[int] | Nonec               6    fd| j         D             }|r|n|S )zReturn list of all codes or names if exists, else default.

        Parameters:
            key: tag code or name to lookup.
            default: value to return if key is not found.

        c                (    g | ]}|v |         S r   r   )r   r  rn   s     r   r:  z*TiffTagRegistry.getall.<locals>.<listcomp>/  s"    999Qq!C&r   r  )rp  rn   r  r  s    `  r   r  zTiffTagRegistry.getall/  s/     :999$*999,vvW,r   c                   d S r   r   rX  s     r   rY  zTiffTagRegistry.__getitem__/      /2sr   c                   d S r   r   rX  s     r   rY  zTiffTagRegistry.__getitem__/  r  r   c               P    | j         D ]}||v r
||         c S t          |          )z7Return first code or name. Raise KeyError if not found.r  r  )rp  rn   r  s      r   rY  zTiffTagRegistry.__getitem__/  s:     	 	Aaxxv smmr   c               h    d}| j         D ]}||v rd}||         }||= ||= |st          |          dS )z Delete all tags of code or name.FTNr  )rp  rn   r  r  rU  s        r   r  zTiffTagRegistry.__delitem__/  s\     	 	Aaxx#cFeH 	 3--	  	 r   r(  r   c               (    | j         D ]	}||v r dS 
dS )z&Return if code or name is in registry.TFr  )rp  r(  r  s      r   r  zTiffTagRegistry.__contains__/  s-     	 	Aqyytt ur   Iterator[tuple[int, str]]c                D    t          |                                           S )z+Return iterator over all items in registry.)r-  r:  r  s    r   rd  zTiffTagRegistry.__iter__/  s    DJJLL!!!r   c                H    d}| j         D ]}|t          |          z  }|dz  S )z!Return number of registered tags.r   r  r  r  s      r   r  zTiffTagRegistry.__len__/  s3     	 	ACFFNDDqyr   c                *    dt          |           ddS )Nz<tifffile.TiffTagRegistry @0xr  rj   r  r  s    r   r!  zTiffTagRegistry.__repr__/  s    ?r$xx?????r   c                    d                     d                    d |                                 D                                 S )NzTiffTagRegistry(((
  {}
))z,
  c              3  .   K   | ]\  }}d | d|dV  dS )(r   r  Nr   r   r  ru   s      r   r   z*TiffTagRegistry.__str__.<locals>.<genexpr>/  s:      NN:4.T..T...NNNNNNr   )rL  r   r:  r  s    r   r5  zTiffTagRegistry.__str__/  s@    -44LLNNNNNNN
 
 	
r   )r0  r  r   r  )r  r   ru   r   r   r  )r   r  )r  r  rn   r   r   r   )r  r  rn   r   r   r   )r  r   rn   r   r   r   r   )r  r   rn   r  r   r  )r  r  rn   r   r   r)  )r  r  rn   r   r   r>  )r  r  rn   r   r   r  )r  r)  rn   r  r   r  rn   r   r   r   )rn   r   r   r   )rn   r  r   r  r  )r(  r  r   r   )r   r  r  r&  )r*  r+  r,  r-  r  r'  rs  r  r  r:  r^   rY  r  rY  r  r  rd  r  r!  r5  r   r   r   r   r   /  s         8 #I%%%%++++   ! ! ! !&
8 
8 
8 
81 1 1 1 @@@ X@@@@ X@888 X8 8<     III XIIII XIGGG XG >B- - - - - 222 X2222 X2   
  
  
  
    " " " "   @ @ @ @
 
 
 
 
 
r   r   c                     e Zd ZU dZded<   	 ded<   	 ded<   	 ded	<   	 d
ed<   	 d
ed<   	 ded<   	 ded<   	 ded<   	 ded<   ded<   ded<   d
ed<   d
ed<   ded<   ded<   ded<   ded<   	 	 	 dbddddddd d d!dd"
dcd5Z	 	 ddded7Zedfd8            Zedgd9            Z	edhd;            Z
didjd=Zdidkd>Z	 didld?Zdd@dmdEZdd@dndGZedodH            ZedpdI            ZedqdJ            ZedrdK            ZedsdM            ZedtdO            ZedrdP            ZedrdQ            ZedudR            ZdvdUZedwdW            ZedxdY            Zdyd\Zdzd^Zdrd_Zdgd`ZdgdaZ dS ){r
   ay  Sequence of TIFF pages making up multi-dimensional image.

    Many TIFF based formats, such as OME-TIFF, use series of TIFF pages to
    store chunks of larger, multi-dimensional images.
    The image shape and position of chunks in the multi-dimensional image is
    defined in format-specific metadata.
    All pages in a series must have the same :py:meth:`TiffPage.hash`,
    that is, the same shape, data type, and storage properties.
    Items of a series may be None (missing) or instances of
    :py:class:`TiffPage` or :py:class:`TiffFrame`, possibly belonging to
    different files.

    Parameters:
        pages:
            List of TiffPage, TiffFrame, or None.
            The file handles of TiffPages or TiffFrames may not be open.
        shape:
            Shape of image array in series.
        dtype:
            Data type of image array in series.
        axes:
            Character codes for dimensions in shape.
            Length must match shape.
        attr:
            Arbitrary metadata associated with series.
        index:
            Index of series in multi-series files.
        parent:
            TiffFile instance series belongs to.
        name:
            Name of series.
        kind:
            Nature of series, such as, 'ome' or 'imagej'.
        truncated:
            Series is truncated, for example, ImageJ hyperstack > 4 GB.
        multifile:
            Series contains pages from multiple files.
        squeeze:
            Remove length-1 dimensions (except X and Y) from shape and axes
            by default.
        transform:
            Function to transform image data after decoding.

    rl  r   r.  rO  r   rb  numpy.dtype[Any]r~   r   rW  ru   -Callable[[NDArray[Any]], NDArray[Any]] | Noner  r   is_multifileis_truncatedr  r  r   r  _squeeze_axes_axes_squeezedr  _shape_shape_squeezed_lenr  _attrNFT)
rw  r  r  rO  ru   rW  r  r  rq   r  r   r   r   r  r   r"  %Sequence[TiffPage | TiffFrame | None]rw  r   r  (Mapping[str, NDArray[Any] | None] | Noner  r   r  r  rq   r   r  c      
           d| _         d| _        d| _        d| _        |i nt	          |          | _        |rt          |          nd| _        t          |          | _	        | g| _
        t          | j	                  }	 t          d | j	        D                       }n.# t          $ r! t          d | j	        D                       }Y nw xY w||j        }||j        }||j        }t#          j        |          | _        |
r|
nd| _        |	r|	nd| _        || _        || _        t-          |          | _        t-          |          | _        ||| _        n | j	        r| j        j        | _        nd | _        |                     ||||           |sT|dk    rNt7          |j                  }|dk    r+t          t7          | j                  |z            | _        d S || _        d S || _        d S )Nr   r  r   c              3  b   K   | ]*}|&|j         |j         j        j        j        !|j         V  +d S r   )rb  rO  r  r  r\  s     r   r   z*TiffPageSeries.__init__.<locals>.<genexpr>?0  sR        =J*
)4; + 
 +***	 r   c              3  6   K   | ]}||j         |j         V  d S r   r  r\  s     r   r   z*TiffPageSeries.__init__.<locals>.<genexpr>G0  s<        =QZ%; 
%;%;%;%; r   rW   )r	  r	  r	  r	  r  r	  r   r  rA  r  r   r   r  rg  r   r  r~   r  rW  ru   r  rb  r   r	  r		  rO  r  rD   r	  )rp  r"  r   r~   r  rw  r  r  rO  ru   rW  r  r  rq   r  r  rb  r  s                     r   rs  zTiffPageSeries.__init__ 0  s   & !
 <RRT$ZZ
$)0c%jjjq5kkfT[!!	      HH  	 	 	      HHH	 =NE<=D=NE[''
 (DDb	 (DDb	"  OO OO DKK[ 	-.DKKDKUD&'::: 	Vq[[''A1uu
 3 3q 899			"			DIIIs   >B (CCr  c                   t          |          | _        t          |          | _        || _        t          ||          \  | _        | _        }dS )zSet shape, axes, and coords.N)r   r
	  r  r	  r	  r  r	  r	  )rp  r   r  r  rq   r	  s         r   r  zTiffPageSeries._set_dimensionsn0  sJ     WEll
7C48
 8
4d1111r   c                ,    | j         r| j        n| j        S )zShape of image array in series.r
	  r	  r	  r  s    r   r   zTiffPageSeries.shape~0  s     (,}Et##$+Er   c                ,    | j         r| j        n| j        S )z.Character codes for dimensions in image array.r
	  r	  r	  r  s    r   r  zTiffPageSeries.axes0  s     '+mCt""Cr   r  c                    t           )r  rM  r  s    r   r  zTiffPageSeries.coords0  s
     "!r   r   c                4    || j         }|r| j        n| j        S )zReturn default, squeezed, or expanded shape of series.

        Parameters:
            squeeze: Remove length-1 dimensions from shape.

        r	  rp  rq   s     r   rc  zTiffPageSeries.get_shape0  s%     ?mG'.?t##DK?r   c                4    || j         }|r| j        n| j        S )zReturn default, squeezed, or expanded axes of series.

        Parameters:
            squeeze: Remove length-1 dimensions from axes.

        r	  r	  s     r   r  zTiffPageSeries.get_axes0  s%     ?mG&-=t""4:=r   c                    t           )zReturn default, squeezed, or expanded coords of series.

        Parameters:
            squeeze: Remove length-1 dimensions from coords.

        rM  r	  s     r   
get_coordszTiffPageSeries.get_coords0  s
     "!r   )rp   rp   r   rb   r   c                   | j         t          d          | | j        |         j        di |S  | j         j        dd| i|}| j        |                     |          }|S )a'  Return images from series of pages as NumPy array.

        Parameters:
            level:
                Pyramid level to return.
                By default, the base layer is returned.
            **kwargs:
                Additional arguments passed to :py:meth:`TiffFile.asarray`.

        N	no parentro   r   )rO  r   r   r   r  )rp  rp   r   r  s       r   r   zTiffPageSeries.asarray0  s}     ;[)))-4;u%-77777$$;;D;F;;>%^^F++Fr   rj  c               P    | j         t          d          ddlm}  || fd|i|S )a3  Return image array from series of pages as Zarr store.

        Parameters:
            level:
                Pyramid level to return.
                By default, a multi-resolution store is returned.
            **kwargs:
                Additional arguments passed to :py:class:`ZarrTiffStore`.

        Nr"	  rW   r  rp   )rO  r   r   rj  )rp  rp   r   rj  s       r   rm   zTiffPageSeries.aszarr0  sI     ;[)))''''''}T999&999r   c                2   | j         sdS d}| j         D ]_}|t          |j                  dk    r dS |j        s dS |s|j        d         |j        z   }A||j        d         k    r dS ||j        z  }`| j         d         }|t          |j                  dk    rdS |j        d         }t          | j                   dk    r,t          |t                    r|j        s|j        s|j	        r|S ||t          | j                  | j        j        z  z   k    r|S dS )z(Offset to contiguous image data in file.Nr   rW   )r  r   r$  r  r  r   r   r  rl  rZ  rD   r   r~   r  )rp  rr  r  rv   s       r   r!  zTiffPageSeries.dataoffset0  sS    { 	4K 
	 
	D|s4#34499tt= tt &q)DK7d&q)))tt4;CC{1~<3t/00A554!!$!!4** " "#'> "59[ "
 M&74:..1DDDDDMtr   c                2    t          | j                  dk    S )z%Series contains multiple resolutions.rW   )r   r   r  s    r   r  zTiffPageSeries.is_pyramidal0  r  r   c                    | j         S )z*Arbitrary metadata associated with series.)r	  r  s    r   rw  zTiffPageSeries.attr1       zr   c                *    t          | j                  S )zNumber of array dimensions.r  r  s    r   r  zTiffPageSeries.ndim1  r  r   r  c                X    t          t          d | j        D                                 S )r  c              3  V   K   | ]$}t           j                            ||          V  %d S r   )r   r  rY  r   rv  s     r   r   z&TiffPageSeries.dims.<locals>.<genexpr>1  s4      KK24?..r266KKKKKKr   )r  unique_stringsr  r  s    r   r  zTiffPageSeries.dims1  s2     KKKKKKK
 
 	
r   r  c                P    t          t          | j        | j                            S )r  )r  r  r  r   r  s    r   r  zTiffPageSeries.sizes1  s      C	4:..///r   c                *    t          | j                  S )zNumber of elements in array.r  r  s    r   rw   zTiffPageSeries.size1  r  r   c                *    | j         | j        j        z  S )zNumber of bytes in array.)rw   r~   r  r  s    r   r  zTiffPageSeries.nbytes1  s     y4:...r   c                    | S r   r   r  s    r   r"  zTiffPageSeries.pages$1  s	     r   rn   rA  c               6   t          |          }|dk     r
|| j        z  }t          | j                  dk    rVd|cxk     r| j        k     rDn nA| j        d         }|J | j        J | j        j                            |j        |z             S | j        |         S )z3Return specified page of series from cache or file.r   rW   )r   r	  r   r  rO  r"  r>  r  )rp  rn   r  s      r   r>  zTiffPageSeries._getitem*1  s    #hh7749Ct{q  Q%8%8%8%8ty%8%8%8%8%8;q>D###;***;$--dj3.>???{3r   int | numpy.integer[Any]c                   d S r   r   rX  s     r   rY  zTiffPageSeries.__getitem__61  s	     '*cr   rZ  c                   d S r   r   rX  s     r   rY  zTiffPageSeries.__getitem__;1  s	     -0Cr   0int | numpy.integer[Any] | slice | Iterable[int]?TiffPage | TiffFrame | list[TiffPage | TiffFrame | None] | Nonec                   t          |t          t          j        f          r"                     t          |                    S t          |t
                    r- fdt          |                     j                   D             S t          |t                    r#t          |t                    s fd|D             S t          d          )zReturn specified page(s).c                :    g | ]}                     |          S r   r>  )r   r  rp  s     r   r:  z.TiffPageSeries.__getitem__.<locals>.<listcomp>G1  s%    MMMDMM!$$MMMr   c                :    g | ]}                     |          S r   r9	  )r   r   rp  s     r   r:  z.TiffPageSeries.__getitem__.<locals>.<listcomp>I1  s%    222DMM!$$222r   ra  )r   r   r  r`  r>  ra  r  r  r	  rP   r   r   rX  s   ` r   rY  zTiffPageSeries.__getitem__@1  s     cC/00 	+==S***c5!! 	NMMMMeS[[5K5K.LMMMMc8$$ 	3ZS-A-A 	32222c2222DEEEr   %Iterator[TiffPage | TiffFrame | None]c              #    K   t          | j                  | j        k    r| j        E d{V  dS | j        | j        d         J | j        j        }| j        d         j        }t          | j                  D ]}|||z            V  dS )z%Return iterator over pages in series.Nr   )r   r  r	  rO  r"  r  r  )rp  r"  r  r  s       r   rd  zTiffPageSeries.__iter__L1  s      t{ty(({""""""""";*t{1~/I/I/IK%EKN(E49%% ' 'EAI&&&&&' 'r   c                    | j         S )z!Return number of pages in series.)r	  r  s    r   r  zTiffPageSeries.__len__W1  s
    yr   c                (    d| j          d| j         dS )Nz<tifffile.TiffPageSeries r!  rj   )r  rW  r  s    r   r!  zTiffPageSeries.__repr__[1  s    E4;EEEEEEr   c                   d                     d | j        rt          | j        d          ndd                     d | j        D                       t	          | j                  | j        | j        | j        rt          | j
                   dndt          |            d| j        r
d	| j         ndfD                       }d
| j         d| S )Nr?  c              3     K   | ]}||V  	d S r   r   rD  s     r   r   z)TiffPageSeries.__str__.<locals>.<genexpr>_1  s>       
 
 

 
 
 
 
 
r      r  r  c              3  4   K   | ]}t          |          V  d S r   rC  r  s     r   r   z)TiffPageSeries.__str__.<locals>.<genexpr>c1  r   r   z Levelsr;  @zTiffPageSeries )r   ru   r   r   r   r~   r  rW  r  r   r   r!  r  )rp  r  s     r   r5  zTiffPageSeries.__str__^1  s    II 
 
 26B49("---4444444DJ		262CKC$$----t99$$$+/?B&T_&&&	
 
 
 
 
 433333r   NNN)r   r   r~   r   r  r   r"  r	  rw  r   r  r	  r  r   rO  r.  ru   r   rW  r   r  r   r  r   rq   r   r  r	  r   r  NT)
r   r  r  r   r  r	  rq   r   r   r  r  r&  r  r   )rq   r   r   r  )rq   r   r   r   )rq   r   r   r  )rp   r   r   rb   r   r   )rp   r   r   rb   r   rj  rj  r  r  r  r  r  )r   r
   )rn   r   r   rA  )rn   r2	  r   rA  )rn   rZ  r   r  )rn   r5	  r   r6	  )r   r;	  )!r*  r+  r,  r-  r'  rs  r  r(  r   r  r  rc  r  r 	  r   rm   rV   r!  r  rw  r  r  r  rw   r  r"  r>  r^   rY  rd  r  r!  r5  r   r   r   r
   r
   /  sb        + +Z !   D.AIIIIII-<<<<:4I---- KKKNNNJJJ$$$$III '+"&L '+;? "&CG#L L L L L Ld <@
 
 
 
 
  F F F XF D D D XD " " " X"	@ 	@ 	@ 	@ 	@	> 	> 	> 	> 	> &*	" 	" 	" 	" 	" &*     . &*: : : : : :(    _@ $ $ $ X$    _    X 
 
 
 X
 0 0 0 X0
 # # # _# / / / _/    X

  
  
  
  * * * X* 0 0 0 X0
F 
F 
F 
F	' 	' 	' 	'   F F F F4 4 4 4 4 4r   r
   c                  @   e Zd ZU dZded<   	 ded<   	 ded<   	 ded	<   	 d
ed<   	 ded<   ded<   dddddHdZdddddddddId/ZdJd1ZdKd2ZdLd3Z	e
dMd4            Ze
dNd6            ZdOd8ZdNd9ZedPd;            ZedQd=            ZdRd@ZdSdAZdTdEZdLdFZdLdGZdS )Ur/   a  Sequence of files containing compatible array data.

    Parameters:
        imread:
            Function to read image array from single file.
        files:
            Glob filename pattern or sequence of file names.
            If *None*, use '\*'.
            All files must contain array data of same shape and dtype.
            Binary streams are not supported.
        container:
            Name or open instance of ZIP file in which files are stored.
        sort:
            Function to sort file names if `files` is a pattern.
            The default is :py:func:`natural_sorted`.
            If *False*, disable sorting.
        parse:
            Function to parse sequence of sorted file names to dims, shape,
            chunk indices, and filtered file names.
            The default is :py:func:`parse_filenames` if `kwargs`
            contains `'pattern'`.
        **kwargs:
            Additional arguments passed to `parse` function.

    Examples:
        >>> filenames = ['temp_C001T002.tif', 'temp_C001T001.tif']
        >>> ims = TiffSequence(filenames, pattern=r'_(C)(\d+)(T)(\d+)')
        >>> ims[0]
        'temp_C001T002.tif'
        >>> ims.shape
        (1, 2)
        >>> ims.axes
        'CT'

    Callable[..., NDArray[Any]]r   r  r   r   r  r  r  ztuple[tuple[int, ...]]r  r  r,  rb   
_containerN)r|   r{   parser   @str | os.PathLike[Any] | Sequence[str | os.PathLike[Any]] | Noner|   r   r{   r   rI	  r  r   r   r  c                   d }|d}|t           }nt          |          r|}n	|rt           }| _        |dd l}t	          |t
          t          j        f          rdd l}	|		                    |           _        n$t           j        d          st          d          t	          |t
                    r:|                     j                                        |          }| ||          }nut	          |t          j                  r%t          j        |          g}|| ||          }n6t	          |t
                    r!t          j        |          }| ||          }d |D             }|st          d          t          |          st          d          |r
|fd fd}
|
}||                    dd           rt"          }|r2	  ||fi |\  }}}}ng# t          $ r}t          d          |d }~ww xY wd}t%          |          f}t'          d t)          t%          |                    D                       }t	          |t*                    rt	          |d         t
                    sJ t,          j        d                    fd|D                       }| _        | _        | _        t'          |           _        t'          |           _        | _        d S )Nr   r   r  zinvalid containerc                6    g | ]}t          j        |          S r   )r  r  r>  s     r   r:  z)FileSequence.__init__.<locals>.<listcomp>1  s     ---!1---r   r   zinvalid imread functionr  r   _imreadrb   r   r   r   c                   j                             |           5 }t          j        |                                          5 } ||fi |cd d d            cd d d            S # 1 swxY w Y   	 d d d            d S # 1 swxY w Y   d S r   )rH	  r  r  r  r?  )r  rM	  r   handle1handle2rp  s        r   imread_z&FileSequence.__init__.<locals>.imread_1  s(    _))%00 :GGLLNN33 :w&ww99&99: : : : : : :: : : : : : : :: : : : : : : : :: : : : : : : : : : : : : : : : : :s5   'A>	A%A>%A)	)A>,A)	-A>>BBrx   zfailed to parse file names)rS  c              3     K   | ]}|fV  d S r   r   r  s     r   r   z(FileSequence.__init__.<locals>.<genexpr>1  s$      <<QQD<<<<<<r   r  c              3     K   | ]D}                     |                                |d                                                    V  EdS r4  )rY  r  rT  )r   dimr  s     r   r   z(FileSequence.__init__.<locals>.<genexpr>1  sE      NN#uyyc!fllnn==NNNNNNr   )r  r   rM	  rb   r   rb   r   r   )r?   callablerH	  fnmatchr   r   r  PathLikezipfileZipFiler;  r   filternamelistr  r   rY  rA   r   r  r  rA  r   r  r   r,  r   r  r  r   r  )rp  r   r   r|   r{   rI	  r   	sort_funcrV	  rX	  rQ	  r  r   r  r  r  r  s   `               @r   rs  zFileSequence.__init__1  sC    6:	=E<&IId^^ 	'II 	'&I $ NNN)c2;%788 6")//)"<"<T_f55 6 !4555%%% -t'?'?'A'A5II(%Ie,,Er{++ 	)Yu%%&EI$9!	%((s## 	)Ie$$E$!	%((--u--- 	/-... 	86777 		 ,2: : : : : : : F=VZZ	488=#E 	=H.3eE.D.DV.D.D+eWee H H H !=>>CGH !DZZME<<%E

*;*;<<<<<G%&&D:eAh+D+DDDDwwNNNNNNNNN	$KK	5\\
s   G 
G;&G66G;rW   )r   r}   r   r   r   r   r   r   r   r}   r   r   r   r   r   r   r   r   r   r   r   r   c                    j         }	||z  ||dk     rt          j        }t          t	          |	          |          }t          |t                    sJ  j        t          k    rdnt                    ||#  j        |	d         fi }
|
j	        }|
j
        }~
t          j
        |          }|J |rt           j	        ||          }t          ||j	        |          d fd}|dk     r<t          |                     j                  |	          D ]\  }} |||           n	t#          |          5 }|                    ||                     j                  |	          D ]}	 ddd           n# 1 swxY w Y   n j	        |z   }t          |||           j        dg|R  d fd}|dk     r(t           j        |	          D ]\  }} |||           nGt#          |          5 }|                    | j        |	          D ]}	 ddd           n# 1 swxY w Y   |_	        S )a;  Return images from files as NumPy array.

        Parameters:
            imreadargs:
                Arguments passed to :py:attr:`FileSequence.imread`.
            chunkshape:
                Shape of chunk in each file.
                Must match ``FileSequence.imread(file, **imreadargs).shape``.
                By default, this is determined by reading the first file.
            chunkdtype:
                Data type of chunk in each file.
                Must match ``FileSequence.imread(file, **imreadargs).dtype``.
                By default, this is determined by reading the first file.
            axestiled:
                Axes to be tiled.
                Map stacked sequence axis to chunk axis.
            ioworkers:
                Maximum number of threads to execute
                :py:attr:`FileSequence.imread` asynchronously.
                If *0*, use up to :py:attr:`_TIFF.MAXIOWORKERS` threads.
                Using threads can significantly improve runtime when reading
                many small files from a network share.
                If enabled, internal threading for the `imread` function
                should be disabled.
            out_inplace:
                :py:attr:`FileSequence.imread` decodes directly to the output
                instead of returning an array, which is copied to the output.
                Not all imread functions support this, especially in
                non-contiguous cases.
            out:
                Specifies how image array is returned.
                By default, create a new array.
                If a *numpy.ndarray*, a writable array to which the images
                are copied.
                If *'memmap'*, create a memory-mapped array in a temporary
                file.
                If a *string* or *open file*, the file used to create a
                memory-mapped array.
            **kwargs:
                Arguments passed to :py:attr:`FileSequence.imread` in
                addition to `imreadargs`.

        Raises:
            IndexError, ValueError: Array shapes do not match.

        NrW   Tr   )r   r  tuple[int | slice, ...]r  r   r   r  c                d    r j         |fd|          i d S  j         |fi }|| <   ~d S Nr   r   )r  r  imr   r   r  rp  s      r   r  z"FileSequence.asarray.<locals>.funcV2  s_      DKCC6%=CFCCCCC$U55f55B$&F5Mr   r  rT  c                    | d S t          t          j        | j                            }r j        |fd|         i d S  j        |fi }||<   ~d S r`	  )r   r  r  r   r   )r  r  index_ra	  r   r   r  rp  s       r   r  z"FileSequence.asarray.<locals>.funco2  s    =F+
    DKDD6&>DVDDDDD$U55f55B%'F6Nr   )r  r^	  r  r   r   r  )r,  r   MAXIOWORKERSr  r   r   r   r   r   r   r~   r  r1   r6   r  r  r  rS   r  rz  )rp  r   r}   r   r   r   r   r   r   r   ra	  tiledr  r  r  r  r	  r   r  s   `    `  `         @r   r   zFileSequence.asarray2  sj   v !j F	A)IE

I..	)S)))))4;&#8#8KK{++K!3U1X0000BJJ[,,
%%% 6	!!$*jINNNE"3Z@@F	 	 	 	 	 	 	 	 	 1}}$'T\(B(BE$J$J ' 'LE5D&&&&' (	22 h%\\ell4<88%                   J+E"3z::F#V^B4444F        " 1}}$'e$<$< ' 'LE5D&&&&' (	22 h%\\$eDD                 !FLs$   3FFF H//H36H3ZarrFileSequenceStorec                     ddl m}  || fi |S )zReturn images from files as Zarr store.

        Parameters:
            **kwargs: Arguments passed to :py:class:`ZarrFileSequenceStore`.

        rW   )rf	  )r   rf	  )rp  r   rf	  s      r   rm   zFileSequence.aszarr2  s/     	0/////$$T44V444r   c                T    | j         | j                                          d| _         dS )zClose open files.N)rH	  r  r  s    r   r  zFileSequence.close2  s)    ?&O!!###r   c                    t          | j                  dk    r+t          j                            | j        d                   }n$t          j                            | j                  }|S )z8Return longest common sub-path of each file in sequence.rW   r   )r   r,  r  r  r  
commonpath)rp  rj	  s     r   rj	  zFileSequence.commonpath2  sO    t{q  Q88JJ++DK88Jr   c                H    t          j        dt          d           | j        S )zVDeprecated. Use the FileSequence sequence interface.

        :meta private:

        ze<tifffile.FileSequence.files> is deprecated since 2024.5.22. Use the FileSequence sequence interface.r  r  )rm  rn  r\  r,  r  s    r   r   zFileSequence.files2  s2     	7		
 	
 	
 	
 {r   r   c                T    t          | j                  t          | j                  z
  S )zNumber of empty chunks.)rD   r   r   r,  r  s    r   r  zFileSequence.files_missing2  s#     tz""S%5%555r   Iterator[str]c                *    t          | j                  S )z$Return iterator over all file names.)r-  r,  r  s    r   rd  zFileSequence.__iter__2  s    DK   r   c                *    t          | j                  S r   )r   r,  r  s    r   r  zFileSequence.__len__2  s    4;r   rn   c                   d S r   r   rX  s     r   rY  zFileSequence.__getitem__2  r  r   ra  c                   d S r   r   rX  s     r   rY  zFileSequence.__getitem__2  s    7:sr   int | slicestr | list[str]c                   | j         |         S r   )r,  rX  s     r   rY  zFileSequence.__getitem__2  s    {3r   c                    | S r   r   r  s    r   r  zFileSequence.__enter__2  r  r   r  r  r  c                .    |                                   d S r   r  r  s       r   r  zFileSequence.__exit__2  r  r   c                *    dt          |           ddS )Nz<tifffile.FileSequence @0xr  rj   r  r  s    r   r!  zFileSequence.__repr__2      <BtHH<<<<<r   c                   | j         rt          | j                   n| j        d         }t          j                            |          d         }d                    | j        j        |dt          | j                   d| j
         dd                    d                    d	 | j        D                                 d
                    d                    d | j        D                                 f          S )Nr   rT  
 zfiles: z (z	 missing)z	shape: {}r   c              3  4   K   | ]}t          |          V  d S r   rC  r  s     r   r   z'FileSequence.__str__.<locals>.<genexpr>2  s(      ,H,HSVV,H,H,H,H,H,Hr   zdims: {}c              3     K   | ]}|V  d S r   r   rD  s     r   r   z'FileSequence.__str__.<locals>.<genexpr>2  s"      +A+A!A+A+A+A+A+A+Ar   )rH	  r   r,  r  r  r  r   r-  r*  r   r  rL  r   r  )rp  r   s     r   r5  zFileSequence.__str__2  s    '+Js4?###DKNw}}T""2&zz'K#dk**KKd.@KKK""499,H,HTZ,H,H,H#H#HII!!$))+A+Aty+A+A+A"A"ABB	
 	
 		
r   )r   rG	  r   rJ	  r|   r   r{   r   rI	  r  r   rb   r   r  )r   r   r}   r   r   r   r   r   r   r   r   r   r   r   r   rb   r   r   )r   rb   r   rf	  r"  r&  )r   r  r  )r   rm	  r	  )rn   ra  r   r  )rn   rr	  r   rs	  )r   r/   r%  )r*  r+  r,  r-  r'  rs  r   rm   r  rj	  r(  r   r  rd  r  r^   rY  r  r  r!  r5  r   r   r   r/   r/   p1  s"        " "H ('''8BIII2'####$OOO 4815+/X X X X X Xz -1-1'+GK#' !I I I I I IV	5 	5 	5 	5          X 6 6 6 X6! ! ! !        222 X2::: X:             = = = =
 
 
 
 
 
r   r/   c                  6     e Zd ZdZ	 dedd fdZddZ xZS )r   zSequence of TIFF files containing compatible array data.

    Same as :py:class:`FileSequence` with the :py:func:`imread` function,
    `'\*.tif'` glob pattern, and `out_inplace` enabled by default.

    Nr   r   rJ	  r   rG	  r   rb   r   r  c               F     t                      j        ||dn|fi | d S )Nz*.tif)superrs  )rp  r   r   r   r-  s       r   rs  zTiffSequence.__init__2  s4     	EMuOOOOOOOr   r   c                *    dt          |           ddS )Nz<tifffile.TiffSequence @0xr  rj   r  r  s    r   r!  zTiffSequence.__repr__2  rx	  r   r   )r   rJ	  r   rG	  r   rb   r   r  r&  )r*  r+  r,  r-  r   rs  r!  __classcell__)r-  s   @r   r   r   2  s}          		P /5	P 	P 	P 	P 	P 	P 	P 	P= = = = = = = =r   r   c                      e Zd ZU dZded<   	 ded<   	 ded<   	 ded<   	 ded<   	 d	ed
<   	 d	ed<   	 ded<   	 ded<   	 dddd$dZd%dZ	 d&d'd Zed(d!            Z	ed)d#            Z
dS )*r1   a  Tiled sequence of chunks.

    Transform a sequence of stacked chunks to tiled chunks.

    Parameters:
        stackshape:
            Shape of stacked sequence excluding chunks.
        chunkshape:
            Shape of chunks.
        axestiled:
            Axes to be tiled. Map stacked sequence axis
            to chunk axis. By default, the sequence is not tiled.
        axes:
            Character codes for dimensions in stackshape and chunkshape.

    Examples:
        >>> ts = TiledSequence((1, 2), (3, 4), axestiled={1: 0}, axes='ABYX')
        >>> ts.shape
        (1, 6, 4)
        >>> ts.chunks
        (1, 3, 4)
        >>> ts.axes
        'AYX'

    r  r	  r   zstr | tuple[str, ...] | Noner  shape_squeezedaxes_squeezedr   
_stackdims
_chunkdims_shape_untiledztuple[tuple[int, int], ...]
_axestiledN)r   r  
stackshaper  r}   r   r   str | Sequence[str] | Noner   r  c                 t          |          | _        t          |          | _        t          |          t          |          z   | _        |4t          |          t          | j                  k    rt          d          |rt          |          }|                                D ]\  }}|| j        z   ||<   t          t          t          |                                                              | _
        |g nt          |          }t          | j                  }dg| j        z  t          |          z   }	t                      }
| j
        D ]\\  }}||
v s||
v rt          d          |
                    |           |
                    |           ||xx         ||         z  cc<   ]| j
        D ]\  }}||= |	|= |r||= t          |          | _        t          |	          | _        |d | _        nt#          |t$                    rd                    |          | _        nt          |          | _        nmd| _
        | j        | _        d| j        z  t          |          z   | _        |d | _        n1t#          |t$                    r|| _        nt          |          | _        t          | j                  t          | j                  k    sJ | j        ,t          | j                  t          | j                  k    sJ | j        ,t          d | j        D                       | _        d | _        d S dt          fd	t-          | j        | j                  D                       | _        t          fd
t-          | j        | j                  D                       }t#          | j        t$                    rd                    |          n|| _        d S )Nz2axes length does not match stackshape + chunkshaperW   zduplicate axisr  r   r  c              3  &   K   | ]}|d k    |V  dS r  r   r  s     r   r   z)TiledSequence.__init__.<locals>.<genexpr>o3  s&      'G'GaQ'G'Gr   )r  r  r^  r_  r  c              3  6   K   | ]\  }}|d k    s|v |V  dS r  r   r   r  rv  keeps      r   r   z)TiledSequence.__init__.<locals>.<genexpr>s3  sA       ( (Arq55B$JJ &JJJ( (r   c              3  6   K   | ]\  }}|d k    s|v |V  dS r  r   r	  s      r   r   z)TiledSequence.__init__.<locals>.<genexpr>x3  sA        Arq55B$JJ &JJJ r   )r   r	  r	  r  r	  r   r  r:  r  r|  r	  rA  setr  r   r	  r  r   r   r   r	  r	  r  )rp  r	  r}   r   r  ax0ax1	axes_listr   r	  usedr  r	  s               @r   rs  zTiledSequence.__init__13  s    j//j//#J//%
2C2CCD		S1D-E-E E ED    &	(YI%OO-- 7 7S!$t!6	##HVIOO4E4E-F-F$G$GHHDO"lT

I,--ES4?*T*-=-==F55D O . .S$;;#++$%5666c


jo-



 O ' 'S#J3K '!#uDJ--DK| 		D#&& -GGI..		!),,		 DO,DJ053D3DDDK| 		D#&& ( 		!$KK	4:#dk"2"222229 tz??c$)nn44449"''G'G4:'G'G'G"G"GD!%D:D"' ( ( ( ( TY77( ( ( # #D
      TY77    H &0	3%?%?M!!!X r   r  Iterable[Sequence[int]]Iterator[tuple[int, ...]]c             #  J  K   dg| j         z  }|D ]}|dV  	t          |          | j        k    r&t          t          |           d| j                   t	          |          |z   }| j        D ]\  }}||         ||<   | j        D ]\  }}||= 	t          |          V  dS )zReturn iterator over chunk indices of tiled sequence.

        Parameters:
            indices: Indices of chunks in stacked sequence.

        r   Nr  )r	  r   r	  r   rA  r	  r  )rp  r  r  r  r	  r	  s         r   r  zTiledSequence.indices3  s       S4?*
 	# 	#E}



u::00$E

%I%I%I%IJJJUj0 $ , ,HC!&sE#JJ $ # #HCc

Ell""""	# 	#r   Iterable[Sequence[int]] | None!Iterator[tuple[int | slice, ...]]c             #    K   t          d          g| j        z  }|&t          j        | j        d| j                           }|D ]}|dV  	t          |          | j        k    sJ g ||}| j        D ]F\  }}| j        |         }t          t          ||                   |z  }t          |||z             ||<   G| j        D ]\  }}||= 	t          |          V  dS )zReturn iterator over slices of chunks in tiled sequence.

        Parameters:
            indices: Indices of chunks in stacked sequence.

        N)ra  r	  r  r  r	  r	  r   r	  r\   r   r  )	rp  r  
chunkslicer  
wholeslicer	  r	  r6  r  s	            r   r  zTiledSequence.slices3  s      */t(G
?mD$78I$/8I$JKKG 	( 	(E}



5zzT_44442u2z2
 $ 6 6HC+C0AS*S/22Q6A&+Aq1uooJsOO $ ( (HC"3J''''''	( 	(r   c                *    t          | j                  S )z8Number of dimensions of tiled sequence excluding chunks.r  r  s    r   r  zTiledSequence.ndim3  r  r   r   c                *    t          | j                  S )zSequence is tiled.)r   r	  r  s    r   r  zTiledSequence.is_tiled3  s     DO$$$r   )
r	  r  r}   r  r   r   r  r	  r   r  )r  r	  r   r	  r   )r  r	  r   r	  r  r  )r*  r+  r,  r-  r'  rs  r  r  r(  r  r  r   r   r   r1   r1   2  sF         4 , 3&&&&-####C////NOOO9OOO)####>++++0 HL+/N N N N N N`# # # #0 9=( ( ( ( (:    X % % % X% % %r   r1   c                  l   e Zd ZU dZdZded<   ded<   ded<   ded	<   ded
<   ded<   ded<   ded<   ded<   	 dldddddmdZdnd Zdnd!Zdod"Z	dpd#Z
dpd$Zdod%Zdqdrd(Zdsdtd+Zdud-Zdvd/Zdnd0Z	 dqd1d2d3dwd:Z	 	 dxdd;dyd?Z	 dzddAd{dFZd|dGZ	 dld}dIZ	 dldJdddJdKd~dWZddXZdd]Zdd^Zdd_Zedd`            Zedda            Zeddb            Zeddc            Z edodd            Z!edpde            Z"eddf            Z#e#j$        ddh            Z#ddiZ%edpdj            Z&edpdk            Z'dS )r.   a$  Binary file handle.

    A limited, special purpose binary file handle that can:

    - handle embedded files (for example, LSM within LSM files).
    - re-open closed files (for multi-file formats, such as OME-TIFF).
    - read and write NumPy arrays and records from file-like objects.

    When initialized from another file handle, do not use the other handle
    unless this FileHandle is closed.

    FileHandle instances are not thread-safe.

    Parameters:
        file:
            File name or seekable binary stream, such as open file,
            BytesIO, or fsspec OpenFile.
        mode:
            File open mode if `file` is file name.
            The default is 'rb'. Files are always opened in binary mode.
        name:
            Name of file if `file` is binary stream.
        offset:
            Start position of embedded file.
            The default is the current file position.
        size:
            Size of embedded file.
            The default is the number of bytes from `offset` to
            the end of the file.

    )	r0  _filer\  _name_dir_lockr.  _size_closez6str | os.PathLike[Any] | FileHandle | IO[bytes] | Noner	  zIO[bytes] | Noner0  r   r\  r	  r	  r   r.  r	  r   r	  threading.RLock | NullContextr	  N)ru   rv   rw   rt   <Literal['r', 'r+', 'w', 'x', 'rb', 'r+b', 'wb', 'xb'] | Noner   r   ru   r   rv   r   rw   r   r  c                  |dn|| _         d | _        || _        |r|nd| _        d| _        |dn|| _        |dn|| _        d| _        t                      | _	        | 
                                 | j        J d S )NrN  r  rT  T)r\  r0  r	  r	  r	  r.  r	  r	  r2   r	  r  )rp  r   rt   ru   rv   rw   s         r   rs  zFileHandle.__init__3  s     "\TTt

!)TTr
	#^rr<RRT
 ]]
		x#####r   c                   | j         dS t          | j        t          j                  rt          j        | j                  | _        t          | j        t                    r| j        dd         dk    r| xj        dz  c_        | j        dvrt          d| j                   t          j	        
                    | j                  | _        t          j	                            | j                  \  | _        | _        t          | j        | j        d          | _         d| _        t!          d| j                  | _        nt          | j        t$                    r| j        j         | _         t!          d| j                  | _        | xj        | j        j        z  c_        d	| _        | j        sX| j        r@t          j	                            | j        j                  \  }}| d
| j         | | _        n| j        j        | _        | j        j        | _        | j        j        | _        nt)          | j        d          rZt+          t,          t.                   | j                  | _         	 | j                                          n"# t2          $ r}t          d          |d}~ww xY w| j        dk     r| j                                         | _        d	| _        | j        s	 t          j	                            | j         j                  \  | _        | _        n_# t6          $ rR 	 t          j	                            | j         j	                  \  | _        | _        n# t6          $ r
 d| _        Y nw xY wY nw xY w	 | j         j        | _        n# t6          $ r Y nw xY wt)          | j        d          rE| j        }t+          t,          t.                   |                                          | _         	 | j                                          nM# t2          $ r@}	 | j                                          n# t2          $ r Y nw xY wt          d          |d}~ww xY w| j        dk     r| j                                         | _        d| _        | j        sJ	 t          j	                            |j	                  \  | _        | _        n# t6          $ r
 d| _        Y nw xY w	 |j        | _        n4# t6          $ r Y n(w xY wt          dt=          | j                            | j         J | j        r| j                             | j                   | j         dk     r}| j                                         }| j                             | j        t          j!                   | j                                         | _         | j                             |           dS dS )zOpen or re-open file.NrT  b>   rN  wbxbrM  r1  )encodingTr   FrC	  ra  zbinary stream is not seekablezUnnamed binary streamr  zOpenFile is not seekablezLthe first parameter must be a file name or seekable binary file object, not )"r0  r   r	  r  rW	  r  r   r\  r   r  realpathr  r	  r	  r  r	  rq  r.  r.   splitextr;  r\   rZ   r  r]  r  ru   r?  rt   r  r~  ra  r	  ri  )rp  ru   r  r  r	  rr  s         r   r  zFileHandle.open4  sl   8Fdj"+.. 	/4:..DJdj#&& R	z"###%%

c!

z!::: !=!=!=>>>))$*55DJ$&GMM$*$=$=!DItzDJ
TBBBDHDKq$,//DLL
J// G	z~DHq$,//DLLLDJ..LLDK: 2< 2 " 0 01A B BID#$(!>!>4<!>!>!>DJJ!%!1DJ)DJ
DIITZ(( 9	 BuItz22DHK K K K !@AAsJK |a#x}}DK: 	==,.GMM$(-,H,H)DItzz% = = ==02 HM1 1-	4:: * = = =%<


==!X]

!   TZ(( 	EBuIuzz||44DHF F F FHNN$$$$    D !;<<#EF |a#x}}DK: 99,.GMM%*,E,E)DItzz% 9 9 9!8DJJJ9"Z

!    ,DJ'', ,   x###< 	(HMM$,''':>>(--//CHMM$,444DJHMM#	 >s   ,J 
J%J  J% 6L 
M3"6MM3M-*M3,M--M32M37N
 

NN0P
 

QP/.Q/
P<9Q;P<<QQ1S SSS& &
S32S3c                    | j         r;| j        6	 | j                                         n# t          $ r Y nw xY wd| _        dS dS dS )zClose file handle.N)r	  r0  r  r  r  s    r   r  zFileHandle.closey4  sj    ; 	48/        DHHH	 	//s   * 
77c                    | j         J 	 | j                                         S # t          t          f$ r*}t          t	          | j                    d          |d}~ww xY w)z@Return underlying file descriptor if exists, else raise OSError.Nz  does not have a file descriptor)r0  rR  rb  r?  r~  )rp  r  s     r   rR  zFileHandle.fileno4  st    x###	8??$$$( 	 	 	>>CCC 	s   $ A%AAc                t    | j         J t          | j         d          r| j                                         S dS )z'Return True if stream supports writing.NwritableF)r0  r;  r	  r  s    r   r	  zFileHandle.writable4  s=    x###48Z(( 	'8$$&&&ur   c                    dS )z-Return True if stream supports random access.Tr   r  s    r   seekablezFileHandle.seekable4  s    tr   c                V    | j         J | j                                         | j        z
  S )zReturn file's current position.)r0  r]  r.  r  s    r   r]  zFileHandle.tell4  s'    x###x}}--r   r   whencec               B   | j         J | j        ru|dk    r+| j                             | j        |z   |          | j        z
  S |dk    r>| j        dk    r3| j                             | j        | j        z   |z   d          | j        z
  S | j                             ||          S )a  Set file's current position.

        Parameters:
            offset:
                Position of file handle relative to position indicated
                by `whence`.
            whence:
                Relative position of `offset`.
                0 (`os.SEEK_SET`) beginning of file (default).
                1 (`os.SEEK_CUR`) current position.
                2 (`os.SEEK_END`) end of file.

        Nr   r  )r0  r.  ra  r	  )rp  rv   r	  s      r   ra  zFileHandle.seek4  s     x###< 		{{HMM$,"7@@4<O {{tzA~~HMM$,";f"DaHHl# x}}VV,,,r   rT  r  c               p    |dk     r| j         r| j        }| j        J | j                            |          S )zReturn bytes read from file.

        Parameters:
            size:
                Number of bytes to read from file.
                By default, read until the end of the file.

        r   )r.  r	  r0  r?  rp  rw   s     r   r?  zFileHandle.read4  s<     !888:Dx###x}}T"""r   bufferc               H    | j         J | j                             |          S )zRead bytes from file into buffer.

        Parameters:
            buffer: Buffer to read into.

        Returns:
            Number of bytes read from file.

        )r0  readintorp  r	  s     r   r	  zFileHandle.readinto4  s(     x###x  (((r   bytes | memoryview[Any]c               H    | j         J | j                             |          S )zWrite bytes to file and return number of bytes written.

        Parameters:
            buffer: Bytes to write to file.

        Returns:
            Number of bytes written.

        )r0  r  r	  s     r   r  zFileHandle.write4  s&     x###x~~f%%%r   c                x    | j         J t          | j         d          r| j                                          dS dS )z,Flush write buffers of stream if applicable.Nr  )r0  r;  r  r  s    r   r  zFileHandle.flush4  sF    x###48W%% 	HNN	 	r   r0  r  )rt   r  r~   rg   r   r  r  r   c                   | j         st          d          | j        J t          j        | j        ||| j        |z   ||          S )a  Return `numpy.memmap` of array data stored in file.

        Parameters:
            dtype:
                Data type of array in file.
            shape:
                Shape of array in file.
            offset:
                Start position of array-data in file.
            mode:
                File is opened in this mode. The default is read-only.
            order:
                Order of ndarray memory layout. The default is 'C'.

        z%cannot memory-map file without filenoN)r~   rt   rv   r   r  )r  r   r0  r  r   r.  )rp  r~   r   rv   rt   r  s         r   rd  zFileHandle.memmap_array4  s`    0 | 	FDEEEx###|H<&(
 
 
 	
r   r   r  r   NDArray[Any] | Nonec                  t          j        |          }|dk     r|| j        n|j        }||j        z  }n
||j        z  }|t          j        ||          n|}|j        |k    rt          d          | j        J |r"| j                            | j	        |z              	 | j        
                    |          }n\# t          $ rO t          j        | j                            |          |                              |j                  |dd<   |}Y nw xY w||k    rt          d| d|           |j        j        sI|j        s|                    d           |                    |j                                                  }n*|j        j        |j        k    r|                    d           |$t)          |d          r|                                 |S )a  Return NumPy array from file in native byte order.

        Parameters:
            dtype:
                Data type of array to read.
            count:
                Number of items to read. By default, all items are read.
            offset:
                Start position of array-data in file.
            out:
                NumPy array to read into. By default, a new array is created.

        r   Nzsize mismatchzfailed to read  bytes, got Tr  )r  r~   r	  r  r  r  r   r0  ra  r.  r	  r?  r  r?  rz  r   isnativebyteswapr  r  r;  r  )rp  r~   r  rv   r   r  r  r   s           r   re  zFileHandle.read_array
5  s   * E""199#&;TZZCJFen,EEU^+F.1kUE***s=F""_---x### 	1HMM$,/000	!!&))AA 	 	 	(v)>)>FFNN F111I AAA		 ;;FvFF1FFGGG|$ 	"> &%%%[[!:!:!<!<==FF\"en44OOD!!!?sG$$ 		s   !B< <ADDrW   r  tuple[int, ...] | int | Noner   'Literal['S', '<', '>', '=', '|'] | Nonenumpy.recarray[Any, Any]c                  | j         J t          j        |          }||                    |          }	 t          j                            | j         ||          }n# t          $ rs || j        |j        z  }t          t          |                    |j        z  }| j                             |          }t          j                            |||          }Y nw xY w|dk    r|d         n|S )a  Return NumPy record from file.

        Parameters:
            dtype:
                Data type of record array to read.
            shape:
                Shape of record array to read.
            byteorder:
                Byte order of record array to read.

        NrW   r   )r0  r  r~   r  recr  r  r	  r  rD   rS  r?  r  )rp  r~   r   r   recordrw   r   s          r   read_recordzFileHandle.read_recordI5  s    $ x###E"" &&y11E	Y''% FF  	 	 	}
en48E??++en<D
 8==&&DY)) FFF	 "QJJvayyF2s   &A A:CCc                   |dk     rdS | j         J | j                             |dz
  t          j                   | j                             d           |S )zAppend null-bytes to file.

        The file position must be at the end of the file.

        Parameters:
            size: Number of null-bytes to write to file.

        rW   r   Nr1  )r0  ra  r  r  r  r	  s     r   rF  zFileHandle.write_emptyu5  sU     !881x###dQh,,,wr   r   c               b   | j         J | j                                         }t          j        ||          }	 |                    | j                    nA# t
          j        $ r/ | j                             |                                           Y nw xY w| j                                         |z
  S )zyWrite NumPy array to file in C contiguous order.

        Parameters:
            data: Array to write to file.

        )	r0  r]  r  r  tofiler  UnsupportedOperationr  r  )rp  r   r~   rr  s       r   rG  zFileHandle.write_array5  s     x###hmmoo&tU33	+KK!!!!& 	+ 	+ 	+HNN4<<>>*****	+ x}}$$s   A ;BBT)r{   r  rs   r  r  r   r  r  r  r{   r  r  rs   r  MIterator[tuple[bytes | None, int]] | Iterator[list[tuple[bytes | None, int]]]c            #    K   | j         J t                    }|dk     rdS |dk    rdnd         }	|	         dk    rk|	         dk    r_|| j        }|5  |                     |	                    | j                             |	                   }
ddd           n# 1 swxY w Y   nd}
|r|
|	fn|
|	fgV  dS || j        }|t
          j        }fdt          |          D             }nfdt          |          D             }|rt          |d           }d}t          |dz
            D ]?}||         \  }}}||dz            d         }|dk    s|dk    s|dk    r2||z   |k    rd	} n@| j        }| j         j        }|rd}||k     r|}d
}d}||k    r<||k     r6||         \  }}}|dk    r|dk    r|dk     r|}||z  }|dz  }||k    r||k     6|dk     rd}
n0|5   ||            ||          }
ddd           n# 1 swxY w Y   d}d}g }||k     ra||         \  }	}}|dk    r-|dk    r'||z  }|	                    |
||         |	f           |}n|	                    d|	f           |dz  }||k     a|r	|E d{V  n|V  ||k     dS d}||k     rg }d}|5  ||k    rw||k     rq||         \  }	}}|dk    r7|dk    r1 ||           |	                     ||          |	f           ||z  }n|	                    d|	f           |dz  }||k    r||k     qddd           n# 1 swxY w Y   |r	|E d{V  n|V  ||k     dS dS )a*  Return iterator over segments read from file and their indices.

        The purpose of this function is to

        - reduce small or random reads.
        - reduce acquiring reentrant locks.
        - synchronize seeks and reads.
        - limit size of segments read into memory at once.
          (ThreadPoolExecutor.map is not collecting iterables lazily).

        Parameters:
            offsets:
                Offsets of segments to read from file.
            bytecounts:
                Byte counts of segments to read from file.
            indices:
                Indices of segments in image.
                The default is `range(len(offsets))`.
            sort:
                Read segments from file in order of their offsets.
            lock:
                Reentrant lock to synchronize seeks and reads.
            buffersize:
                Approximate number of bytes to read from file in one pass.
                The default is :py:attr:`_TIFF.BUFFERSIZE`.
            flat:
                If *True*, return iterator over individual (segment, index)
                tuples.
                Else, return an iterator over a list of (segment, index)
                tuples that were acquired in one pass.

        Yields:
            Individual or lists of `(segment, index)` tuples.

        NrW   r   c                2    g | ]}||         |         fS r   r   r  s     r   r:  z,FileHandle.read_segments.<locals>.<listcomp>5  s(    NNN1GAJ
16NNNr   c                >    g | ]}|         |         |         fS r   r   )r   r  r  r  r  s     r   r:  z,FileHandle.read_segments.<locals>.<listcomp>5  s9       <=WQZA7  r   c                    | d         S r  r   r  s    r   r  z*FileHandle.read_segments.<locals>.<lambda>5  s
    ad r   r  TFrT  )
r0  r   r	  ra  r?  r   
BUFFERSIZEr  r|  r   )rp  r  r  r  r{   r  rs   r  r_  r  r   r  iscontigr  r	  rv   r  
nextoffsetra  r?  r6  or	  r  r  r  rw   s    ```                       r   r  zFileHandle.read_segments5  s     f x###WA::FQ;; AAgajE% 1$$!););<:D < <IIgen---8==E):;;D< < < < < < < < < < < < < < < #'<4--tUm_<<<F<:DJ?NNNNNfNNNHH     AFv  H  	<hNN;;;Hvz"" 	 	A#+A; Avy!!a%+J{{i1nn
a	!Z//  0 yx}  '	Af**	:--!f**&qkGAq!1uuQ!A::%&F!Q	FA  :--!f** A::DD / /V#tI/ / / / / / / / / / / / / / / !ee/7{,E69zzi!mm	)!%*-u5   !%tUm444FA !ee  !%%%%%%%%% LLLG f**H F&jjFD  j((QZZ/7{,E69zzi!mmVttI&>??? 	)tUm444FA j((QZZ                !!!!!!!!!' &jjjjjjs7   <B##B'*B'-HHH.A>L88L<?L<c                    | S r   r   r  s    r   r  zFileHandle.__enter__;6  r  r   r  rb   r  r  c                <    |                                   d | _        d S r   )r  r	  r  s       r   r  zFileHandle.__exit__>6  s    




r   c                4    dt          | j        d          dS )Nz<tifffile.FileHandle r  rj   )r   r	  r  s    r   r!  zFileHandle.__repr__M6  s    Cwtz2'>'>CCCCr   c                l    d                     d| j        | j        | j         d| j        dndf          S )Nrz	  r.   z bytesr  r  )r   r	  r	  r	  r0  r  s    r   r5  zFileHandle.__str__P6  sF    zz
	:%%% H,&
 
 	
r   c                    | j         S )zName of file or stream.)r	  r  s    r   ru   zFileHandle.name[6  r'	  r   c                    | j         S )z"Directory in which file is stored.)r	  r  s    r   r  zFileHandle.dirname`6  s     yr   c                V    t           j                            | j        | j                  S )zAbsolute path of file.)r  r  r   r	  r	  r  s    r   r  zFileHandle.pathe6  s     w||DItz222r   c                    t           j                            | j                                                  \  }}|r|                    d          rd|z   }|S )z&File name extension of file or stream.z.ome)r  r  r	  r	  r  rP  )rp  ru   r  s      r   rH  zFileHandle.extensionj6  sT     G$$TZ%5%5%7%788	c 	4==(( 	3,C
r   c                    | j         S )zSize of file in bytes.)r	  r  s    r   rw   zFileHandle.sizer6  r'	  r   c                    | j         du S )zFile is closed.Nr  r  s    r   r  zFileHandle.closedw6  s     x4r   c                    | j         S )z/Reentrant lock to synchronize reads and writes.)r	  r  s    r   r  zFileHandle.lock|6  r'	  r   rU  c               0    |                      |           d S r   )set_lockr  s     r   r  zFileHandle.lock6  s    er   c                   t          |          t          | j        t                    k    r*|rt	          j                    nt                      | _        d S d S r   )r   r   r	  r2   	threadingRLockr  s     r   r	  zFileHandle.set_lock6  sH    ;;*TZ====.3F***DJJJ >=r   c                8    t          | j        t                     S )z<A reentrant lock is currently used to sync reads and writes.)r   r	  r2   r  s    r   has_lockzFileHandle.has_lock6  s     dj+6666r   c                \    	 | j                                          dS # t          $ r Y dS w xY w)z)File has fileno and can be memory-mapped.TF)r0  rR  r  r  s    r   r  zFileHandle.is_file6  s@    	HOO4 	 	 	55	s    
++r   )rt   r	  r   r   ru   r   rv   r   rw   r   r   r  r"  r  r  r  )r	  r   rv   r   r   r   r8  )rw   r   r   r  )r	  r  r   r   )r	  r	  r   r   )r~   rg   r   r  rv   r   rt   r   r  r   r   r   )rT  r   )
r~   rg   r  r   rv   r   r   r	  r   r   r  )r~   rg   r   r	  r   r	  r   r	  )rw   r   r   r   )r   r   r~   rg   r   r   )r  r   r  r  r  r  r{   r   r  r  rs   r   r  r   r   r	  r#  r%  r&  )r   r	  ri  )(r*  r+  r,  r-  r  r'  rs  r  r  rR  r	  r	  r]  ra  r?  r	  r  r  rd  re  r	  rF  rG  r  r  r  r!  r5  r(  ru   r  r  rH  rw   r  r  r  r	  r	  r  r   r   r   r.   r.   3  sR         D
I BAAAJJJJJJIIILLLJJJLLL(((( $  !$ $ $ $ $ $0e e e eN            . . . .
- - - - -6# # # # #) ) ) )& & & &    	"
 "
 "
 "
 "
 "
 "
N 	= $(= = = = = =D /0*3
 >B*3 *3 *3 *3 *3 *3X   &  % % % % %8 )-] 59!%] ] ] ] ] ]~      D D D D	
 	
 	
 	
    X    X 3 3 3 X3    X    X       X     X 
[   [G G G G 7 7 7 X7    X  r   r.   c                      e Zd ZU dZdZded<   	 ded<   	 ded<   	 d	ed
<   	 ded<   	 	 d%ddd&dZd'dZd'dZd(dZ		 d)d*dZ
	 d)d+d Zd(d!Zd,d"Zd-d$ZdS ).r-   zKeep FileHandles open.

    Parameters:
        size: Maximum number of files to keep open. The default is 8.
        lock: Reentrant lock to synchronize reads and writes.

    )r   r	  pastr  rw   r   rw   zdict[FileHandle, int]r   zset[FileHandle]r	  zlist[FileHandle]r	  r	  r  N)r  r   r  r   r  c                   g | _         i | _        t                      | _        |dnt	          |          | _        |t                      n|| _        d S r  )r	  r   r	  r	  r   rw   r2   r  )rp  rw   r  s      r   rs  zFileCache.__init__6  sI     	
EE	AA3t99	%)\KMMMt			r   rq  r.   c                  | j         5  || j        v r| j        |xx         dz  cc<   n~|j        r9|                                 d| j        |<   | j                            |           n>d| j        |<   | j                            |           | j                            |           ddd           dS # 1 swxY w Y   dS )z Open file, re-open if necessary.rW   r  N)r  r   r  r  r	  r   r	  r  rp  rq  s     r   r  zFileCache.open6  s   Y 
	% 
	%TZ
2!# %			!"
2	  $$$$!"
2	b!!!	  $$$
	% 
	% 
	% 
	% 
	% 
	% 
	% 
	% 
	% 
	% 
	% 
	% 
	% 
	% 
	% 
	% 
	% 
	%s   BB33B7:B7c                   | j         5  || j        v r| j        |xx         dz  cc<   |                                  ddd           dS # 1 swxY w Y   dS )z%Close least recently used open files.rW   N)r  r   _trimr	  s     r   r  zFileCache.close6  s    Y 	 	TZ
2!#JJLLL	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   3AAAc                *   | j         5  t          | j                                                  D ]J\  }}|| j        vr<|                                 | j        |= | j        | j                            |          = K	 ddd           dS # 1 swxY w Y   dS )z7Close all opened files if not in use when opened first.N)r  rA  r   r:  r	  r  r	  r  )rp  rq  refcounts      r   clearzFileCache.clear6  s    Y 	7 	7 $TZ%5%5%7%7 8 8 7 7HTY&&HHJJJ
2	$)//""5"56	7	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7 	7s   A2BBBr   rv   r  r	  r  c                  | j         5  || j        v}|rd|j        r|                                 d| j        |<   n$d| j        |<   | j                            |           | j                            |           |                    ||           |	                    |          }|r| 
                                 ddd           n# 1 swxY w Y   |S )a*  Return bytes read from binary file.

        Parameters:
            fh:
                File handle to read from.
            offset:
                Position in file to start reading from relative to the
                position indicated by `whence`.
            bytecount:
                Number of bytes to read.
            whence:
                Relative position of offset.
                0 (`os.SEEK_SET`) beginning of file (default).
                1 (`os.SEEK_CUR`) current position.
                2 (`os.SEEK_END`) end of file.

        r   rW   N)r  r   r  r  r	  r  r	  r   ra  r?  r	  )rp  rq  rv   r  r	  r	  r   s          r   r?  zFileCache.read6  s   > Y 	 	$*$A %9 &GGIII%&DJrNN%&DJrNIMM"%%%	  $$$GGFF###779%%D 

	 	 	 	 	 	 	 	 	 	 	 	 	 	 	    B1CC	C	r   c                  | j         5  || j        v}|rd|j        r|                                 d| j        |<   n$d| j        |<   | j                            |           | j                            |           |                    ||           |	                    |          }|r| 
                                 ddd           n# 1 swxY w Y   |S )a  Write bytes to binary file.

        Parameters:
            fh:
                File handle to write to.
            offset:
                Position in file to start writing from relative to the
                position indicated by `whence`.
            value:
                Bytes to write.
            whence:
                Relative position of offset.
                0 (`os.SEEK_SET`) beginning of file (default).
                1 (`os.SEEK_CUR`) current position.
                2 (`os.SEEK_END`) end of file.

        r   rW   N)r  r   r  r  r	  r  r	  r   ra  r  r	  )rp  rq  rv   r   r	  r	  writtens          r   r  zFileCache.write7  s   2 Y 	 	$*$A %9 &GGIII%&DJrNN%&DJrNIMM"%%%	  $$$GGFF###hhtnnG 

	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 r	  c                8   d}t          | j                  }||cxk     r| j        k    rqn dS | j        |         }|| j        vr;| j        |         dk    r*|                                 | j        |= | j        |= |dz  }n|dz  }||cxk     r| j        k    hdS  dS dS )zTrim file cache.r   rW   N)r   r	  rw   r	  r   r  )rp  r  rw   rq  s       r   r	  zFileCache._trim57  s    49~~d&&&&TY&&&&&&5!B""tz"~':':


JrNIe$	
 d&&&&TY&&&&&&&&&r   c                *    t          | j                  S )zReturn number of open files.)r   r   r  s    r   r  zFileCache.__len__C7  s    4:r   r   c                *    dt          |           ddS )Nz<tifffile.FileCache @0xr  rj   r  r  s    r   r!  zFileCache.__repr__G7  s    9D99999r   r   )rw   r   r  r  r   r  )rq  r.   r   r  r"  r  )
rv   r   r  r   r	  r   rq  r.   r   r  )
rv   r   r   r  r	  r   rq  r.   r   r   r  r&  )r*  r+  r,  r-  r  r'  rs  r  r  r	  r?  r  r	  r  r!  r   r   r   r-   r-   6  sR          :IIII/    +$$''''9  
< 6:	
< 
< 
< 
< 
< 
<% % % %   7 7 7 7 - - - - -j ' ' ' ' 'R      : : : : : :r   r-   c                     e Zd ZU dZdZded<   	 ded<   	 ded<   	 ded<   	 ded<   	 ded	<   	 ded
<   	 	 	 	 	 	 	 	 d-d.dZed/d            Zed/d            Z	ed/d            Z
ed0d            Zed1d            Zed/d            Zed2d            Zed3d            Zed3d            Zed4d            Zd/dZed5d!            Zed6d#            Zd7d&Zd8d)Zd9d+Zd,S ):r0   a  Normalized shape of image array in TIFF pages.

    Parameters:
        frames:
            Number of TIFF pages.
        separate_samples:
            Number of separate samples.
        depth:
            Image depth.
        length:
            Image length (height).
        width:
            Image width.
        contig_samples:
            Number of contiguous samples.
        extrasamples:
            Number of extra samples.

    rx  ra  r`  r_  r^  r]  r   r   rx  ra  r`  r_  r^  r]  r   rW   r   r   r  c                T   |dk    r|dk    rt          d          t          |          | _        t          |          | _        t          |          | _        t          |          | _        t          |          | _        t          |          | _        t          |          | _        d S )NrW   zinvalid samples)	r   r   rx  ra  r`  r_  r^  r]  r   )rp  rx  ra  r`  r_  r^  r]  r   s           r   rs  zStoredShape.__init__7  s     q  ^q%8%8.///&kk #$4 5 5ZZ
&kkZZ
!.11--r   c                z    t          | j                  | j        z  | j        z  | j        z  | j        z  | j        z  S )zProduct of all dimensions.)absrx  ra  r`  r_  r^  r]  r  s    r   rw   zStoredShape.size7  sP     #$j k j	
 !"	
r   c                    | j         dk    s| j        dk    sJ | j         dk    r| j         n| j        }| j        |k     sJ |S )z0Number of samples. Count of SamplesPerPixel tag.rW   )ra  r]  r   )rp  rb  s     r   rb  zStoredShape.samples7  sf     $))T-@A-E-E-E-E $q(( !!$ 	
  7****r   c                     | j         | j        z
  S )zNumber of photometric samples.)rb  r   r  s    r   photometric_sampleszStoredShape.photometric_samples7  s     |d///r   #tuple[int, int, int, int, int, int]c                N    | j         | j        | j        | j        | j        | j        fS )z0Normalized 6D shape of image array in all pages.rx  ra  r`  r_  r^  r]  r  s    r   r   zStoredShape.shape7  s.     K!JKJ
 	
r   r  c                B    | j         | j        | j        | j        | j        fS )z2Normalized 5D shape of image array in single page.ra  r`  r_  r^  r]  r  s    r   r  zStoredShape.page_shape7  s)     !JKJ
 	
r   c                P    | j         | j        z  | j        z  | j        z  | j        z  S )z%Product of dimensions in single page.r
  r  s    r   re  zStoredShape.page_size7  s<     !jk j !	"	
r   r  c                    | j         | j        g}| j        dk    r|                    d| j                   n%| j        dk    r|                    | j                   | j        dk    r|                    d| j                   t          |          S )z9Shape with length-1 removed, except for length and width.rW   r   )r_  r^  ra  r[  r]  r   rx  r  r  s     r   r  zStoredShape.squeezed7  s     dj) 1$$LLD12222 1$$LL,---;??LLDK(((U||r   r   c                    | j         dk    oX| j        dk    oM| j        dk    oB| j        dk    o7| j        dk    p
| j        dk    o!| j        dk    r| j        n| j        | j        k    S )zShape is valid.rW   )rx  r`  r_  r^  ra  r]  r   r  s    r   rf  zStoredShape.is_valid7  s     K1 
 
a
 q 
  
a
  &!+Gt/Ba/G	
  &** ##* 	
r   c                    | j         dk    S )zShape contains planar samples.rW   )ra  r  s    r   	is_planarzStoredShape.is_planar7  s     $q((r   r   c                :    | j         dk    rdS | j        dk    rdS dS )z!Value of PlanarConfiguration tag.rW   r  N)ra  r]  r  s    r   r   zStoredShape.planarconfig7  s/      1$$1""1tr   c                    dS )Nr  r   r  s    r   r  zStoredShape.__len__7      qr   rn   c                   d S r   r   rX  s     r   rY  zStoredShape.__getitem__8  r  r   ra  c                   d S r   r   rX  s     r   rY  zStoredShape.__getitem__8  r  r   rr	  int | tuple[int, ...]c               Z    | j         | j        | j        | j        | j        | j        f|         S r   r
  rX  s     r   rY  zStoredShape.__getitem__8  s6    K!JKJ
  	r   rh  r  c                   t          |t                    o_| j        |j        k    oO| j        |j        k    o?| j        |j        k    o/| j        |j        k    o| j        |j        k    o| j        |j        k    S r   )r   r0   rx  ra  r`  r_  r^  r]  )rp  rh  s     r   __eq__zStoredShape.__eq__8  s    uk** <u|+<%)??< 
ek)< u|+	<
 
ek)< #u';;	
r   r   c                x    d| j          d| j         d| j         d| j         d| j         d| j         d| j         dS )	Nz<StoredShape(frames=z, separate_samples=z, depth=z	, length=z, width=z, contig_samples=z, extrasamples=z)>r
  r  s    r   r!  zStoredShape.__repr__8  s    k  $ 5  Z  k	 
 Z  #1  !-  
	
r   N)rW   rW   rW   rW   rW   rW   r   )rx  r   ra  r   r`  r   r_  r   r^  r   r]  r   r   r   r   r  r  )r   r	
  r'  r  r  rj  )rn   r   r   r   )rn   ra  r   r  )rn   rr	  r   r
  )rh  r  r   r   r&  )r*  r+  r,  r-  r  r'  rs  r(  rw   rb  r
  r   r  re  r  rf  r
  r   r  r^   rY  r
  r!  r   r   r   r0   r0   K7  st         (I KKK%JJJ4KKK:JJJ/'B  !. . . . .* 	
 	
 	
 X	
 	 	 	 X	 0 0 0 X0 	
 	
 	
 X	
 
 
 
 X
 
 
 
 X
 	 	 	 X	 
 
 
 X
  ) ) ) X)    X    222 X2@@@ X@   	
 	
 	
 	

 
 
 
 
 
r   r0   c                  .    e Zd ZdZdZddZdd
ZddZdS )r2   zxNull context manager. Can be used as a dummy reentrant lock.

    >>> with NullContext():
    ...     pass
    ...

    r   r   c                    | S r   r   r  s    r   r  zNullContext.__enter__78  r  r   r  rb   r  r  r  c                    d S r   r   r  s       r   r  zNullContext.__exit__:8  s    r   r   c                    dS )NzNullContext()r   r  s    r   r!  zNullContext.__repr__=8  s    r   N)r   r2   r%  r&  )r*  r+  r,  r-  r  r  r  r!  r   r   r   r2   r2   +8  sa          I           r   r2   c                      e Zd ZU dZdZded<   	 ded<   	 ded<   	 	 dddd	d dZdddd!dZdddd!dZ	 dddd"dZ	e
d#d            Zd$dZd$dZd%dZd&dZdS )'r3   a  Stopwatch for timing execution speed.

    Parameters:
        message:
            Message to print.
        end:
            End of print statement.
        started:
            Value of performance counter when started.
            The default is the current performance counter.

    Examples:
        >>> import time
        >>> with Timer('sleep:'):
        ...     time.sleep(1.05)
        sleep: 1.0... s

    )startedstoppeddurationr  r"
  r#
  r$
  Nr!  )endr"
  messager   r%
  r   float | Noner   r  c                   |t          ||d           d| _        |t          j                    }|x| _        | _        d S )NTr%
  r          printr$
  timeperf_counterr"
  r#
  )rp  r&
  r%
  r"
  s       r   rs  zTimer.__init__a8  sK     's$////?'))G&--t|||r   r%
  c                   |t          ||d           d| _        t          j                    x| _        | _        | j        S )z$Start timer and return current time.NTr)
  r*
  r+
  rp  r&
  r%
  s      r   r  zTimer.starto8  sC    's$////&*&7&9&99t||r   c                   t          j                    | _        |t          ||d           | j        | j        z
  | _        | j        S )zReturn duration of timer till start.

        Parameters:
            message: Message to print.
            end: End of print statement.

        NTr)
  )r-
  r.
  r#
  r,
  r"
  r$
  r1
  s      r   r  z
Timer.stopw8  sG     (**'s$////t|3}r   c               n    t          |           }|t          |d           t          ||d           dS )zPrint duration from timer start till last stop or now.

        Parameters:
            message: Message to print.
            end: End of print statement.

        Nr!  r/
  Tr)
  )r   r,
  )rp  r&
  r%
  r  s       r   r,
  zTimer.print8  sC     $ii's####cs$''''''r   c                 (    t          j                    S )z$Return value of performance counter.)r-
  r.
  r   r   r   clockzTimer.clock8  s      """r   c                t   | j         dk    rt          j                    | j        z
  }n| j         }t	          t          |                    }d}|t          |          k     r6|||dz            dv r'|dz  }|t          |          k     r|||dz            dv '|||dz            dk    r|dz  }||d          d	S )
z7Return duration from timer start till last stop or now.r*
  )secondsr   r  z0:0010203040506070809rW   r  Nz s)r$
  r-
  r.
  r"
  r   	TimeDeltar   )rp  r$
  r  r  s       r   r5  zTimer.__str__8  s    =C(**T\9HH}H	(+++,,#a&&jjQq1q5y\-DDDFA #a&&jjQq1q5y\-DDDQQY<3FAABB%|||r   c                    d| j          dS )NzTimer(started=r  )r"
  r  s    r   r!  zTimer.__repr__8  s    /////r   c                    | S r   r   r  s    r   r  zTimer.__enter__8  r  r   r  rb   r  r  c                .    |                                   d S r   )r,
  r  s       r   r  zTimer.__exit__8  r  r   r   )r&
  r   r%
  r   r"
  r'
  r   r  )r&
  r   r%
  r   r   r  )r&
  r   r%
  r   r   r  )r   r  r&  )r   r3   r%  )r*  r+  r,  r-  r  r'  rs  r  r  r,
  r)  r5
  r5  r!  r  r  r   r   r   r3   r3   A8  s`         & 3INNN4NNN4OOO> #.  $. . . . . .c      S       %)(?C( ( ( ( ( ( # # # \#   0 0 0 0        r   r3   c                      e Zd ZdZdS )r,   z;Exception to indicate invalid OME-XML or unsupported cases.Nr)  r   r   r   r,   r,   8  s        EEEEr   r,   c                  6   e Zd ZU dZded<   	 ded<   	 ded<   	 ded<   ded	<   d>dZddd?dZddd@dZdAdZdAd Z	e
dBd#            Ze
	 dCdDd'            Ze
dEd)            Ze
	 	 dFdGd,            Ze
dHd.            ZdId1ZdJd3Ze
	 	 dKg d5dLd=            ZdS )Mr+   ah  Create OME-TIFF XML metadata.

    Parameters:
        **metadata:
            Additional OME-XML attributes or elements to be stored.

            Creator:
                Name of creating application. The default is 'tifffile'.
            UUID:
                Unique identifier.

    Examples:
        >>> omexml = OmeXml()
        >>> omexml.addimage(
        ...     dtype='uint16',
        ...     shape=(32, 256, 256),
        ...     storedshape=(32, 1, 1, 256, 256, 1),
        ...     axes='CYX',
        ...     Name='First Image',
        ...     PhysicalSizeX=2.0,
        ...     MapAnnotation={'key': 'value'},
        ...     Dataset={'Name': 'FirstDataset'},
        ... )
        >>> xml = omexml.tostring()
        >>> xml
        '<OME ...<Image ID="Image:0" Name="First Image">...</Image>...</OME>'
        >>> OmeXml.validate(xml)
        True

    r  rk  r   datasetsr   _xmlr   _ifdr   rb   r   r  c                l   |                     d|          }d| _        g | _        g | _        g | _        d|v r"|d                             d          d         }nddlm} t           |                      }t          
                    |ddt           	          }d
}d| d| d| d| d| d| _        d S )NOMEr   r`  r  rT  )uuid1Creatorztifffile.py r  z1http://www.openmicroscopy.org/Schemas/OME/2016-06z{declaration}<OME xmlns="zL" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="r!  z/ome.xsd" UUID="urn:uuid:r	  z&>{datasets}{images}{annotations}</OME>)rY  r@
  rk  r   r>
  r  r  rC
  r   r+   
_attributer   r?
  )rp  r   r  rC
  creatorschemas         r   rs  zOmeXml.__init__8  s   <<x00	 XF#))#..r2DD""""""uuww<<D##i)E)E)E $ 
 
 E!  $*  -3  #	  &-	   				r   N)r  r~   rg   r   r  r  r	
  r  r   c               b  012 t          | j                  }g }|                    d|          }|                    d|          }t          |t          t
          f          r||         }d|v rJddl}|                    |          }d|d         v r	|d         d= |                    |d                    |d= 	 t          j
        |          j        }ddd	d
dddddddd|         }n&# t          $ r}	t          d|d          |	d}	~	ww xY w|                    d|          |k    rt          d|d         d|          d}
|\  }}}}}}|dk    rt          d          |dk    s|dk    st          d          t          d |D                       }t          |          }|dk     st          |          dk    rt          d          ||dk    s|dd         ||dfk    rd}|}
n$|dk    s|dk    r|dd         d||fk    rd }|}
nd!}t          |          |cxk    rd"|v rdnd#k    sn t          | d$          |                    d%d&          ddd'         }|d"|v rdnd#|z
  d         |z   }t          |          t          |          k    sJ n%|                                }t          |          t          |          k    rt          d(          |                    d!          s=|                    d          s(|                    d)          rd"|vst          d*          g }|D ]E}|d+vrt          d,|d          ||v rt          d-|d.          |                    |           F|d"|v rd/nd0k    rt          d1          |dk    r|}
|d2k     rt          d3          |d'         d4k    r*d"|v rt          d5          |                    d4d"          }n|d'         d"k    rt          d6          |d'         |k    s|d7         |k    rt          d8          n|dk    r|}
|d2k     rt          d3          |d         d4k    r*d"|v rt          d5          |                    d4d"          }n|d         d"k    rt          d6          |d         |k    s|d'         |k    rt          d8          ||                    d9                   |k    s||                    d:                   |k    rt          d8          d"|v r?|dt+          |                    d"          |                    d:                             }n|d|                    d:                   }t-          d; |D                       rJi }d<0d=d>d?d@dAdBdC}|                    dDi           }t/          |          D ]\  }}|dEv rw||v rdF||          dG}nd<}||dz
  |         }|r|dHv r||         ||         |f||<   DdHD ])}|0vr#||vr||vr||         ||         |f||<   0|z  0 n*t          dI          0|z  00}d<                    dJ |                                D                       }|                    dKt          | j                   dL           | j                            dMt          | j                   dN| dO           ni }d<}|ddd'         }|                    d%d&          d&dPdQdRdSdTfD ]0|0v r n	t          dU|dV|dW          g 10D ]b}|d"k    r	||v r||                    |                   }nd}|d4k    r|}||
z  }||v r|||         d         z  }1                    |           cd<                    dX t7          01          D                       }d%|v r@|d%         } d<                    01fdY| D                       } || vrt          dZ|          t7          01          D ]7\  }}|                    d[| |          |k    rt          d\| d]|          810                    d4          xx         |
z  cc<   |t          1d^d                   k    rt          d8          g }!|                    d_d<          }"|"rt          0fd`daD                       }#t9          |          D ]z}$t:                              |"|$dbdcdddedfdgdhdidjdk          }%t          j        |$1d^d         dlm          22fdn|#D             \  }&}'}(|!                    do|& dp|' dq|( dr|% ds	           {d<                    |!          })g }*t9          |          D ]f}&dt}+t:                              |                    dud<          |&dvdwdxdydzd{d|d}d~ddddd          }%|*                    d| d|& d|
 dr|% d|+ d           gd<                    |*          },t:                               |dd          }-t:          !                    |dvd|           }.t:                              |dddddddddd          }%|dk    s|dk    r|dk    rdnd}/d|/ dr}/nd<}/| "                    |                    di           d| dL           | #                    |                    d|          |           d<                    |          }| j                            d| dr|. d|- d| d0 d| dr| |/ |% d|, d| j$         d| dL|) d| d           | xj$        |z  c_$        dS )a}	  Add image to OME-XML.

        The OME model can handle up to 9 dimensional images for selected
        axes orders. Refer to the OME-XML specification for details.
        Non-TZCYXS (modulo) dimensions must be after a TZC dimension or
        require an unused TZC dimension.

        Parameters:
            dtype:
                Data type of image array.
            shape:
                Shape of image array.
            storedshape:
                Normalized shape describing how image array is stored in
                TIFF file as (pages, separate_samples, depth, length, width,
                contig_samples).
            axes:
                Character codes for dimensions in `shape`.
                By default, `axes` is determined from the DimensionOrder
                metadata attribute or matched to the `shape` in reverse order
                of TZC(S)YX(S) based on `storedshape`.
                The following codes are supported: 'S' sample, 'X' width,
                'Y' length, 'Z' depth, 'C' channel, 'T' time, 'A' angle,
                'P' phase, 'R' tile, 'H' lifetime, 'E' lambda, 'Q' other.
            **metadata:
                Additional OME-XML attributes or elements to be stored.

                Image/Pixels:
                    Name, Description,
                    DimensionOrder, TypeDescription,
                    PhysicalSizeX, PhysicalSizeXUnit,
                    PhysicalSizeY, PhysicalSizeYUnit,
                    PhysicalSizeZ, PhysicalSizeZUnit,
                    TimeIncrement, TimeIncrementUnit,
                    StructuredAnnotations, BooleanAnnotation, DoubleAnnotation,
                    LongAnnotation, CommentAnnotation, MapAnnotation,
                    Dataset
                Per Plane:
                    DeltaT, DeltaTUnit,
                    ExposureTime, ExposureTimeUnit,
                    PositionX, PositionXUnit,
                    PositionY, PositionYUnit,
                    PositionZ, PositionZUnit.
                Per Channel:
                    Name, AcquisitionMode, Color, ContrastMethod,
                    EmissionWavelength, EmissionWavelengthUnit,
                    ExcitationWavelength, ExcitationWavelengthUnit,
                    Fluor, IlluminationType, NDFilter,
                    PinholeSize, PinholeSizeUnit, PockelCellSetting.

        Raises:
            OmeXmlError: Image format not supported.

        rB
  rn  rq  r   Nre  int8int16r  r  r  uint32r  doublecomplexzdouble-complexbit)rI
  rJ
  r  r  r  rK
  r  float64	complex64
complex128r   z
data type r8  rg  zmetadata Pixels Type z does not match array dtype rW   zImageDepth not supportedzinvalid stored shapec              3  4   K   | ]}t          |          V  d S r   r  r  s     r   r   z"OmeXml.addimage.<locals>.<genexpr>{9  s(      ,,c!ff,,,,,,r   zempty arrays not supportedr  r  r  r  r  r  r  z dimensions not supportedrr  XYCZTrT  axes do not match shapeYXCz"dimensions must end with YX or YXSTZCYXSAPRHEQz
dimension z	multiple z dimensionsr<  rY  z$more than 8 dimensions not supportedr   z$dimensions do not match stored shaper  zinvalid axeszaxes do not match stored shaper}  z!shape does not match stored shaper  r  c              3     K   | ]}|d v V  	dS )APRHEQNr   r+	  s     r   r   z"OmeXml.addimage.<locals>.<genexpr>9  s&      //"rX~//////r   r  anglephaser   lifetimelambdarh  )Ar  r  rZ  Er  TypeDescriptionrX
  zTypeDescription="" r  zmore than 3 modulo dimensionsc           
   3  H   K   | ]\  }\  }}}d | d| d| d|dz
   d	V  dS )z<ModuloAlongz Type="r`
  zStart="0" End="rW   "/>Nr   )r   rv  axtyperw   	typedescrs        r   r   z"OmeXml.addimage.<locals>.<genexpr>9  s}       " " 2B1y0r 0 0& 0 0I 0 0"&(0 0 0" " " " " "r   <AnnotationRef ID="Annotation:rb
  z<XMLAnnotation ID="Annotation:z" Namespace="openmicroscopy.org/omero/dimension/modulo"><Value><Modulo namespace="http://www.openmicroscopy.org/Schemas/Additions/2011-09">z!</Modulo></Value></XMLAnnotation>XYZCTXYZTCXYCTZXYTCZXYTZCzdimension order z not supported (hiaxes=r  c              3  .   K   | ]\  }}d | d| dV  dS )z Size="r	  Nr   )r   rv  rw   s      r   r   z"OmeXml.addimage.<locals>.<genexpr>):  sK       
 
&.b$!B!!$!!!
 
 
 
 
 
r   c              3  Z   K   | ]%}                     |                   d k    !|V  &dS r  r	  )r   rv  dimorderdimsizess     r   r   z"OmeXml.addimage.<locals>.<genexpr>0:  sG       " "HX^^B5G5G,H1,L,L,L,L,L,L" "r   z'metadata DimensionOrder does not match rt  zmetadata Sizer  r  Planec              3  R   K   | ]!}d d                              |          V  "dS r  Nr	  )r   rv  rn
  s     r   r   z"OmeXml.addimage.<locals>.<genexpr>F:  s9      DDXabb\//33DDDDDDr   r  DeltaT
DeltaTUnitExposureTimeExposureTimeUnit	PositionXPositionXUnit	PositionYPositionYUnit	PositionZPositionZUnitF)r  c              3  B   K   | ]}t          |                   V  d S r   r  )r   r  	unraveleds     r   r   z"OmeXml.addimage.<locals>.<genexpr>W:  s/      ??3y|,,??????r   z<Plane TheC="z" TheZ="z" TheT="r	  z/>z<LightPath/>rx  rp  AcquisitionModeColorContrastMethodEmissionWavelengthEmissionWavelengthUnitExcitationWavelengthExcitationWavelengthUnitFluorIlluminationTypeNDFilterPinholeSizePinholeSizeUnitPockelCellSettingz<Channel ID="Channel:r  z" SamplesPerPixel="rj   z
</Channel>AcquisitionDateDescriptionr  SignificantBitsPhysicalSizeXPhysicalSizeXUnitPhysicalSizeYPhysicalSizeYUnitPhysicalSizeZPhysicalSizeZUnitTimeIncrementTimeIncrementUnitfalsetruez Interleaved="Datasetz<ImageRef ID="Image:rb  z<Image ID="Image:z<Pixels ID="Pixels:z" DimensionOrder="z" Type="z<TiffData IFD="z" PlaneCount="z	</Pixels>z</Image>)%r   rk  rY  r   rA  r  rj  deepcopyr  r  r~   ru   r  r,   r   rD   rT  rP  r   r  r  r  r@  r  r   r:  r   r  r  r+   _attributesunravel_index	_elementsrE
  _dataset_annotationsr@
  )3rp  r~   r   r  r  r   r  annotation_refsrj  r  rb  r  separater`  r_  r^  contigr  hiaxesuniquerv  rd  axestypeaxestypedescrr  rd
  r  moduloalongr  rw   sizecr  omedimorder
plane_listplaneattributescztorderr]  
attributesr  rK  r  r   channel_list	lightpathr  elementsru   interleavedrn
  ro
  r
  s3                                                   @@@r   rD  zOmeXml.addimage
9  s]   ~ DK   <<x00<<22hu.. 	'HxKKK}}X..Hx)))X&t,OOHX.///"	MK&&+E   """#&.  EE  	M 	M 	MB5BBBCCL	M <<&&%//8(8 8 8.38 8  
 =H:
HeVUFA::8999A13444,,e,,,,,5zz!88wu~~**:;;;<{{eBCCjVUA,>>> Q		eBCCjQ,>>>"t99AAAAcTkkqAAAA!T"D"D"DEEE",,'7AA%1R%HFt11d:<<=DDt99E

***** ::<<D4yyCJJ&& !:;;;d##H==''H MM%((H .1__!"FGGGF " "^++%&G2&G&G&GHHH<<%&C"&C&C&CDDDb!!!!C4KKqqQ//!"HIII{{ !88$%KLLL8s??d{{(888<<S11DD"X__$%EFFF9&&%)u*<*<$%HIII +=Q"!88$%KLLL8s??d{{(888<<S11DD"X__$%EFFF9((E"I,>,>$%HIIIC!U**eDJJsOO.D.N.N@AAA$;;AC

3CAAABFF+DJJsOO+,F/////// ?	FH H %LL):B??M"6** # #2>>]**$Mb8I$M$M$M		$&	q1uqy)A OQ%ZZ$,RL%(I$Eq		 "' O OA ! 1 1$%VOO$%VOO,4RL%(I,Mq	 (A % #..M"N"NN !&
 NHHF '' " " 6<\\^^" " "  K
 ""KT5E1F1FKKK   ###T5E1F1F # #
 # # #
 
 
 
 FM"LL)733
 	 	H !! " E4EE6EEE    	" 	"BSyyTzzTZZ^^,SyyV||r
1%OOD!!!! 
 
25h2I2I
 
 
 
 

 x''"#34K'' " " " " "(" " "  K [((!FdFF  
 Hh// 	 	HB||K2KK..$66!ABAAAA   7
 	$$%%%'1%%%!""....@AAA
",,w33 	DDDDeDDDDDH:&&  #//# "&### 
 "/8ABB<sKKK	????h???1a!!LALLqLL!LLjLLL    $$u 	 	A&I  ++Y++! $(&*"!#! J$     $+         77<(( ##H.?OO  6?5?? KK''
 

 a<<6A::%-\\''vK9;999KKKLLB'')J)J)J)J	
 	
 	
 	LL0(;;_	
 	
 	
 00     "'   (  	 
       #i  8B      	
 	
 	
  			Z				s   9-C' '
D
1DD
Fr  r  r   c                   d                     | j                  }d                     | j                  }d                     | j                  }|rd| d}|rd}nd}| j                            ||||          }|S )zgReturn OME-XML string.

        Parameters:
            declaration: Include XML declaration.

        r  z<StructuredAnnotations>z</StructuredAnnotations>z&<?xml version="1.0" encoding="UTF-8"?>)r  rk  r   r>
  )r   r>
  rk  r   r?
  rL  )rp  r  r>
  rk  r   declaration_strxmls          r   r  zOmeXml.tostring:  s     774=))%%ggd.// 	O+OOO   	!FOO Oi'#	  
 
 
r   c                *    dt          |           ddS )Nz<tifffile.OmeXml @0xr  rj   r  r  s    r   r!  zOmeXml.__repr__:  s    6bhh66666r   c                   |                                  }	 ddlm} |                    d          }|                    ||          }|                     |ddd                                          }nL# t          $ r Y n@t          $ r4}t          j	        d|j
        j         d| t                     Y d	}~nd	}~ww xY w|S )
zReturn OME-XML string.r   r  T)remove_blank_textr  )r	  pretty_printxml_declarationz<tifffile.OmeXml.__str__> r  N)r  lxmlr  	XMLParserr  r  ImportErrorr  rm  rn  r-  r*  ro  )rp  r
  r  parserr  r  s         r   r5  zOmeXml.__str__:  s   mmoo	""""""__t_<<F##C00D..wT4 !  fhh C  	 	 	D 	 	 	MLS]-CLLsLL       	
 
s   AA4 4
B= 	B=	*B88B=rU  r  c                   t          | t                    st          |           } nd| v sd| v sd| v r| S |                     dd          } |                     dd          } |                     dd          } | S )zReturn escaped string of value.z&amp;z&gt;z&lt;&rj   rk   )r   r   r  rI  s    r   _escapezOmeXml._escape:  s     %%% 	JJEE5FeOOLc7++c6**c6**r   r  ru   r  c                ~    |                      ||          }|dS d| dt                              |           d| dS )z1Return XML formatted element if name in metadata.Nr  rk   rj   </)rY  r+   r
  )r   ru   r  rU  s       r   _elementzOmeXml._element:  sN    
 T7++=2:4::&..//::4::::r   r  c               f      sdS  fd|D             }d                     d |D                       S )zReturn XML formatted elements.r  c              3  N   K   | ]}t                               |          V   d S r   )r+   r
  r   ru   r   s     r   r   z#OmeXml._elements.<locals>.<genexpr> ;  s1      FFFOOHd33FFFFFFr   c              3     K   | ]}||V  	d S r   r   )r   es     r   r   z#OmeXml._elements.<locals>.<genexpr>;  s'      00Qa0q000000r   )r   )r   r  r
  s   `  r   r
  zOmeXml._elements:  sL      	2FFFFFFFww00(000000r   r  r   c               f   |                      ||          }|dS |ut          |t          t          f          r/	 ||         }nO# t          $ r}t	          d|          |d}~ww xY w|dk    r$t          t          |          j        d          d| dt          	                    |           dS )	z3Return XML formatted attribute if name in metadata.Nr  z&list index out of range for attribute r   z is not a list or tupler!  rl
  r	  )
rY  r   rA  r  r  r   r~  r*  r+   r
  )r   ru   r  r  rU  r  s         r   rE
  zOmeXml._attribute;  s     T7++=2%$// 
!%LEE!   $III  E{{+FFF   44336>>%003333s   A 
A%A  A%rc	  c                    sdS  fd|D             }nWt           t          t          f          r            fd|D             }n$t           t                    r fd|D             }d                    d |D                       S )z Return XML formatted attributes.r  Nc              3  N   K   | ]}t                               |          V   d S r   r+   rE
  r
  s     r   r   z%OmeXml._attributes.<locals>.<genexpr>(;  3      NN&++Hd;;NNNNNNr   c              3  N   K   | ]}t                               |          V   d S r   r
  r
  s     r   r   z%OmeXml._attributes.<locals>.<genexpr>+;  r
  r   c              3  P   K   | ] }t                               |          V  !d S r   r
  )r   ru   rc	  r   s     r   r   z%OmeXml._attributes.<locals>.<genexpr>-;  sF        >B!!(D&99     r   c              3     K   | ]}||V  	d S r   r   )r   r  s     r   r   z%OmeXml._attributes.<locals>.<genexpr>0;  s'      22Q2q222222r   )r   rA  r  r  r   )r   rc	  r  r
  s   ``  r   r
  zOmeXml._attributes;  s      	2>NNNNNNNJJ4-00 	'HNNNNNNNJJ$'' 	    FK  J ww22*222222r   r   imagerefc                   t          | j                  }|dS |s|dk    rdS |so|dz  }d| j        |         v r-| j        |                             d| d          | j        |<   n,| j        |                             d| d          | j        |<   dS |                    dd          }|rdt                              |           d	}|                    d
d          }|rdt                              |           d}g }|                     ||           d                    |          }| j                            d| d	| d| | | d	           dS )z%Add Dataset element to self.datasets.Nr   rW   z<AnnotationRefz
</Dataset>rp  r  z Name="r	  r
  <Description></Description>z<Dataset ID="Dataset:rj   )	r   r>
  r  rY  r+   r
  r
  r   r   )rp  r   r
  r  ru   r   r
  r  s           r   r
  zOmeXml._dataset2;  s   DM""4 	EQJJ4 	QJE4=#777'+}U';'C'C$&A&A&A( (e$$ (,}U';'C'C X"9"9"9( (e$ 4 ||FB'' 	54V^^D11444Dll="55 	K{ ; ;KKK  &((O44400E  D     	
 	
 	
 tr   r
  c                P   |                                 D ]\  }}|dvr|st          |t          t          f          s|g}|D ]}d}d}t          |t                    r|                                }|                    dd          }|rdt                              |           d}|                    dd          }|rdt                              |           d}|                    d	|          }|d
k    rCt          |t                    st          d          d |                                 D             }nR|dk    r$t          |                                           g}n(t                              t          |                    g}|                    dt          | j                   d           | j                            d                    d| dt          | j                   d| d|dd                    |          dd| df                     dS )z8Add annotations to self.annotations and annotation_refs.>   MapAnnotationLongAnnotationDoubleAnnotationBooleanAnnotationCommentAnnotationr  r
  r
  r
  rc  z Namespace="r	  Valuer
  zMapAnnotation is not a dictc                    g | ]>\  }}d t                               |           dt                               |           d?S )z<M K="z">z</M>)r+   r
  r   r   r  s      r   r:  z'OmeXml._annotations.<locals>.<listcomp>;  sX        Aq N!2!2MMfnnQ6G6GMMM  r   r
  re
  rb
  rk   z ID="Annotation:rj   z<Value>z</Value>r
  N)r:  r   rA  r  r  rj  r  r+   r
  r   r   r  r   r   r   r   r   )rp  r   r
  ru   rT  rU  	namespacer   s           r   r
  zOmeXml._annotations`;  s   
 %NN,, <	 <	LD& 
 
 
  ftUm44 "  + +	 eT** 6!JJLLE"'))M2">">K" -%~~k::- - - $
 !&		+r : :I  P$O6>>)3L3L$O$O$O	!IIgu55E?**%eT22 H()FGGG $)KKMM  FF 000!%e.44667FF$nnSZZ889F&&OS9I5J5JOOO    ''GG, , ,.1$2B.C.C, ,(, , , (%GGFOO&(LLL	    =+#<	 <	r   T)_schemaomexsdr   assert_r   r
  	list[Any]r   c              d   ddl m} |s|t          j                            t          j                            t                    d          }t          j                            |          r=t          |d          5 }|	                                }ddd           n# 1 swxY w Y   nJddl
}|j                            d          5 }|	                                }ddd           n# 1 swxY w Y   |                    d          r|                    dd	          d
         }	 |                    |                    |                    |                                                               n%# t&          $ r |                    d           Y nw xY w|r|d         |                     d          r|                     dd	          d
         } |                    |           }|r|d                             |           dS t+          |d                             |                    S dS )a2  Return if OME-XML is valid according to XMLSchema.

        Parameters:
            omexml:
                OME-XML string to validate.
            omexsd:
                Content of OME-XSD schema to validate against.
                By default, the 2016-06 OME XMLSchema is downloaded on first
                run.
            assert\_:
                Raise AssertionError if validation fails.
            _schema:
                Internal use.

        Raises:
            AssertionError:
                Validation failed and `assert\_` is *True*.

        r   r
  Nzome.xsdrN  z:https://www.openmicroscopy.org/Schemas/OME/2016-06/ome.xsd   <?xml   >rW   rT  <?xmlrj   T)r
  r  r  r  r   r  __file__r  r  r?  urllib.requestrequesturlopenr  r  r   	XMLSchemar  r  r  r
  r   r  )	r   r
  r
  r
  r  omexsd_pathrq  urllibr  s	            r   r  zOmeXml.validate;  s   8 	 	%~ gllGOOH--y  7>>+.. 
+k400 +B!#+ + + + + + + + + + + + + + + *)))//6  + !#	+ + + + + + + + + + + + + + +
   ** 3dA..r2%OOE$4$4V]]__$E$EFF     % % %t$$$$$%  	3wqz-  )) 2c1--b1##F++D 
""4(((t
++D11222ts7   =BB"%B"C))C-0C-&AE4 4FF)r   rb   r   r  )r~   rg   r   r  r  r	
  r  r   r   rb   r   r  )r  r   r   r   r&  )rU  r  r   r   r   )r   r  ru   r   r  r   r   r   )r   r  r  r   r   r   r  )
r  r   r  rb   r   r  ru   r   r   r   )r   r  rc	  r   r  r   r   r   )r   r   r
  r   r   r  )r   r  r
  r  r   r  rE	  )
r
  r   r
  r   r   r   r
  r
  r   r   )r*  r+  r,  r-  r'  rs  rD  r  r!  r5  r)  r
  r
  r
  rE
  r
  r
  r
  r  r   r   r   r+   r+   8  s
         > !&#IIIIII%
 %
 %
 %
Z  g  g  g  g  g  g R /4      67 7 7 7   ( 	 	 	 \	 CG; ; ; ; \; 1 1 1 \1 
 !4 4 4 4 \42 3 3 3 \3(, , , ,\A A A AF   $	>  > > > > > \> > >r   r+   c                  P    e Zd ZU dZded<   ded<   dd	ZddZddZddZddZ	dS )CompressionCodeczMap :py:class:`COMPRESSION` value to encode or decode function.

    Parameters:
        encode: If *True*, return encode functions, else decode functions.

    dict[int, Callable[..., Any]]_codecsr   _encoderm  r   r  c                J    dt           i| _        t          |          | _        d S r  identityfuncr
  r   r
  rp  rm  s     r   rs  zCompressionCodec.__init__;      <(F||r   rn   r   Callable[..., Any]c                  || j         v r| j         |         S 	 |dk    r#| j        rt          j        }nt          j        }n|dv r.| j        r|dv rt
          t          j        }nt          j        }n|dv rt          t          d          r4t          j	        j
        r#| j        rt          j        }nCt          j        }n5t          t          d          r4t          j        j
        r#| j        rt          j        }nt          j        }n	 ddlm} n# t$          $ r d	d l}Y nw xY w| j        r	|j        }n|j        }n|d
k    r#| j        rt          j        }nt          j        }n|dv r#| j        rt          j        }nut          j        }ng|dk    r#| j        rt          j        }nLt          j        }n>|dk    r#| j        rt          j        }n#t          j        }n|dk    r~t          t          d          r4t          j        j
        r#| j        rt          j        }nt          j        }n	 ddlm} n# t$          $ r d	d l}Y nw xY w| j        r	|j        }n|j        }n|dk    r#| j        rt          j        }nvt          j        }nh|dv r#| j        rt          j         }nOt          j!        }nA|dk    r#| j        rt          j"        }n&t          j#        }n|dv rzt          t          d          r2t          j$        j
        r!| j        rt          j%        }nt          j&        }n	 ddlm} n# t$          $ r d	d l}Y nw xY w| j        r|j%        }n|j&        }n|dv r!| j        rt          j'        }nt          j(        }nu|dv r| j        st          j)        }n]|dv r!| j        rt          j*        }nEt          j+        }n8	 tY          |          d}n# tZ          $ r | d}Y nw xY wt]          |          nf# t^          t$          f$ r%}t]          tY          |          d          |d }~wt
          $ r%}t]          tY          |          d          |d }~ww xY w|| j         |<   |S )Nr  >   r  r  r  >   r  r  >   rY  r   r"  DEFLATEr  rW   rX   r   r  r  r  r  r!  LZMAr  >   r  r  r  >   r  n  ZSTD>   r  o  rA  >   r  r  r8  z is not a known COMPRESSION# requires the 'imagecodecs' package not implemented)0r
  r
  r/  
lzw_encode
lzw_decoder  jpeg_encoderq  r;  r
  	availabledeflate_encodedeflate_decoder  zlib_encodezlib_decoder  rY   r
  packbits_encodepackbits_decodejpeg2k_encodejpeg2k_decodelerc_encodelerc_decodejpeg8_encodejpeg8_decoder
  lzma_encodelzma_decode
png_encode
png_decodejpegxr_encodejpegxr_decodejetraw_encodejetraw_decoder
  zstd_encodezstd_decodewebp_encoderQ  
eer_decodejpegxl_encodejpegxl_decoder    r   r  r?  )rp  rn   codecrY   r  r  s         r   rY  zCompressionCodec.__getitem__;  sL   $,<$$L	M axx< 3'2EE'2EE%%< 4j((11'3EE'3EE)))K339#+59
 | ; + : + :K0095@5E5O9 | 8 + 7 + 7,2222222& , , ,++++++, | 9 , 8 , 8< 8'7EE'7EE444< 6'5EE'5EE< 4'3EE'3EE< 5'4EE'4EE;// 9K4D4N 9| 8 + 7 + 7,2222222& , , ,++++++, | 9 , 8 , 8< 3'2EE'2EE&&< 6'5EE'5EE< 6'5EE'5EE&&;// 9K4D4N 9| 8 + 7 + 7,2222222& , , ,++++++, | 9 , 8 , 8&&< 4'3EE'3EE---dl-#.&&< 6'5EE'5EE>(--???CC! > > > ===CCC>smm#, 	 	 	s##MMM  # 	M 	M 	Mk#..BBBCCL	M!Ss   C1O6 
D O6 D"O6 !D""DO6 0H7 6O6 7IO6 IC O6 )L0 /O6 0M>O6  MA<O6 >O O6 O# O6 "O##O6 6Q P''Q4 QQrb   c               <    	 | |          n# t           $ r Y dS w xY wdS NFTr  rX  s     r   r  zCompressionCodec.__contains__<  9    	III 	 	 	55	t    
Iterator[int]c              #     K   dV  d S r  r   r  s    r   rd  zCompressionCodec.__iter__<        r   c                    dS r  r   r  s    r   r  zCompressionCodec.__len__<  r
  r   Nrm  r   r   r  rn   r   r   r
  rn   rb   r   r   r   r'  r  
r*  r+  r,  r-  r'  rs  rY  r  rd  r  r   r   r   r
  r
  ;  s           +***MMM$ $ $ $R R R Rh           r   r
  c                  P    e Zd ZU dZded<   ded<   dd	ZddZddZddZddZ	dS )PredictorCodeczMap :py:class:`PREDICTOR` value to encode or decode function.

    Parameters:
        encode: If *True*, return encode functions, else decode functions.

    r
  r
  r   r
  rm  r   r  c                J    dt           i| _        t          |          | _        d S r  r
  r
  s     r   rs  zPredictorCodec.__init__<  r
  r   rn   r   r
  c                  || j         v r| j         |         S 	 |dk    r!| j        rt          j        }nt          j        }n|dk    r!| j        rt          j        }n{t          j        }nn|dk    r| j        rdd}n\dd}nW|dk    r| j        rdd}nEdd	}n@|d
k    r| j        rdd}n.dd}n)|dk    r| j        rdd}ndd}nt          | d          n_# t          $ r%}t          t          |          d          |d }~wt          $ r%}t          t          |          d          |d }~ww xY w|| j         |<   |S )Nr  r   r  rT  c                2    t          j        | ||d          S Nr  r  r   distr/  delta_encoder   r  r   s      r   r!  z)PredictorCodec.__getitem__.<locals>.codec<  %    *7 t1      r   c                2    t          j        | ||d          S r5  r/  delta_decoder:  s      r   r!  z)PredictorCodec.__getitem__.<locals>.codec<  r;  r   r  c                2    t          j        | ||d          S Nr  r6  r8  r:  s      r   r!  z)PredictorCodec.__getitem__.<locals>.codec<  r;  r   c                2    t          j        | ||d          S r@  r=  r:  s      r   r!  z)PredictorCodec.__getitem__.<locals>.codec<  r;  r   r  c                2    t          j        | ||d          S r5  r/  floatpred_encoder:  s      r   r!  z)PredictorCodec.__getitem__.<locals>.codec<  %    *; t1      r   c                2    t          j        | ||d          S r5  r/  floatpred_decoder:  s      r   r!  z)PredictorCodec.__getitem__.<locals>.codec<  rE  r   r  c                2    t          j        | ||d          S r@  rC  r:  s      r   r!  z)PredictorCodec.__getitem__.<locals>.codec<  rE  r   c                2    t          j        | ||d          S r@  rG  r:  s      r   r!  z)PredictorCodec.__getitem__.<locals>.codec<  rE  r   z is not a known PREDICTORr  r  )rT  N)r
  r
  r/  r9  r>  rD  rH  r  r?  r(   r  )rp  rn   r!  r  s       r   rY  zPredictorCodec.__getitem__<  s7   $,<$$N	Kaxx< 5'4EE'4EE< 9'8EE'8EE<         
 <         
 <         
 <          #@@@AAA 	 	 	S>>KKK  # 	K 	K 	Kinn@@@AAsJ	K!Ss$   B<C 
D1 C??D1 D,,D1rb   c               <    	 | |          n# t           $ r Y dS w xY wdS r#  r$  rX  s     r   r  zPredictorCodec.__contains__<  r%  r&  r'  c              #     K   dV  d S r  r   r  s    r   rd  zPredictorCodec.__iter__=  r)  r   c                    dS r  r   r  s    r   r  zPredictorCodec.__len__=  r
  r   Nr+  r,  r-  r.  r  r/  r   r   r   r1  r1  <  s           +***MMM$ $ $ $T T T Tl           r   r1  c                  |    e Zd ZdZdZ	 dZ	 dZ	 dZ	 dZ	 dZ		 dZ
	 d	Z	 d
Z	 dZ	 dZ	 dZ	 dZ	 dZ	 dZ	 dZ	 dZ	 dZdS )r   zTIFF tag data types.rW   r  r   r  r  r  r  rY  r<  r  rY  r  r  r  r  r  r  r  N)r*  r+  r,  r-  BYTEASCIISHORTLONGRATIONALSBYTE	UNDEFINEDSSHORTSLONG	SRATIONALFLOATDOUBLEr}  UNICODECOMPLEXLONG8SLONG8IFD8r   r   r   r   r   =  s        D!EFE"D"HNEI/F E ILE0F0
C%G)G3E,F*D//r   r   c                  4   e Zd ZdZdZ	 dZdZdZdZ	 dZ	dZ
	 d	Z	 d
ZdZdZdZdZdZ	 dZdZdZdZdZdZdZ	 dZdZdZdZdZdZdZdZ dZ!d Z"	 d!Z#	 d"Z$	 d#Z%	 d$Z&d%Z'd&Z(d'Z)d(Z*	 d)Z+d*Z,d+Z-d,Z.d-Z/d.Z0	 d/Z1d0Z2	 d1Z3d2Z4d3Z5	 d4Z6	 d5Z7	 d6Z8	 d7Z9	 d8Z:	 d9Z;	 d:Z<	 d;Z=d<Z>d=Z?dBd@Z@dAS )Cr    zLValues of Compression tag.

    Compression scheme used on image data.

    rW   r  r   r  r  r  r  rY  r<  r  c   g   r  r  i  i  i  i  i  i  r  i)  i  i  i  i  i  i  r"  i  r  r  r  r  ie  it  iu  i  r  i  i  i  i  i  r  r  r!  r
  r   r  r  r  r  r  r  r   r  rx  r  rB  r   r   c                    | dk    S r  r   r  s    r   rf  zCOMPRESSION.__bool__=      axr   Nr  )Ar*  r+  r,  r-  r  CCITTRLECCITT_T4CCITT_T6LZWr!  JPEGADOBE_DEFLATEJBIG_BW
JBIG_COLORJPEG_99IMPACJ	KODAK_262JPEGXR_NDPINEXTSONY_ARW
PACKED_RAWSAMSUNG_SRWCCIRLEWSAMSUNG_SRW2PACKBITSTHUNDERSCANIT8CTPADIT8LWIT8MPIT8BL	PIXARFILMPIXARLOGr
  DCSAPERIO_JP2000_YCBCJPEG_2000_LOSSYAPERIO_JP2000_RGBALT_JPEGJBIGSGILOGSGILOG24LURADOCJPEG2000	NIKON_NEFJBIG2
MDI_BINARYMDI_PROGRESSIVE
MDI_VECTORLERC
JPEG_LOSSYr
  ZSTD_DEPRECATEDWEBP_DEPRECATEDPNGJPEGXRJETRAWr
  WEBPJPEGXLPIXTIFF
JPEGXL_DNGEER_V0EER_V1EER_V2rf  r   r   r   r    r    4=  s         D#HHH
CEDMGJGFIK"DHJKGLH&KHEEEIHG
C)O('H
 DFHGHIEJOJD0JD,OO
CAF/FDDFGJFFF     r   r    c                  <    e Zd ZdZdZ	 dZ	 dZ	 dZdZdZ	dZ
ddZdS )r(   zuValues of Predictor tag.

    A mathematical operator that is applied to the image data before
    compression.

    rW   r  r   r  r  r  r  r   r   c                    | dk    S r  r   r  s    r   rf  zPREDICTOR.__bool__=  rd  r   Nr  )r*  r+  r,  r-  r  
HORIZONTALFLOATINGPOINTHORIZONTALX2HORIZONTALX4FLOATINGPOINTX2FLOATINGPOINTX4rf  r   r   r   r(   r(   =  s`          D.J"M1LLOO     r   r(   c                  `    e Zd ZdZdZ	 dZ	 dZ	 dZ	 dZdZ		 dZ
	 d	Zd
ZdZdZ	 dZdZdZdZdZdS )r&   zQValues of PhotometricInterpretation tag.

    The color space of the image.

    r   rW   r  r   r  r  r  rY  r<  r  #  L  M  r    /  N)r*  r+  r,  r-  rM  rL  rN  rP  rd  r  rO  CIELABICCLABITULABrc  LOGLLOGLUV
LINEAR_RAW	DEPTH_MAPSEMANTIC_MASKr   r   r   r&   r&   =  s          JAJA
C1G9DIGEJFFF
CDFJIMMMr   r&   c                  :    e Zd ZdZdZ	 dZ	 dZ	 dZ	 dZ	 dZ		 dZ
d	S )
r"   zWValues of NewSubfileType tag.

    A general indication of the kind of the image.

    r   rW   r  r  rY  r  r  N)r*  r+  r,  r-  rU  REDUCEDIMAGEPAGErd  MACROENHANCEDDNGr   r   r   r"   r"   =  sO          I-L?D3D7EJH.
CCCr   r"   c                  "    e Zd ZdZdZdZdZdZdS )r$   z%Values of deprecated SubfileType tag.r   rW   r  r   N)r*  r+  r,  r-  rU  IMAGEr  r  r   r   r   r$   r$   =  s(        //IELDDDr   r$   c                      e Zd ZdZdZ	 dZdS )r#   zLValues of FillOrder tag.

    The logical order of bits within a byte.

    rW   r  N)r*  r+  r,  r-  MSB2LSBLSB2MSBr   r   r   r#   r#   =  s)          GIG??r   r#   c                  2    e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zd
S )r%   zhValues of Orientation tag.

    The orientation of the image with respect to the rows and columns.

    rW   r  r   r  r  r  r  rY  N)r*  r+  r,  r-  TOPLEFTTOPRIGHTBOTRIGHTBOTLEFTLEFTTOPRIGHTTOPRIGHTBOTLEFTBOTr   r   r   r%   r%   =  sB          GHHGGHHGGGr   r%   c                      e Zd ZdZdZ	 dZdS )r'   z`Values of PlanarConfiguration tag.

    Specifies how components of each pixel are stored.

    rW   r  N)r*  r+  r,  r-  rQ  rR  r   r   r   r'   r'   >  s)          FEHAAr   r'   c                  8    e Zd ZdZdZ	 dZ	 dZ	 dZ	 dZ	 dd	Z	d
S )r)   zaValues of ResolutionUnit tag.

    The unit of measurement for XResolution and YResolution.

    rW   r  r   r  r  r   r   c                    | dk    S r  r   r  s    r   rf  zRESUNIT.__bool__*>  rd  r   Nr  )
r*  r+  r,  r-  r  rt  
CENTIMETER
MILLIMETER
MICROMETERrf  r   r   r   r)   r)   >  s\          D*DJJJ     r   r)   c                  "    e Zd ZdZdZ	 dZ	 dZdS )r!   zUValues of ExtraSamples tag.

    Interpretation of extra components in a pixel.

    r   rW   r  N)r*  r+  r,  r-  UNSPECIFIED
ASSOCALPHA
UNASSALPHAr   r   r   r!   r!   .>  s1          KJ9J""r   r!   c                  4    e Zd ZdZdZ	 dZ	 dZ	 dZ	 dZ	 dZ	dS )	r*   zGValues of SampleFormat tag.

    Data type of samples in a pixel.

    rW   r  r   r  r  r  N)
r*  r+  r,  r-  r)  INTr%  VOID
COMPLEXINTCOMPLEXIEEEFPr   r   r   r*   r*   =>  sI          D
CFDJM!!r   r*   c                  (    e Zd ZdZdZ	 dZ	 dZ	 dZdS )r   zMZarrStore chunk modes.

    Specifies how to chunk data in Zarr stores.

    r   rW   r  r   N)r*  r+  r,  r-  STRILEPLANEr  FILEr   r   r   r   r   R>  s9          F!ED!D!!r   r   c                     e Zd ZU dZedWd            ZedWd            ZedWd            ZedWd            ZedWd            Z	edXd
            Z
edYd            ZedZd            ZedZd            ZedZd            Zed[d            Zed\d            ZedXd            ZedXd            ZedXd            ZedXd            Zed]d            Zed[d            Zed^d            Zed_d            Zed`d!            Zed`d"            Zed`d#            Zed`d$            Zedad&            Zedbd(            Zedbd)            Zedcd+            Z eddd-            Z!eded/            Z"eded0            Z#e$dbd1            Z%e$dfd3            Z&e$dgd5            Z'e$dgd6            Z(e$dhd8            Z)e$d[d9            Z*e$dbd:            Z+e$d[d;            Z,e$d[d<            Z-e$d[d=            Z.e$d[d>            Z/e$d[d?            Z0ed@             Z1edA             Z2e$dB             Z3e$dfdC            Z4e$dfdD            Z5e$dfdE            Z6e$dfdF            Z7e$dgdG            Z8e$dgdH            Z9e$didJ            Z:e$dbdK            Z;e$djdM            Z<e$dkdO            Z=edldQ            Z>edldR            Z?edldS            Z@dTZAdPeBdU<   dVS )mrM   z@Delay-loaded constants, accessible via :py:attr:`TIFF` instance.r   r   c                4    t          ddddddddd	d

  
        S )z!32-bit little-endian TIFF format.r[  rk   r  r  r  <Hr  r  z<I4s
rJ  r   rJ  rl  r  rI  rK  r  r  r  r   r  s    r   rf  z_TIFF.CLASSIC_LE}>  9      
 
 
 	
r   c                4    t          ddddddddd	d

  
        S )z32-bit big-endian TIFF format.r[  rj   r  z>Ir  >Hr  >HHz>I4sr  r  r  s    r   rh  z_TIFF.CLASSIC_BE>  r  r   c                4    t          dddddddddd
  
        S )	z!64-bit little-endian TIFF format.rX  rk   rY  rv  rA	  r  z<Q8sr  r  r  s    r   re  z_TIFF.BIG_LE>  r  r   c                4    t          dddddddddd
  
        S )	z64-bit big-endian TIFF format.rX  rj   rY  z>QrA	  r  z>Q8sr  r  r  s    r   rg  z_TIFF.BIG_BE>  r  r   c                4    t          ddddddddd	d

  
        S )z532-bit little-endian TIFF format with 64-bit offsets.r[  rk   rY  rv  r  r  r  r  z<I8sr  r  r  r  s    r   rA  z_TIFF.NDPI_LE>  r  r   r   c                     t          d          S )z?Registry of TIFF tag codes and names from TIFF6, TIFF/EP, EXIF.(  )rY  ProcessingSoftware)r  NewSubfileType)r  SubfileType)r  
ImageWidth)r  ImageLength)r  BitsPerSample)r  Compression)r  PhotometricInterpretation)i  Thresholding)i  	CellWidth)i	  
CellLength)
  	FillOrder)i  DocumentName)r  ImageDescription)r  rE  )i  rF  )r  StripOffsets)  Orientation)r  ry  )r  RowsPerStrip)r  StripByteCounts)i  MinSampleValue)i  MaxSampleValue)r  XResolution)r   YResolution)r  PlanarConfiguration)r  PageName)i  	XPosition)i  	YPosition)   FreeOffsets)i!  FreeByteCounts)i"  GrayResponseUnit)i#  GrayResponseCurve)i$  	T4Options)i%  	T6Options)r  ResolutionUnit)i)  
PageNumber)i,  ColorResponseUnit)r  TransferFunction)r  rG  )r  rn  )i;  Artist)i<  HostComputer)r  	Predictor)i>  
WhitePoint)i?  PrimaryChromaticities)r  ColorMap)iA  HalftoneHints)r  	TileWidth)r  
TileLength)r  TileOffsets)r  TileByteCounts)iF  BadFaxLines)iG  CleanFaxData)iH  ConsecutiveBadFaxLines)r  SubIFDs)iL  InkSet)iM  InkNames)iN  NumberOfInks)iP  DotRange)iQ  TargetPrinter)r  ExtraSamples)r  SampleFormat)iT  SMinSampleValue)iU  SMaxSampleValue)iV  TransferRange)iW  ClipPath)iX  XClipPathUnits)iY  YClipPathUnits)iZ  Indexed)r  
JPEGTables)i_  OPIProxy)  GlobalParametersIFD)i  ProfileType)i  
FaxProfile)i  CodingMethods)i  VersionYear)i  
ModeNumber)i  Decode)i  DefaultImageColor)i  
T82Options)i  r*  )r  JPEGProc)r
  JPEGInterchangeFormat)r  JPEGInterchangeFormatLength)i  JPEGRestartInterval)i  JPEGLosslessPredictors)i  JPEGPointTransforms)i  JPEGQTables)i  JPEGDCTables)i	  JPEGACTables)i  YCbCrCoefficients)r  YCbCrSubSampling)  YCbCrPositioning)r  ReferenceBlackWhite)i/  StripRowCounts)r  XMP)i  GDIGamma)i  ICCProfileDescriptor)i  SRGBRenderingIntent)i   
ImageTitle)i  SiffCompress)i  USPTO_Miscellaneous)r<  AndorId)i  AndorTemperature)i  AndorExposureTime)i  AndorKineticCycleTime)i  AndorAccumulations)i  AndorAcquisitionCycleTime)i  AndorReadoutTime)i  AndorPhotonCounting)i  AndorEmDacLevel)i  AndorFrames)i   AndorHorizontalFlip)i!  AndorVerticalFlip)i"  AndorClockwise)i#  AndorCounterClockwise)i(  AndorVerticalClockVoltage)i)  AndorVerticalShiftSpeed)i+  AndorPreAmpSetting)i,  AndorCameraSerial)i/  AndorActualTemperature)i0  AndorBaselineClamp)i1  AndorPrescans)i2  
AndorModel)i3  AndorChipSizeX)i4  AndorChipSizeY)iP  AndorBaselineOffset)if  AndorSoftwareVersion)iFG  Rating)iGG  
XP_DIP_XML)iHG  
StitchInfo)iIG  RatingPercent)iP  ResolutionXUnit)iP  ResolutionYUnit)iP  ResolutionXLengthUnit)iP  ResolutionYLengthUnit)iP  
PrintFlags)iP  PrintFlagsVersion)iP  PrintFlagsCrop)iP  PrintFlagsBleedWidth)i	P  PrintFlagsBleedWidthScale)i
P  HalftoneLPI)iP  HalftoneLPIUnit)iP  HalftoneDegree)iP  HalftoneShape)iP  HalftoneMisc)iP  HalftoneScreen)iP  JPEGQuality)iP  GridSize)iP  ThumbnailFormat)iP  ThumbnailWidth)iP  ThumbnailHeight)iP  ThumbnailColorDepth)iP  ThumbnailPlanes)iP  ThumbnailRawBytes)iP  ThumbnailSize)iP  ThumbnailCompressedSize)iP  ColorTransferFunction)iP  ThumbnailData)i P  ThumbnailImageWidth)i!P  ThumbnailImageHeight)i"P  ThumbnailBitsPerSample)i#P  ThumbnailCompression)i$P  ThumbnailPhotometricInterp)i%P  ThumbnailImageDescription)i&P  ThumbnailEquipMake)i'P  ThumbnailEquipModel)i(P  ThumbnailStripOffsets)i)P  ThumbnailOrientation)i*P  ThumbnailSamplesPerPixel)i+P  ThumbnailRowsPerStrip)i,P  ThumbnailStripBytesCount)i-P  ThumbnailResolutionX)i.P  ThumbnailResolutionY)i/P  ThumbnailPlanarConfig)i0P  ThumbnailResolutionUnit)i1P  ThumbnailTransferFunction)i2P  ThumbnailSoftwareUsed)i3P  ThumbnailDateTime)i4P  ThumbnailArtist)i5P  ThumbnailWhitePoint)i6P  ThumbnailPrimaryChromaticities)i7P  ThumbnailYCbCrCoefficients)i8P  ThumbnailYCbCrSubsampling)i9P  ThumbnailYCbCrPositioning)i:P  ThumbnailRefBlackWhite)i;P  ThumbnailCopyRight)iAP  InteroperabilityIndex)iBP  InteroperabilityVersion)iP  LuminanceTable)iP  ChrominanceTable)i Q  
FrameDelay)iQ  	LoopCount)iQ  GlobalPalette)iQ  IndexBackground)iQ  IndexTransparent)iQ  	PixelUnit)iQ  PixelPerUnitX)iQ  PixelPerUnitY)iQ  PaletteHistogram)rl  SonyRawFileType)i2p  VignettingCorrParams)i5p  ChromaticAberrationCorrParams)i7p  DistortionCorrParams)i  ImageID)i  WangTag1)i  WangAnnotation)i  WangTag3)i  WangTag4)i  ImageReferencePoints)i  RegionXformTackPoint)i  WarpQuadrilateral)i  AffineTransformMat)i  Matteing)i  DataType)r  
ImageDepth)r  	TileDepth)i  ImageFullWidth)i  ImageFullLength)i  TextureFormat)i  TextureWrapModes)i  FieldOfViewCotangent)i  MatrixWorldToScreen)i  MatrixWorldToCamera)i}  Model2)i  CFARepeatPatternDim)i  
CFAPattern)i  BatteryLevel)i  KodakIFD)i  ru
  )i  FNumber)i  	Copyright)r  	MDFileTag)i  MDScalePixel)i  MDColorTable)i  	MDLabName)i  MDSampleInfo)i  
MDPrepDate)i  
MDPrepTime)i  MDFileUnits)i  NiffRotation)i  NiffNavyCompression)i  NiffTileIndex)r  
OlympusINI)rU  ModelPixelScaleTag)r  
OlympusSIS)i5  AdventScale)i6  AdventRevision)r  UIC1tag)r  UIC2tag)r  UIC3tag)r  UIC4tag)黃  IPTCNAA)iB  ExtendedTagsOffset)i~  IntergraphPacketData)i  IntergraphFlagRegisters)rR  IntergraphMatrixTag)i  INGRReserved)rW  ModelTiepointTag)郄  
LeicaMagic)i  Site)i  ColorSequence)i  	IT8Header)i  RasterPadding)i  BitsPerRunLength)i  BitsPerExtendedRunLength)i  
ColorTable)i  ImageColorIndicator)i  BackgroundColorIndicator)i  ImageColorValue)i  BackgroundColorValue)i  PixelIntensityRange)i  TransparencyIndicator)i  ColorCharacterization)i  HCUsage)i  TrapIndicator)i  CMYKEquivalent)r  CZ_SEM)ih  	AFCP_IPTC)i  PixelMagicJBIGOptions)iׅ  JPLCartoIFD)iJ  IPLAB)rY  ModelTransformationTag)i  WB_GRGBLevels)i  LeafData)r  	MM_Header)r  MM_Stamp);  
MM_Unknown)iI  ImageResources)R  MM_UserBlock)r}  
CZ_LSMINFO)i  ExifTag)r  InterColorProfile)r  FEI_SFEG)r  
FEI_HELIOS)i{  	FEI_TITAN)i  FXExtensions)i  MultiProfiles)i  
SharedData)i  
T88Options)i  MarCCD)i  
ImageLayer)rM  GeoKeyDirectoryTag)鰇  GeoDoubleParamsTag)rQ  GeoAsciiParamsTag)i  JBIGOptions)i  r  )i"  ExposureProgram)i$  SpectralSensitivity)%  GPSTag)r  OlympusSIS2)'  ISOSpeedRatings)r"  PhotographicSensitivity)i(  OECF)i)  	Interlace)i*  TimeZoneOffset)i+  SelfTimerMode)i0  SensitivityType)i1  StandardOutputSensitivity)i2  RecommendedExposureIndex)i3  ISOSpeed)i4  ISOSpeedLatitudeyyy)i5  ISOSpeedLatitudezzz)i\  HylaFAXFaxRecvParams)i]  HylaFAXFaxSubAddress)i^  HylaFAXFaxRecvTime)i_  FaxDcs)iq  FedexEDR)i  
LeafSubIFD)i  	Aphelion1)i  	Aphelion2)i  AphelionInternal)   ExifVersion)  DateTimeOriginal)  DateTimeDigitized)	  GooglePlusUploadCode)  
OffsetTime)i  OffsetTimeOriginal)i  OffsetTimeDigitized)r8  TVX_Unknown)i  TVX_NumExposure)i  TVX_NumBackground)r:  TVX_ExposureTime)r<  TVX_BackgroundTime)i  rD  )r>  
TVX_SubBpp)i
  TVX_SubWide)i  TVX_SubHigh)i  TVX_BlackLevel)i  TVX_DarkCurrent)i  TVX_ReadNoise)i  TVX_DarkCurrentNoise)r@  TVX_BeamMonitor)i   TVX_UserVariables)i  ComponentsConfiguration)i  CompressedBitsPerPixel)i  ShutterSpeedValue)i  ApertureValue)i  BrightnessValue)i  ExposureBiasValue)i  MaxApertureValue)i  SubjectDistance)i  MeteringMode)i  LightSource)i	  Flash)i
  FocalLength)i  FlashEnergy)i  SpatialFrequencyResponse)i  Noise)i  FocalPlaneXResolution)i  FocalPlaneYResolution)i  FocalPlaneResolutionUnit)i  ImageNumber)i  SecurityClassification)i  ImageHistory)i  SubjectLocation)i  ExposureIndex)r  TIFFEPStandardID)i  SensingMethod)i:  CIP3DataFile)i;  	CIP3Sheet)i<  CIP3Side)i?  StoNits)i|  	MakerNote)i  UserComment)i  
SubsecTime)i  SubsecTimeOriginal)i  SubsecTimeDigitized)i/  MODIText)i0  MODIOLEPropertySetStorage)i1  MODIPositioning)r  AgilentBinary)iF  AgilentString)r  TVIPS)iK  TVIPS1)iL  TVIPS2)\  ImageSourceData)i   Temperature)i  Humidity)i  Pressure)i  
WaterDepth)i  Acceleration)i  CameraElevationAngle)i@  XPos)A  YPos)B  ZPos)r  MC_IpWinScal)r  	RecipName)r  RecipNumber)iC  
SenderName)iD  Routing)iE  CallerId)iF  TSID)iG  CSID)iH  FaxTime)餜  MC_IdOld)i  
MC_Unknown)  InteroperabilityTag)i  XPTitle)i  	XPComment)i  XPAuthor)i  
XPKeywords)i  	XPSubject)i   FlashpixVersion)i  
ColorSpace)i  PixelXDimension)i  PixelYDimension)i  RelatedSoundFile)i  SamsungRawPointersOffset)i  SamsungRawPointersLength)i  SamsungRawByteOrder)i  SamsungRawUnknown)i  r^  )i  r_  )i  r`  )i  ra  )i  rb  )i  rc  )i  rd  )i  re  )i  rf  )i  rg  )i  zExposureIndex )i  zTIFF-EPStandardID)i  rj  )i   
FileSource)i  	SceneType)i  r  )i  CustomRendered)i  ExposureMode)i  WhiteBalance)i  DigitalZoomRatio)i  FocalLengthIn35mmFilm)i  SceneCaptureType)i  GainControl)i  Contrast)i	  
Saturation)i
  	Sharpness)i  DeviceSettingDescription)i  SubjectDistanceRange)i   ImageUniqueID)i0  CameraOwnerName)i1  BodySerialNumber)i2  LensSpecification)i3  LensMake)i4  	LensModel)i5  LensSerialNumber)i`  CompositeImage)ia  SourceImageNumberCompositeImage)ib  !SourceExposureTimesCompositeImage)r  GDAL_METADATA)r  GDAL_NODATA)i   Gamma)r  NIHImageHeader)i  ExpandSoftware)i  
ExpandLens)i¯  
ExpandFilm)iï  ExpandFilterLens)iį  ExpandScanner)iů  ExpandFlashLamp)i  PixelFormat)i  Transformation)i  Uncompressed)i  	ImageType)i  r  )i  ImageHeight)i  WidthResolution)i  HeightResolution)i  ImageOffset)i  ImageByteCount)i¼  AlphaOffset)iü  AlphaByteCount)iļ  ImageDataDiscard)iż  AlphaDataDiscard)iS  	KodakAPP3)i'  OceScanjobDescription)i(  OceApplicationSelector)i)  OceIdentificationNumber)i*  OceImageLogicCharacteristics)iO  Annotations)r  MC_Id)iq  MC_XYPosition)ir  MC_ZPosition)is  MC_XYCalibration)it  MC_LensCharacteristics)iu  MC_ChannelName)iv  MC_ExcitationWavelength)iw  MC_TimeStamp)x  MC_FrameProperties)i  PrintImageMatching)i?  PCO_RAW)is  OriginalFileName)i  USPTO_OriginalContentType)i  USPTO_RotationCode)i  CR2Unknown1)i  CR2Unknown2)i  CR2CFAPattern)r  LercParameters)r  
DNGVersion)i  DNGBackwardVersion)i  UniqueCameraModel)i  LocalizedCameraModel)i  CFAPlaneColor)i  	CFALayout)i  LinearizationTable)i  BlackLevelRepeatDim)i  
BlackLevel)i  BlackLevelDeltaH)i  BlackLevelDeltaV)i  
WhiteLevel)i  DefaultScale)i  DefaultCropOrigin)i   DefaultCropSize)i!  ColorMatrix1)i"  ColorMatrix2)i#  CameraCalibration1)i$  CameraCalibration2)i%  ReductionMatrix1)i&  ReductionMatrix2)i'  AnalogBalance)i(  AsShotNeutral)i)  AsShotWhiteXY)i*  BaselineExposure)i+  BaselineNoise)i,  BaselineSharpness)i-  BayerGreenSplit)i.  LinearResponseLimit)i/  CameraSerialNumber)i0  LensInfo)i1  ChromaBlurRadius)i2  AntiAliasStrength)i3  ShadowScale)i4  DNGPrivateData)i5  MakerNoteSafety)i@  RawImageSegmentation)iZ  CalibrationIlluminant1)i[  CalibrationIlluminant2)i\  BestQualityScale)i]  RawDataUniqueID)i`  AliasLayerMetadata)i  OriginalRawFileName)i  OriginalRawFileData)i  
ActiveArea)i  MaskedAreas)i  AsShotICCProfile)i  AsShotPreProfileMatrix)i  CurrentICCProfile)i  CurrentPreProfileMatrix)r  IJMetadataByteCounts)r  
IJMetadata)r[  RPCCoefficientTag)i  ColorimetricReference)i  SRawType)i  PanasonicTitle)i  PanasonicTitle2)i  RSID)i  GEO_METADATA)i  CameraCalibrationSignature)i  ProfileCalibrationSignature)i  
ProfileIFD)i  AsShotProfileName)i  NoiseReductionApplied)i  ProfileName)i  ProfileHueSatMapDims)i  ProfileHueSatMapData1)i  ProfileHueSatMapData2)i  ProfileToneCurve)i  ProfileEmbedPolicy)i  ProfileCopyright)i  ForwardMatrix1)i  ForwardMatrix2)i  PreviewApplicationName)i  PreviewApplicationVersion)i  PreviewSettingsName)i  PreviewSettingsDigest)i  PreviewColorSpace)i  PreviewDateTime)i  RawImageDigest)i  OriginalRawFileDigest)i  SubTileBlockSize)i  RowInterleaveFactor)i%  ProfileLookTableDims)i&  ProfileLookTableData)i@  OpcodeList1)iA  OpcodeList2)iN  OpcodeList3)iO  	FibicsXML)ia  NoiseProfile)ic  	TimeCodes)id  	FrameRate)ir  TStop)i  ReelName)i  OriginalDefaultFinalSize)i  OriginalBestQualitySize)i  OriginalDefaultCropSize)i  CameraLabel)i  ProfileHueSatMapEncoding)i  ProfileLookTableEncoding)i  BaselineExposureOffset)i  DefaultBlackRender)i  NewRawImageDigest)i  RawToPreviewGain)i  	CacheBlob)i  CacheVersion)r  MicroManagerMetadata)i  DefaultUserCrop)i  ZIFmetadata)i  ZIFannotations)r  DepthFormat)i  	DepthNear)i  DepthFar)i  
DepthUnits)i  DepthMeasureType)i  EnhanceParams)i-  ProfileGainTableMap)i.  SemanticName)i0  SemanticInstanceID)i8  MaskSubArea)i?  	RGBTables)i1  CalibrationIlluminant3)i3  ColorMatrix3)i2  CameraCalibration3)i:  ReductionMatrix3)i9  ProfileHueSatMapData3)i4  ForwardMatrix3)i5  IlluminantData1)i6  IlluminantData2)i  IlluminantData3)i@  ProfileGainTableMap2)iC  ColumnInterleaveFactor)iD  ImageSequenceInfo)iF  
ImageStats)iG  ProfileDynamicRange)iH  ProfileGroupName)iI  JXLDistance)iJ  	JXLEffort)iK  JXLDecodeSpeed)i  AperioUnknown55000)i  AperioMagnification)i  	AperioMPP)i  AperioScanScopeID)i  
AperioDate)i  Padding)i  OffsetSchema)i  FlexXMLr   r  s    r   r  z
_TIFF.TAGS>  s     v
x

 x

 x
	
r   @dict[int, Callable[[FileHandle, ByteOrder, int, int, int], Any]]c                   i dt           dt           dt          dt          dt          dt          dt
          dt          d	t          d
t          dt          dt          dt          dt          dt          dt          dt          i dt          dt          dt          dt          dt          dt          dt          dt          dt           dt"          dt$          dt&          dt          dt          d t          d!t          S )"Nr  r  r  r  r  r  r  r  r  r  r  r	  r}  r  r  r  r|  r  r  r  r  r  r  r  r  r  r  r  r  r  r    i  )read_colormap
read_bytesr$  read_uic2tagread_uic3tagread_uic4tagread_cz_semread_mm_headerread_mm_stampr  read_cz_lsminforead_fei_metadataread_tvips_headerread_nih_image_header	read_jsonread_sis_iniread_sisread_exif_ifdread_gps_ifdread_interoperability_ifdr  s    r   rw  z_TIFF.TAG_READERSA  s   
&
&
&

 :&
 <&
 <&
 <&
 <&
 ;&
 >&
 =&
 :&
 :&
  ?!&
" $#&
$ $%&
& $'&
( :)&
 &
* :+&
, (-&
0 :1&
2 :3&
4 :5&
6 :7&
8 99&
: <;&
< 8=&
> =?&
@ <A&
B ,C&
D :E&
F :G&
H :I&
J :K&
 &
 &	
r   frozenset[int]c                     t          d          S )N)r  r  r  r  r  r  r   r  r  r  r  r  r  r  r
  r  r  r  r  r  r  	frozensetr  s    r   rx  z_TIFF.TAG_LOADA  s     
 
 	
r   c                     t          d          S )N)r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r,  r  r  r  r  r  r  r  s    r   r{  z_TIFF.TAG_FILTEREDA  s     
 
 	
r   c                     t          d          S )N)r  r  r  r   r  r  r  r  r
  r  r  rA  r  r  r  r  s    r   r  z_TIFF.TAG_TUPLEA  s     
 
 	
r   dict[int, str]c                x    i ddddddddd	d
dddddddddddddddddddddd d!d"d#d$d%d&S )'Nr  r   r  r  r  r  r  r   r  r   r  r  r  r   r  r  r  r   r  r   r  r   r  r   r  r  r  r  r  rt  r  r   r  r   r   r  r  )r  r  r  r   r  s    r   r  z_TIFF.TAG_ATTRIBUTESB  s    


 

 
 
 
 
 "
 
 
 
 
  !
" #
$ %
& '
* +
, 1
 
 
 	
r   dict[int, type[enum.Enum]]c                    t           t          t          t          t          t
          t          t          t          t          t          dS )N)r  r  r  r  r  r  r  r  r  r  r  )r"   r$   r    r&   r#   r%   r'   r)   r(   r!   r*   r  s    r   r  z_TIFF.TAG_ENUM-B  s6      !
 
 	
r   c                b    t          d          }|                    t          j                   |S )z>Registry of EXIF tags, including private Photoshop Camera RAW.))rx  	OwnerName)r  SerialNumber)rB  Lens)iL  RawFile)iM  	Converter)iN  r  )iQ  Exposure)iR  Shadows)iS  
Brightness)iT  r  )iU  r  )iV  r  )iW  
Smoothness)iX  MoireFilter)r   r  r   r  r  s     r   	EXIF_TAGSz_TIFF.EXIF_TAGSEB  s3     
 
$ 	DIr   c                     t          d          S )z?Registry of private TIFF tags for Hamamatsu NDPI (65420-65458).)*)i,  OffsetHighBytes)i-  ByteCountHighBytes)r  
FileFormat)r  Magnification)i  XOffsetFromSlideCenter)i  YOffsetFromSlideCenter)i  ZOffsetFromSlideCenter)i  TissueIndex)r  rH  )r  
SlideLabel)i  AuthCode)i  65429)i  65430)i  65431)r  rI  )i  65433)i  Fluorescence)i  ExposureRatio)i  RedMultiplier)i  GreenMultiplier)i  BlueMultiplier)r  FocusPoints)i  FocusPointRegions)r(  CaptureMode)i  ScannerSerialNumber)i  65443)i  JpegQuality)i  RefocusInterval)i  FocusOffset)i  
BlankLines)i  FirmwareVersion)i  Comments)i  LabelObscured)i  
Wavelength)i  65452)i  LampAge)i  ru
  )i  	FocusTime)i  ScanTime)i  	WriteTime)i  FullyAutoFocus)r  DefaultGammar  r  s    r   rJ  z_TIFF.NDPI_TAGS^B  s     +-
 -
 -	
r   c                     t          d          S )zRegistry of GPS IFD tags.) )r   GPSVersionID)rW   GPSLatitudeRef)r  GPSLatitude)r   GPSLongitudeRef)r  GPSLongitude)r  GPSAltitudeRef)r  GPSAltitude)r  GPSTimeStamp)rY  GPSSatellites)r<  	GPSStatus)r  GPSMeasureMode)rY  GPSDOP)r  GPSSpeedRef)r  GPSSpeed)r  GPSTrackRef)r  GPSTrack)r  GPSImgDirectionRef)r  GPSImgDirection)r  GPSMapDatum)r  GPSDestLatitudeRef)rA	  GPSDestLatitude)r  GPSDestLongitudeRef)   GPSDestLongitude)   GPSDestBearingRef)rG  GPSDestBearing)   GPSDestDistanceRef)   GPSDestDistance)   GPSProcessingMethod)   GPSAreaInformation)   GPSDateStamp)   GPSDifferential)   GPSHPositioningErrorr  r  s    r   GPS_TAGSz_TIFF.GPS_TAGSB  s     !#
 #
 #	
r   c                     t          d          S )z&Registry of Interoperability IFD tags.))rW   r  )r  r  )r  RelatedImageFileFormat)i  RelatedImageWidth)i  RelatedImageLengthr  r  s    r   IOP_TAGSz_TIFF.IOP_TAGSB  s     
 
 	
r   dict[int, int]c                f    i ddddddddddddddddd	dd
dddddddddddddS )z=Map :py:class:`PHOTOMETRIC` to number of photometric samples.r   rW   r  r   r  r  r  rY  r<  r  r  r  r  r  r  r  r   r  s    r   r[  z_TIFF.PHOTOMETRIC_SAMPLESB  s    
q
q
 q
 q	

 q
 q
 q
 q
 q
 
 1
 1
 1
 1
 1
  1!
 	
r   c                f    i ddddddddd	d
ddddddddddddddddddddddS )z2Map :py:class:`DATATYPE` to Python struct formats.rW   1Br  1sr   1Hr  1Ir  2Ir  1br  rY  1hr<  1ir  2irY  1fr  1dr  r  1Qr  1qr  r   r  s    r   r  z_TIFF.DATA_FORMATSB  s    
t
t
 t
 t	

 t
 t
 t
 t
 t
 
 
 
 
  !
" #
$ %
 	
r   r  c                "    ddddddddd	d
ddddS )z(Map NumPy dtype to :py:class:`DATATYPE`.rW   r  r   r  r  r  rY  r<  r  rY  r  r  r  )r  r  rZ  r  r  r	  r&  r  r  r  r  r  qr   r  s    r   r  z_TIFF.DATA_DTYPESB  s:     
 
 	
r   ,dict[tuple[int, int | tuple[int, ...]], str]c                   i ddddddddddddd	dd
dddddddddddddddddddi ddddddddddddddddddddd dd!dd"dd#dd$dd%d&d'di d(dd)dd*dd+dd,dd-dd.dd/dd0dd1dd2dd3dd4dd5dd6dd7dd8di d9dd:dd;dd<dd=dd>dd?dd@ddAddBddCddDddEddFddGd&dHdIdJdKdLdMdNdOdOdPdQdRddSdQdRdTS )Uz>Map :py:class:`SAMPLEFORMAT` and BitsPerSample to NumPy dtype.r  r   r  r  )rW   r   )rW   r  )rW   r  )rW   r  )rW   r  )rW   rY  )rW   r<  rZ  )rW   r  )rW   rY  )rW   r  )rW   r  )rW   r  )rW   r  )rW   r  )rW   r  r  )rW   r  )rW   r  )rW   rA	  )rW   r  )rW   r  )rW   r  )rW   rG  )rW   r  )rW   r  )rW   r  )rW   r  )rW   r  )rW   r  )rW   r  )rW   r  )rW   r  r  r  )r  r  )r  r   rS  )r  r  )r  r  )r  r  )r  rY  )r  r<  )r  r  )r  rY  )r  r  )r  r  )r  r  )r  r  )r  r  )r  r  )r  r  )r  r  )r  rA	  )r  r  )r  r  )r  r  )r  rG  )r  r  )r  r  )r  r  )r  r  )r  r  )r  r  )r  r  )r  r  )r  r  )r  rY  r	  r  r  r&  r  r  r
  r  r  r}
  Dr^
  ))r  r  )r  r  )r   r  )r   rG  r   r  )r   r  )r  r  )r  r  )rW   r  r  r  )r  r  )r  r  )r  r  r   r  s    r   r&  z_TIFF.SAMPLE_DTYPESC  s*   X
CX
 CX
 C	X

 CX
 CX
 CX
 CX
 CX
 CX
 SX
 SX
 SX
 SX
 SX
  S!X
" S#X
$ S%X
 X
& S'X
( S)X
* S+X
, S-X
. S/X
0 S1X
2 S3X
4 S5X
6 S7X
8 S9X
: S;X
< S=X
> S?X
@ SAX
B SCX
D SEX
H CIX
 X
 X
J CKX
L CMX
N COX
P CQX
R CSX
T CUX
V CWX
X CYX
Z S[X
\ S]X
^ S_X
` SaX
b ScX
d SeX
f SgX
h SiX
j SkX
 X
 X
l SmX
n SoX
p SqX
r SsX
t SuX
v SwX
x SyX
z S{X
| S}X
~ SX
@ SAX
B SCX
D SEX
F SGX
H SIX
L CMX
N SOX
 X
P oX
 X
 X
 X	
r    Mapping[int, Callable[..., Any]]c                     t          d          S )z3Map :py:class:`PREDICTOR` value to encode function.Tr1  r  s    r   rX  z_TIFF.PREDICTORSdC  s     d###r   c                     t          d          S )z3Map :py:class:`PREDICTOR` value to decode function.Fr  r  s    r   r  z_TIFF.UNPREDICTORSiC  s     e$$$r   c                     t          d          S )z7Map :py:class:`COMPRESSION` value to compress function.Tr
  r  s    r   r  z_TIFF.COMPRESSORSnC  s      %%%r   c                     t          d          S )z9Map :py:class:`COMPRESSION` value to decompress function.Fr!  r  s    r   r  z_TIFF.DECOMPRESSORSsC  s      &&&r   set[int]c                
    h dS )N>   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r  s    r   rV  z_TIFF.IMAGE_COMPRESSIONSxC  s    

 
 
 	
r   dict[str, str]c                t    i ddddddddd	d
dddddddddddddddddddddd d!d"d#d$iS )%a
  Map axes character codes to dimension names.

        - **X : width** (image width)
        - **Y : height** (image length)
        - **Z : depth** (image depth)
        - **S : sample** (color space and extra samples)
        - **I : sequence** (generic sequence of images, frames, planes, pages)
        - **T : time** (time series)
        - **C : channel** (acquisition path or emission wavelength)
        - **A : angle** (OME)
        - **P : phase** (OME. In LSM, **P** maps to **position**)
        - **R : tile** (OME. Region, position, or mosaic)
        - **H : lifetime** (OME. Histogram)
        - **E : lambda** (OME. Excitation wavelength)
        - **Q : other** (OME)
        - **L : exposure** (FluoView)
        - **V : event** (FluoView)
        - **M : mosaic** (LSM 6)
        - **J : column** (NDTiff)
        - **K : row** (NDTiff)

        There is no universal standard for dimension codes or names.
        This mapping mainly follows TIFF, OME-TIFF, ImageJ, LSM, and FluoView
        conventions.

        r  r^  r  r  r  r`  r  sampler  rS  r  r-
  r  r+  r]
  rY
  r  rZ
  r  r   rZ  r[
  r^
  r\
  LexposureVeventr  mosaicr  rh  JcolumnKrowr   r  s    r   r  z_TIFF.AXES_NAMESC  s    8


 
 	

 
 
 
 
 
 
 
 
 
 
  !
" #
$ %
& '
 
 	
r   c                j    d t           j                                        D             }d|d<   d|d<   |S )ziMap dimension names to axes character codes.

        Reverse mapping of :py:attr:`AXES_NAMES`.

        c                    i | ]\  }}||	S r   r   r	  s      r   r  z$_TIFF.AXES_CODES.<locals>.<dictcomp>C  s    FFF
dtFFFr   r  rK  r  position)r   r  r:  )rp  r  s     r   r  z_TIFF.AXES_CODESC  s>     GFdo.C.C.E.EFFFc
jr   type[enum.IntEnum]c                f    	 ddl m} n(# t          $ r  G d dt          j                  }Y nw xY w|S )z:py:class:`geodb.GeoKeys`.rW   )GeoKeysc                      e Zd ZdS )_TIFF.GEO_KEYS.<locals>.GeoKeysN)r*  r+  r,  r   r   r   r6  r8  C  s        r   r6  )geodbr6  r
  enumIntEnum)rp  r6  s     r   ro  z_TIFF.GEO_KEYSC  st    	&&&&&&& 	 	 	    $,     	
 s   	 "..dict[int, type[enum.IntEnum]]c                :    	 ddl m} n# t          $ r i }Y nw xY w|S )z/Map :py:class:`geodb.GeoKeys` to GeoTIFF codes.rW   )rp  )r9  rp  r
  )rp  rp  s     r   rp  z_TIFF.GEO_CODESC  sF    	((((((( 	 	 	III	s   	 rO  c                L    h dfdt          t                    D             S )N>   jfifmaskr]   re	  reducedr   
subsampledr  c                X    h | ]&}|d d         dk    |dd          v|dd          'S r   r   r   r  excludes     r   r  z#_TIFF.PAGE_FLAGS.<locals>.<setcomp>C  N     
 
 
!u~~!ABB%w"6"6 abbE"6"6"6r   )dirr   rp  rE  s    @r   r,  z_TIFF.PAGE_FLAGSC  sE    	
 	
 	

 
 
 
]]
 
 
 	
r   c                    ddhfdt          t                    D                                 t          j                  S )Nr   
appendablec                X    h | ]&}|d d         dk    |dd          v|dd          'S r   r   rD  s     r   r  z#_TIFF.FILE_FLAGS.<locals>.<setcomp>C  rF  r   )rG  r   unionr   r,  rH  s    @r   r;  z_TIFF.FILE_FLAGSC  sQ     l+
 
 
 
]]
 
 
 %
 
 		!r   c                
    ddiS )Nr  a  (?ix)
                # matches Olympus OIF and Leica TIFF series
                _?(?:(q|l|p|a|c|t|x|y|z|ch|tp)(\d{1,4}))
                _?(?:(q|l|p|a|c|t|x|y|z|ch|tp)(\d{1,4}))?
                _?(?:(q|l|p|a|c|t|x|y|z|ch|tp)(\d{1,4}))?
                _?(?:(q|l|p|a|c|t|x|y|z|ch|tp)(\d{1,4}))?
                _?(?:(q|l|p|a|c|t|x|y|z|ch|tp)(\d{1,4}))?
                _?(?:(q|l|p|a|c|t|x|y|z|ch|tp)(\d{1,4}))?
                _?(?:(q|l|p|a|c|t|x|y|z|ch|tp)(\d{1,4}))?
                r   r  s    r   FILE_PATTERNSz_TIFF.FILE_PATTERNSC  s      	
 	
r   r  c                    dS )zKnown TIFF file extensions.)r   r/  zome.tifrn  rr  rv  pcorawqptiffptiffptifgelseqrt  ry  ru  zifrw  rx  tf8tf2btfeerr   r  s    r   FILE_EXTENSIONSz_TIFF.FILE_EXTENSIONSD  s    
 
r   list[tuple[str, str]]c                6    d t           j        D             dgz   S )Nc                F    g | ]}|                                  d d| fS )r  z*.r&  )r   r  s     r   r:  z)_TIFF.FILEOPEN_FILTER.<locals>.<listcomp>.D  sD     
 
 
 		###Z#ZZ0
 
 
r   )z	All filesr   )r   r[  r  s    r   FILEOPEN_FILTERz_TIFF.FILEOPEN_FILTER+D  s3    
 
+
 
 
   ! 	!r   c                
    g dS )N):)MagicNumberu4)StructureSizei4)
DimensionXrd  )
DimensionYrd  )
DimensionZrd  )DimensionChannelsrd  )DimensionTimerd  )r  rd  )
ThumbnailXrd  )
ThumbnailYrd  )
VoxelSizeXf8)
VoxelSizeYrm  )
VoxelSizeZrm  )OriginXrm  )OriginYrm  )OriginZrm  )r  u2)SpectralScanrs  )
TypeOfDatarb  )OffsetVectorOverlayrb  )OffsetInputLutrb  )OffsetOutputLutrb  )OffsetChannelColorsrb  )TimeIntervallrm  )OffsetChannelDataTypesrb  )OffsetScanInformationrb  )OffsetKsDatarb  )OffsetTimeStampsrb  )OffsetEventListrb  )	OffsetRoirb  )OffsetBleachRoirb  )OffsetNextRecordingrb  )DisplayAspectXrm  )DisplayAspectYrm  )DisplayAspectZrm  )DisplayAspectTimerm  )OffsetMeanOfRoisOverlayrb  )OffsetTopoIsolineOverlayrb  )OffsetTopoProfileOverlayrb  )OffsetLinescanOverlayrb  )ToolbarFlagsrb  )OffsetChannelWavelengthrb  )OffsetChannelFactorsrb  )ObjectiveSphereCorrectionrm  )OffsetUnmixParametersrb  )OffsetAcquisitionParametersrb  )OffsetCharacteristicsrb  )OffsetPaletterb  )TimeDifferenceXrm  )TimeDifferenceYrm  )TimeDifferenceZrm  )InternalUse1rb  )r  rd  )r  rd  )DimensionsReserved16i4)OffsetTilePositionsrb  )r  9u4)OffsetPositionsrb  r   r  s    r   r  z_TIFF.CZ_LSMINFO3D  s    >
 >
 >
 >	
r   -dict[str, Callable[[FileHandle], Any] | None]c           	         i dt           dt          dt          dt          dt          dt          dd dt
          d	t
          d
d dt          dd dd dd dd dd dd d t          d d d d d dS )NScanInformation
TimeStamps	EventListChannelColorsr  TilePositionsVectorOverlayInputLut	OutputLutrz  ChannelDataTypesKsDataRoi	BleachRoiNextRecordingMeanOfRoisOverlayTopoIsolineOverlay)TopoProfileOverlayChannelWavelengthSphereCorrectionChannelFactorsUnmixParametersAcquisitionParametersCharacteristics)read_lsm_scaninforead_lsm_timestampsread_lsm_eventlistread_lsm_channelcolorsread_lsm_positionsread_lsm_lookuptableread_lsm_channeldatatypesread_lsm_channelwavelengthr  s    r   CZ_LSMINFO_READERSz_TIFF.CZ_LSMINFO_READERSvD  s   
0
-
 +
 3	

 +
 /
 T
 ,
 -
 T
  9
 d
 4
 
 T
   !
" !$#
$ #'!; $"#%)#1
 
 
 	
r   c                    ddddddddddddS )NZCYXCZXCTXTCYXTCZXTZCYX)r   rW   r  r   r  r  r  r  rY  r<  r  r   r  s    r   r  z_TIFF.CZ_LSMINFO_SCANTYPED  s4     
 
 	
r   c                    ddddddddS )	Nre  rf  rg  rh  ri  r  r  )r  r  r  r  r  r  r  r   r  s    r   r
  z_TIFF.CZ_LSMINFO_DIMENSIONSD  s(     $ 
 
 	
r   c                    dddddS )Nzvarying data typesz8 bit unsigned integerz12 bit unsigned integerz32 bit float)r   rW   r  r  r   r  s    r   CZ_LSMINFO_DATATYPESz_TIFF.CZ_LSMINFO_DATATYPESD  s     $'(	
 
 	
r   c                    dddddS )NzOriginal scan datazCalculated dataz3D reconstructionzTopography height map)r   rW   r  r   r   r  s    r   CZ_LSMINFO_TYPEOFDATAz_TIFF.CZ_LSMINFO_TYPEOFDATAD  s     $ "&	
 
 	
r   c           	         ddddddddd	S )
NTracksLasersDetectionChannelsIlluminationChannelsBeamSplittersDataChannelsTimersMarkers)i    i   0i   `rI  l      @ l        i   i   r   r  s    r   CZ_LSMINFO_SCANINFO_ARRAYSz _TIFF.CZ_LSMINFO_SCANINFO_ARRAYSD  s+     ! +.'& !	
 	
 		
r   c           	         ddddddddd	S )
NTrackLaserDetectionChannelIlluminationChannelBeamSplitterDataChannelr3   Marker)i   @i   Pi   pl        l      ` l        i   i   r   r  s    r   CZ_LSMINFO_SCANINFO_STRUCTSz!_TIFF.CZ_LSMINFO_SCANINFO_STRUCTSD  s+      *-&% 

 

 
	
r   c                Z   i ddddddddd	d
dddddddddddddddddddddd d!d"i d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDi dEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`dadbdcdddedfi dgdhdidjdkdldmdndodpdqdrdsdtdudvdwdxdydzd{d|d}d~ddddddddddi ddddddddddddddddddddddddddddddddddi ddddddddddddddddddddddddddÓddœddǓddɓdd˓i dd͓ddϓddѓddӓddՓddדddٓddۓddݓddߓddddddddddddddi dddddddddddddddddddddd ddddddddd	d
ddi dddddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,i d-dd.dd/dd0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKi dLdMdNdOdPddQddRdSdTddUddVddWdXdYddZdd[d\d]d^d_dd`ddaddbdS (c  Ni  rp  i  r
  i  Notesi  	Objectivei  ProcessingSummaryi  SpecialScanModei  r  i  ScanModei	  NumberOfStacksi
  LinesPerPlanei  SamplesPerLinei  PlanesPerVolumei  ImagesWidthi  ImagesHeighti  ImagesNumberPlanesi  ImagesNumberStacksi  ImagesNumberChannelsi  LinscanXySizei  ScanDirectioni  
TimeSeriesi  OriginalScanDatai  ZoomXi  ZoomYi  ZoomZi  Sample0Xi  Sample0Yi  Sample0Zi  SampleSpacingi  LineSpacingi  PlaneSpacingi  
PlaneWidthi   PlaneHeighti!  VolumeDepthi#  Nutationi4  Rotationi5  
Precessioni6  Sample0timei7  StartScanTriggerIni8  StartScanTriggerOuti9  StartScanEventi@  StartScanTimeiA  StopScanTriggerIniB  StopScanTriggerOutiC  StopScanEventiD  StopScanTimeiE  UseRoisiF  UseReducedMemoryRoisiG  UseriH  UseBcCorrectioniI  PositionBcCorrection1iP  PositionBcCorrection2iQ  InterpolationYiR  CameraBinningiS  CameraSupersamplingiT  CameraFrameWidthiU  CameraFrameHeightiV  CameraOffsetXiW  CameraOffsetYiY  	RtBinningiZ  RtFrameWidthi[  RtFrameHeighti\  RtRegionWidthi]  RtRegionHeighti^  	RtOffsetXi_  	RtOffsetYi`  RtZoomia  RtLinePeriodib  Prescanic  ScanDirectionZi  @MultiplexTypei  @MultiplexOrderi  @SamplingModei  @SamplingMethodi  @SamplingNumberi  @Acquirei  @SampleObservationTimei  @TimeBetweenStacksi  @i  @Collimator1Namei  @Collimator1Positioni  @Collimator2Namei  @Collimator2Positioni  @IsBleachTracki  @IsBleachAfterScanNumberi  @BleachScanNumberi  @	TriggerIni  @
TriggerOuti  @IsRatioTracki  @BleachCounti  @SpiCenterWavelengthi  @	PixelTimei!  @CondensorFrontlensi#  @FieldStopValuei$  @IdCondensorAperturei%  @CondensorAperturei&  @IdCondensorRevolveri'  @CondensorFilteri(  @IdTransmissionFilter1i)  @IdTransmission1i0  @IdTransmissionFilter2i1  @IdTransmission2i2  @RepeatBleachi3  @EnableSpotBleachPosi4  @SpotBleachPosxi5  @SpotBleachPosyi6  @SpotBleachPoszi7  @
IdTubelensi8  @IdTubelensPositioni9  @TransmittedLighti:  @ReflectedLighti;  @SimultanGrabAndBleachi<  @BleachPixelTimei  Pi  Pi  PPoweri  pIntegrationModei  pSpecialModei  pDetectorGainFirsti  pDetectorGainLasti  pAmplifierGainFirsti  pAmplifierGainLasti  pAmplifierOffsFirsti  pAmplifierOffsLasti	  pPinholeDiameteri
  pCountingTriggeri  pi  pPointDetectorNamei  pAmplifierNamei  pPinholeNamei  pFilterSetNamei  p
FilterNamei  pIntegratorNamei  pChannelNamei  pDetectorGainBc1i  pDetectorGainBc2i  pAmplifierGainBc1i  pAmplifierGainBc2i  pAmplifierOffsetBc1i   pAmplifierOffsetBc2i!  pSpectralScanChannelsi"  pSpiWavelengthStarti#  pSpiWavelengthStopi&  pDyeNamei'  p	DyeFolderl       l       l       r  l       Aquirel       DetchannelNamel       PowerBc1l       PowerBc2l     ` 	FilterSetl     ` Filterl     ` l       l       l       r
  l       
SampleTypel       r  l       	RatioTypel       RatioTrack1l   	    RatioTrack2l   
    RatioChannel1l       RatioChannel2l       RatioConst1l       RatioConst2l       RatioConst3l       RatioConst4l       RatioConst5l       RatioConst6l       RatioFirstImages1l       RatioFirstImages2l       l       l       Spectruml       i  i  i  Intervali  i  i  ActivationTimei  ActivationNumberi  i  i  i  r   r  s    r   CZ_LSMINFO_SCANINFO_ATTRIBUTESz$_TIFF.CZ_LSMINFO_SCANINFO_ATTRIBUTESD  s   E
E
 E
 	E

 E
 +E
 )E
 
E
 
E
 (E
 E
 (E
 )E
 E
 E
  ,!E
" ,#E
$ .%E
 E
& 'E
( )E
* +E
, *-E
. /E
0 1E
2 3E
4 
5E
6 
7E
8 
9E
: ;E
< =E
> ?E
@ AE
B CE
D EE
F 
GE
 E
 E
H 
IE
J KE
L ME
N ,OE
P -QE
R (SE
T UE
V +WE
X ,YE
Z [E
\ ]E
^ 	_E
` .aE
b cE
d )eE
f /gE
h /iE
 E
 E
j (kE
l mE
n -oE
p *qE
r +sE
t uE
v wE
x yE
z {E
| }E
~ E
@ (AE
B CE
D EE
F GE
H IE
J 	KE
 E
 E
L (ME
P QE
R (SE
T UE
V (WE
X (YE
Z 	[E
\ /]E
^ +_E
` aE
b )cE
d -eE
f )gE
h -iE
j kE
l 1mE
n *oE
 E
 E
p qE
r sE
t uE
v wE
x -yE
z {E
| ,}E
~ (E
@ -AE
B +CE
D -EE
F )GE
H /IE
J )KE
L /ME
N )OE
P QE
 E
 E
R -SE
T (UE
V (WE
X (YE
Z [E
\ ,]E
^ *_E
` (aE
b /cE
d )eE
h iE
j 	kE
l mE
p )qE
r sE
t +uE
v *wE
 E
 E
x ,yE
z +{E
| ,}E
~ +E
@ )AE
B )CE
D 	EE
F +GE
H IE
J KE
L ME
N OE
P (QE
R SE
T )UE
V )WE
X *YE
 E
 E
Z *[E
\ ,]E
^ ,_E
` .aE
b ,cE
d +eE
f 	gE
h iE
l mE
n oE
p qE
r sE
t (uE
v 
wE
x 
yE
| }E
~ E
 E
 E
@ AE
D EE
F 	GE
H IE
J KE
L ME
N OE
P QE
R SE
T UE
V WE
X YE
Z [E
\ ]E
^ _E
` aE
b cE
 E
 E
d +eE
f +gE
h 	iE
j kE
l 
mE
n 	oE
r sE
t uE
v 
wE
x yE
z {E
| (}E
~ *E
B CE
D EE
F GE
H IE
 E
 E	
r   c                6     G d dt           j                  }|S )Nc                  &    e Zd ZdZdZdZdZdZdZdS ),_TIFF.CZ_LSM_LUTTYPE.<locals>.CZ_LSM_LUTTYPEr   rW   r  r   r  r  N)	r*  r+  r,  NORMALORIGINALRAMPPOLYLINESPLINEGAMMAr   r   r   CZ_LSM_LUTTYPEr  E  s,        FHDHFEEEr   r  r:  r;  )rp  r  s     r   r  z_TIFF.CZ_LSM_LUTTYPEE  s6    	 	 	 	 	T\ 	 	 	 r   c                6     G d dt           j                  }|S )Nc                  *    e Zd ZdZdZdZdZdZdZdZ	dS )	8_TIFF.CZ_LSM_SUBBLOCK_TYPE.<locals>.CZ_LSM_SUBBLOCK_TYPEr   rW   r  r   r  r  r  N)
r*  r+  r,  r  r  
BRIGHTNESSCONTRASTr  KNOTSPALETTE_12_TO_12r   r   r   CZ_LSM_SUBBLOCK_TYPEr  E  s4        CEJHDE r   r  r  )rp  r  s     r   r  z_TIFF.CZ_LSM_SUBBLOCK_TYPEE  s6    	! 	! 	! 	! 	!4< 	! 	! 	! $#r   c                    g ddddddddd	d
ddddddddddgfdddgfddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0S )1N)FileIDS8)nLinesi2)PixelsPerLiner  )Versionr  )
OldLutModer  )
OldnColorsr  )Colorsu1r  )OldColorStartr  )
ColorWidthr  )ExtraColorsrs  )r  r   )nExtraColorsr  )ForegroundIndexr  )BackgroundIndexr  )XScalerm  )Unused2r  )Unused3r  )UnitsIDr  p1)r  r  )yr  p2)CurveFitTyper  )nCoefficientsr  )Coeffrm  r  )UMsizer  )UMS15)UnusedBooleanr  )	BinaryPicb1)
SliceStartr  )SliceEndr  )ScaleMagnificationf4)nSlicesr  )SliceSpacingr  )CurrentSlicer  )FrameIntervalr  )PixelAspectRatior  )
ColorStartr  )ColorEndr  )nColorsr  )Fill13u2)Fill2r  )Tabler  )LutModer  )InvertedTabler  )ZeroClipr  )	XUnitSizer  )XUnitS11)	StackTyper  r   r  s    r   NIH_IMAGE_HEADERz_TIFF.NIH_IMAGE_HEADERE  s   0
0
0
 $0
 	0

 !0
 !0
 &0
 $0
 !0
 *0
 #0
 &0
 &0
 0
 0
  !0
" #0
$ K-.%0
& K-.'0
( #)0
* $+0
, -0
. /0
0 10
2 $30
4  50
6 !70
8 90
: );0
< =0
> #?0
@ #A0
B $C0
D 'E0
F !G0
H I0
J K0
L M0
N O0
P Q0
R S0
T $U0
V W0
X  Y0
Z [0
\  ]0
 0	
r   c                    dS )N)
CustomTableAppleDefaultPseudo20Pseudo32RainbowFire1Fire2IceGraysrz  r   r  s    r   NIH_COLORTABLE_TYPEz_TIFF.NIH_COLORTABLE_TYPEE  s    
 
r   c                    dS )N)PseudoColorOldAppleDefaultOldSpectrum	GrayScaleColorLutCustomGrayscaler   r  s    r   NIH_LUTMODE_TYPEz_TIFF.NIH_LUTMODE_TYPE	F  s    
 
r   c                    dS )N)StraightLinePoly2Poly3Poly4Poly5ExpoFitPowerFitLogFit
RodbardFit	SpareFit1UncalibratedUncalibratedODr   r  s    r   NIH_CURVEFIT_TYPEz_TIFF.NIH_CURVEFIT_TYPEF  s    
 
r   c                    dS )N)
NanometersMicrometersMillimetersCentimetersMeters
KilometersInchesFeetMilesrq  
OtherUnitsr   r  s    r   NIH_UNITS_TYPEz_TIFF.NIH_UNITS_TYPE%F  s    
 
r   c                
    g dS )N)*)r  rd  )	CommentV1S80)HighTensionrd  )SphericalAberrationrd  )IlluminationAperturerd  )r  rd  )PostMagnificationrd  )r]  rd  )Defocusrd  )Astigmatismrd  )AstigmatismDirectionrd  )BiprismVoltagerd  )SpecimenTiltAnglerd  )SpecimenTiltDirectionrd  )IlluminationTiltDirectionrd  )IlluminationTiltAnglerd  )	ImageModerd  )EnergySpreadrd  )ChromaticAberrationrd  )ShutterTyperd  )DefocusSpreadrd  )	CcdNumberrd  )CcdSizerd  )	OffsetXV1rd  )	OffsetYV1rd  )PhysicalPixelSizerd  )Binningrd  )ReadoutSpeedrd  )GainV1rd  )SensitivityV1rd  )ExposureTimeV1rd  )FlatCorrectedrd  )DeadPxCorrectedrd  )	ImageMeanrd  )ImageStdrd  )DisplacementXrd  )DisplacementYrd  )DateV1rd  )TimeV1rd  )ImageMinrd  )ImageMaxrd  )ImageStatisticsQualityrd  r   r  s    r   TVIPS_HEADER_V1z_TIFF.TVIPS_HEADER_V15F  s    +
 +
 +
 +	
r   c                
    g dS )N)6)r  V160)ImageFolderr#  )
ImageSizeXrd  )
ImageSizeYrd  )
ImageSizeZrd  )
ImageSizeErd  )ImageDataTyperd  )r  rd  )r  rd  )CommentV1024)rf  r+  )Scaling16f4)ImageStatistics16c16)r  rd  )ImageDisplaTyperd  )
PixelSizeXr  )
PixelSizeYr  )ImageDistanceZr  )ImageDistanceEr  )	ImageMisc32f4)TemTyper#  )TemHighTensionr  )TemAberrationsr6  )	TemEnergyr6  )TemModerd  )TemMagnificationr  )TemMagnificationCorrectionr  )r  r  )TemStageTyperd  )TemStagePosition5f4)TemImageShift2f4)TemBeamShiftrB  )TemBeamTiltrB  )TilingParameters7f4)TemIllumination3f4)
TemShutterrd  )TemMiscr6  )
CameraTyper#  )PhysicalPixelSizeXr  )PhysicalPixelSizeYr  )OffsetXrd  )OffsetYrd  )BinningXrd  )BinningYrd  )ru
  r  )Gainr  )ReadoutRater  )FlatfieldDescriptionr#  )Sensitivityr  )Doser  )CamMiscr6  )FeiMicroscopeInformationr+  )FeiSpecimenInformationr+  )Magicrb  r   r  s    r   TVIPS_HEADER_V2z_TIFF.TVIPS_HEADER_V2eF  s    8
 8
 8
 8	
r   list[tuple[Any, ...]]c                F    g d}dddddddd	d
d|dfdddddddddd|fdddgS )N))rp  S16)rt  rd  )Originrm  )r5  rm  )UnitS64)
HeaderFlagr  )r  r  )r  S257)
OffsetDatarb  )PaletteSizerd  )OffsetPalette0rb  )OffsetPalette1rb  )CommentSizerd  )OffsetCommentrb  r  r  )OffsetPositionrb  )MapTyper  )MapMinrm  )MapMaxrm  )MinValuerm  )MaxValuerm  )	OffsetMaprb  )r  rm  )Offsetrm  GrayChannel)OffsetThumbnailrb  )
VoiceFieldrd  )OffsetVoiceFieldrb  r   )rp  MM_DIMENSIONs     r   	MM_HEADERz_TIFF.MM_HEADERF  sp    
 
 
 !! !$$!#<,$L)% &/
 	
r   c                    ddddddddddd	
S )
Nr  r  r  r  r  r  r*  r(  )
r  r  r  r  CH
WAVELENGTHTIMEXYEVENTEXPOSUREr   r  s    r   r  z_TIFF.MM_DIMENSIONSF  s1     
 
 	
r   list[tuple[str, Any]]c                   ddl m} g dt          fdt          fdt          fdt          fd|fd|fd	t          fd
t          fdt          fdt          fddt          fdt          fdt          fdt          fdt          fdt          fdt          fdt          fddd|fd|fd|fd|fdt          fdt          fdt          fdd d!d"d#d$d%d&d't
          fd(d)|fd*|fd+d,d-d.d/d0d1d2t          fd3d4t          fd5d6t          fd7|fd8|fd9t          fd:t          fd;t          fd<|fd=|fd>t          fd?t          fd@t          fdA|fdB|fdCt          fdDt          fS )ENr   Fraction	AutoScaleMinScaleMaxScaleSpatialCalibrationXCalibrationYCalibrationCalibrationUnitsrp  ThreshStateThreshStateRed)tagid_10NThreshStateGreenThreshStateBlueThreshStateLoThreshStateHiZoom
CreateTimeLastSavedTimecurrentBuffer)grayFitN)grayPointCountNgrayXgrayYgrayMingrayMaxgrayUnitNameStandardLUT
wavelength)StagePosition
(%i,2,2)u4)CameraChipOffsetr  )OverlayMaskN)OverlayCompressN)OverlayN)SpecialOverlayMaskN)SpecialOverlayCompressN)SpecialOverlayNImageProperty)
StageLabel%ipAutoScaleLoInfoAutoScaleHiInfo)	AbsoluteZz(%i,2)u4)AbsoluteZValidz(%i,)u4)r  r  )GammaRedr  )
GammaGreenr  )	GammaBluer  )	CameraBinr  NewLUT)ImagePropertyExNPlaneProperty)UserLutTablez	(256,3)u1RedAutoScaleInfoRedAutoScaleLoInfoRedAutoScaleHiInfoRedMinScaleInfoRedMaxScaleInfoGreenAutoScaleInfoGreenAutoScaleLoInfoGreenAutoScaleHiInfoGreenMinScaleInfoGreenMaxScaleInfoBlueAutoScaleInfoBlueAutoScaleLoInfoBlueAutoScaleHiInfoBlueMinScaleInfoBlueMaxScaleInfo)	fractionsr  r   r   r  read_uic_property)rp  r  s     r   UIC_TAGSz_TIFF.UIC_TAGSF  s    	'&&&&&D
#D
D
 D
 "3'	D

 X&D
 X&D
  %D
 SMD
 C D
 s#D
 D
  %D
 $D
 c"D
 c"D
  SM!D
" ?+#D
$ o.%D
& c"'D
( )D
* %+D
, h-D
. h/D
0 !1D
2 !3D
4 S!5D
6 C 7D
8 39D
: ,;D
< /=D
> "?D
@ &AD
B CD
D )ED
F -GD
H %ID
J /0KD
L "MD
N )OD
P )QD
R &SD
T *UD
V WD
X YD
Z  [D
\ ]D
^  _D
` sOaD
b &cD
d c"eD
f *gD
h  %iD
j "8,kD
l "8,mD
n $oD
p $qD
r "3'sD
t $X.uD
v $X.wD
x !#&yD
z !#&{D
| !#&}D
~ #H-D
@ #H-AD
B  %CD
D  %ED
 D	
r   r  c                   i dt          dd           gt          fdddgt          fddgt          fddgt          fddgt          fd	dgt          fd
dgt          fddgt          fdddgt          fddgt          fddgt          fddgt          fddgt          fddgt          fddgt          fdddgt          fddgt          fi ddgt          fdddgt          fddgt          fddgt          fddgt          fddgt          fddgt          fddgt          fddgt          fddgt          fd dgt          fd!dgt          fd"dgt          fd#dgt          fd$t          dd           gt          fd%dgt          fd&dgt          fdgt          fdgt          fdgt          fdgt          fd'S )(NDetectorrW   
Pixel_sizer  Siliconr   Exposure_timeExposure_periodTauCount_cutoffThreshold_settingGain_settingr  N_excluded_pixelsExcluded_pixels
Flat_field	Trim_file
Image_pathr  Energy_rangeDetector_distanceDetector_VoffsetBeam_xyFluxFilter_transmissionStart_angleAngle_incrementDetector_2thetaPolarizationAlphaKappaPhiPhi_incrementChiChi_incrementOscillation_axisN_oscillationsStart_position)Position_incrementShutter_timeOmegaOmega_increment)ra  r   r  r   r  s    r   PILATUS_HEADERz_TIFF.PILATUS_HEADER!G  s   (
%4..)3/(
Aq65/(
 U|(
 qc5\	(

 U|(
 QC<(
 aS#J(
  1#u(
 aVSM(
  1#s(
 Sz(
 A3*(
 1#s(
 A3*(
  A3,!(
" aVUO#(
$  1#u%(
 (
& !e'(
( A)(
* aS#J+(
, "QC<-(
. QC</(
0 U|1(
2 U|3(
4 aS%L5(
6 qc5\7(
8 qc5\9(
: QC<;(
< qc5\=(
> QC<?(
@ qc5\A(
B %4..!13 7C(
D sCjE(
F sElG(
 (
H %&3,S%Lc5\!"U|O(
 (
 (
 (	
r   r   c                    dd l }|j        S r  )mmapr  )rp  r  s     r   r  z_TIFF.ALLOCATIONGRANULARITYOG  s     	))r   c                N   dt           j        v r-t          dt          t           j        d                             S 	 t	          t          j        d                    }n## t          $ r t          j                    }Y nw xY w|dS t          dt          d|dz                      S )zDefault maximum number of threads for de/compressing segments.

        The value of the ``TIFFFILE_NUM_THREADS`` environment variable if set,
        else half the CPU cores up to 32.

        TIFFFILE_NUM_THREADSrW   r   Nr  r  	r  environrq  r   r   sched_getaffinityr?  	cpu_countr  rp  r  s     r   r  z_TIFF.MAXWORKERSVG  s     "RZ//q#bj)?@AABBB	'$Q'' II  	' 	' 	'III	'12s1i1n--...   !A A?>A?c                2   dt           j        v r-t          dt          t           j        d                             S 	 t	          t          j        d                    }n## t          $ r t          j                    }Y nw xY w|dS t          d|dz             S )zDefault maximum number of I/O threads for reading file sequences.

        The value of the ``TIFFFILE_NUM_IOTHREADS`` environment variable if
        set, else 4 more than the number of CPU cores up to 32.

        TIFFFILE_NUM_IOTHREADSrW   r   Nr  r  r  r  r  s     r   rd	  z_TIFF.MAXIOWORKERSkG  s     $rz11q#bj)ABCCDDD	'$Q'' II  	' 	' 	'III	'12y1}%%%r     r	  N)r   r   )r   r   )r   r  )r   r  )r   r  )r   r  )r   r  r  )r   r  )r   r  )r   r#  )r   r%  )r   r4  )r   r<  r  r  )r   r\  )r   r  )r   r\  )r   r  r  r  )Cr*  r+  r,  r-  rV   rf  rh  re  rg  rA  r  rw  rx  r{  r  r  r  r  rJ  r  r  r[  r  r  r&  rX  r  r  r  rV  r  r  ro  rp  r,  r;  r(  rN  r[  r_  r  r  r  r
  r  r  r  r  r~  r  r  r  r  r  r  r  r!  r[  rw  r  r  r  r  r  rd	  r	  r'  r   r   r   rM   rM   z>  s        JJ
 
 
 _
 
 
 
 _
 
 
 
 _
 
 
 
 _
 
 
 
 _
 {

 {

 {

 _{

z *
 *
 *
 _*
X 
 
 
 _
> 
 
 
 _
@ 
 
 
 _
* 
 
 
 _
: 
 
 
 _
.    _0 0
 0
 0
 _0
d %
 %
 %
 _%
N 

 

 

 _

 
 
 
 _
* 
 
 
 _
. 
 
 
 _
$ Z
 Z
 Z
 _Z
x $ $ $ _$ % % % _% & & & _& ' ' ' _' 
 
 
 _
, /
 /
 /
 _/
b 	 	 	 _	 	 	 	 _	    _ 
 
 
 _
$ ! ! ! _! 
 
 
 X
 
 
 
 X
6 ! ! ! X! @
 @
 @
 X@
D 
 
 
 X
@ 
 
 
 X
  

 

 

 X

 
 
 
 X
 
 
 
 X
 

 

 

 X

 
 
 
 X
 F
 F
 F
 XF
P 	 	 _	 
$ 
$ _
$ 1
 1
 X1
f 
 
 
 X
 
 
 
 X
 
 
 
 X
  
 
 
 X
 -
 -
 -
 X-
^ 9
 9
 9
 X9
v !
 !
 !
 X!
F 
 
 
 X
 I
 I
 I
 XI
V +
 +
 +
 X+
Z * * * _* / / / _/( & & & _&(  JIIr   rM   )maxifds
customtags	ByteOrderrJ  tagnamesrq  r  r  Gdict[int, Callable[[FileHandle, ByteOrder, int, int, int], Any]] | Nonelist[dict[str, Any]]c         
     t  " |dk    r|dz   }d}|dz   }d}	|dz   }
|dz   }n.|dk    r|d	z   }d}|d	z   }d
}	|dz   }
|dz   }nt          d          |i }|d}g }t          j        }|                                 }t	          |          |k     r+	  |||                     |                    d         }|dk    rt          d|           n@# t          $ r3}t                      	                    d| d|d           Y d}~nd}~ww xY wi }|                     |	|z            }|                                 }d}t          |          D ]} ||
|||dz                      \  }} ||||dz   ||	z                      \  }}||	z  }|                    |t          |                    }	 t          j        |         }n7# t          $ r* t                      	                    d|d|            Y w xY w|t          j        |          z  }||k    s||v r- |||          d         }|dk     s||z   | j        k    r)t                      	                    d| d|            |                     |           ||v r||         } || ||||          }n|dv rM|                     |          }t	          |          |k    r$t                                          d|            n||v rD| |t)          |d                   z   |d          }  || |                     |                    }n[t+          | ||||          }nG|dv r|d|         }n8| |t)          |d                   z   |d          }  || |d|                   }||vo|t          j        vo|dk    }!|!r|dk    r|                    d          }	 |                    d                                          }n# t4          $ rk 	 |                    d                                          }n?# t4          $ r2}t                                          d| d |d           Y d}~nd}~ww xY wY nw xY w|t          j        v rrt          j        |         "	 t9          "fd!|D                       }nC# t           $ r6}|d"vr(t                                          d#| d|d           Y d}~nd}~ww xY w|!rt	          |          dk    r|d         }|||<   |                    |           |                     |            |||                     |                    d         }|dk    rnY|| j        k    r%t                      	                    d$|           n)|                     |           t	          |          |k     +|S )%aG  Read tag values from chain of IFDs.

    Parameters:
        fh:
            Binary file handle to read from.
            The file handle position must be at a valid IFD header.
        byteorder:
            Byte order of TIFF file.
        offsetsize:
            Size of offsets in TIFF file (8 for BigTIFF, else 4).
        tagnames:
            Map of tag codes to names.
            For example, :py:class:`_TIFF.GPS_TAGS` or
            :py:class:`_TIFF.IOP_TAGS`.
        maxifds:
            Maximum number of IFDs to read.
            By default, read the whole IFD chain.
        customtags:
            Mapping of tag codes to functions reading special tag value from
            file.

    Raises:
        TiffFileError: Invalid TIFF structure.

    Notes:
        This implementation does not support 64-bit NDPI files.

    r  r  r  rZ  r  r  I4srY  r  rA	  Q8szinvalid offset sizeNr|  r   r  r  z)<tifffile.read_tags> corrupted tag list @r  r9  zinvalid data type z
 for tag #zinvalid value offset ru  z8<tifffile.read_tags> could not read all values for tag #rW   r  r1  r  r  z><tifffile.read_tags> coercing invalid ASCII to bytes for tag #z	, due to c              3  .   K   | ]} |          V  d S r   r   r  s     r   r   zread_tags.<locals>.<genexpr>,H  s+      %:%:qaadd%:%:%:%:%:%:r   r  z<tifffile.read_tags> tag #z.<tifffile.read_tags> invalid next page offset=)r   rj  r@  r]  r   r?  r   r  r=   rB  r  rY  r   r   r  r  r  rw   ra  rs  r   r  r  r  r  r=  r  r  r  r   )#rq  r   rJ  r  r  r  rl  r  rI  rK  r  r  r  r@  rv   r.  r  r  r   rr  r  r	  r  r~   r  
valuebytesru   r   r|  r  r  rU  r  processr  s#                                     @r   	read_tagsr  G  s`   \ Q 3	#o%
&

	q 3	#o%
&

.///
#%F]FWWYYF
f++

		F;	(:(:;;A>Et||#$H$H$HIII  	 	 	HHNN'F ' '&' '   EEEE	 www''ggiiu V	 V	A &T%%!)2C-DEEKD% &DUW_!<=! !E: WE<<c$ii00D"/6   MEMMtMMNNN  < <<I:%%););$f\:>>qA??kI&=&G&GHHNNMMMtMM   $$$:%%)$/H$HRE5*MMEEi''GGI..E5zzY..((IBFI I   X%%$ , 3{1~#6#66,&q>, , 
 #F3	(:(:;;EE&r9eUJOOEE)##":I:. ! (s;q>222("1~( ( 
 sJz	z$:;; J& .QJ 
  %5A:: W--	!LL117799EE)    %X 6 6 < < > >-   ((J.2J J=@IJ J        4=((d+A %%:%:%:%:E%:%:%: : :%   z11"HH,,!7T !7 !7*- 6!7 !7    %s5zzQ!!HEDJJd 	bggj&9&9::1=Q;;RWHHNNNVNNOOO
i f++

l Ms~   =C 
D	(DD	.G1G54G5'O--
Q"8'P Q" 
Q*(QQ"QQ"!Q"R""
S",,SS"r  r  c                  t          | ||t          j        d          d         }dD ]+}	 t          ||                   ||<   # t          $ r Y (w xY wd|v ru|d         dd         }	 |dk    r!t          |d         dd                   |d<   n,|d	k    r&|d         dd                             d
          |d<   n# t          $ r Y nw xY w|S )zRead EXIF tags from file.rW   r  r   )r9  r  rp  NrY  s   ASCII   s   UNICODE utf-16)r  r   r  	bytes2strr  r  )rq  r   r~   r  rJ  exifru   idcodes           r   r  r  GH  s    RJJJJ1MD2  	"4:..DJJ 	 	 	D	m$RaR(	---&/]0CABB0G&H&H]##>))&*=&9!""&=&D&DX&N&N]# 	 	 	D	Ks$   A
AA(AB< <
C	C	c               J    t          | ||t          j        d          d         S )zRead GPS tags from file.rW   r
  r   )r  r   r  rq  r   r~   r  rJ  s        r   r  r  bH  $     RJqIII!LLr   c               J    t          | ||t          j        d          d         S )z%Read Interoperability tags from file.rW   r
  r   )r  r   r  r  s        r   r  r  nH  r  r   r  c               :   |t          j        |dk    rdn|t          j        |         d         z             j        z  }|                     |          }t          |          |k    r5t                                          d| dt          |           d           |S )zRead tag data from file.r  r  rT  z%<tifffile.read_bytes> failed to read r	  r  )	r  r~   r   r  r  r?  r   r=   rs  )rq  r   r~   r  rJ  r   s         r   r  r  zH  s     
U[zzy4+<U+CB+GG E 775>>D
4yyE>#> >14T> > >	
 	
 	
 Kr   r   c               P    |                      |                                          S )z!Read unicode tag value from file.)r?  r  r  s        r   	read_utf8r  H  s      775>>  """r   c               p    |                      |dk    rdn|t          j        |         d         z   |          S )z%Read NumPy array tag value from file.r  r	  rT  )re  r   r  r  s        r   r  r  H  s=     ==zzy4+<U+CB+GG  r   c                   |                      |t          j        |         d         z   |          }|dz  dk    rd|_        |S )z6Read ColorMap or TransferFunction tag value from file.rT  r   r   )r   rT  )re  r   r  r   )rq  r   r~   r  rJ  cmaps         r   r  r  H  sB     ==T%6u%=b%AA5IIDqyA~~
Kr   c                   |                      |          }	 t          j        t          |d                    S # t          $ r/}t                                          d|d           Y d}~nd}~ww xY wdS )zRead JSON tag value from file.r  z<tifffile.read_json> raised r9  N)r?  jsonloadsr  r   r=   rs  )rq  r   r~   r  rJ  r   r  s          r   r  r  H  s     775>>DFz)D'22333 F F FDDDDEEEEEEEEF4s   !9 
A2%A--A2c                  t          |                     t          j        t          j                  |                    }d |d         D             |d<   |d         }t          |d                                                   |d         |d         |d         t          |d	                                                   f|d<   |S )
z,Read FluoView mm_header tag value from file.r  c           
         g | ]e}t          |d                                                    |d         |d         |d         t          |d                                                   ffS )r   rW   r  r   r  )r  r=  )r   r  s     r   r:  z"read_mm_header.<locals>.<listcomp>H  sk        
1Q4			 	 !A$!adIadOO4I4I4K4KL  r   r  rr  r   rW   r  r   r  )recarray2dictr	  r  r~   r   rw  r  r=  )rq  r   r~   r  rJ  r  r  s          r   r  r  H  s     
u{4>22iHH D l#  D 	]A!A$	!	!	!!A$D Kr   c               4    |                      |dz   d          S )z+Read FluoView mm_stamp tag value from file.rm  rY  )re  r  s        r   r  r  H  s     ==T)1---r   r  c                  |dvs|dk    rt          d| |           i }|dk    rI|                     dd|z                                |d          }d|ddd	f         |ddd
f         z  i}nt          |          D ]}t	          j        d|                     d                    d	         }	|d
k    r|	dv r|                     d           Pt          | |	|d          \  }
}|
dk    rx|                                 }| 	                    |dz              |
                    |
g                               t          |                      | 	                    |           |||
<   |S )zhRead MetaMorph STK UIC1Tag value from file.

    Return empty dictionary if planecount is unknown.

    >   r  r  rk   zinvalid UIC1Tag r  <u4r  r  Nr   rW   r  r  >   r  r  %   (   )   Tr  )r   re  rz  r  rj  r@  r?  read_uic_tagr]  ra  
setdefaultr   r  )rq  r   r~   r  rJ  r  r  rT  r	  ru  ru   rU  rr  s                r   r$  r$  H  s    Fi3..>I>u>>???Fzzua%i0088BBvaaad|fQQQTl:;u 	% 	%AM$

33A6EA~~%+?"?"?


&r5*dCCKD%&&ggii	"""!!$++223DR3H3HIII$tMr   r  c                   |dk    s|dk    rt          d          |                     dd|z                                |d          }|dddf         |dddf         z  |ddd	f         |ddd
f         |dddf         |dddf         dS )z+Read MetaMorph STK UIC2Tag value from file.r  rk   zinvalid UIC2Tagr!  r  Nr   rW   r  r   r  )r  DateCreatedr  DateModifiedr  r   re  rz  rq  r   r~   r  rJ  rT  s         r   r  r  I  s     zzY#%%*+++]]5!e),,44UA>>FAAAqD\F111a4L0aaad|aaad|qqq!tqqq!t  r   c                   |dk    s|dk    rt          d          |                     dd|z                                |d          }d|dddf         |ddd	f         z  iS )
z+Read MetaMorph STK UIC3Tag value from file.r  rk   zinvalid UIC3Tagr!  r  WavelengthsNr   rW   r*  r+  s         r   r  r  ,I  su     zzY#%%*+++]]5!e),,44UA>>F6!!!Q$<&A,677r   c                   |dk    s|dk    rt          d          i }	 t          j        d|                     d                    d         }|dk    rnt	          | ||d          \  }}|||<   P|S )	z+Read MetaMorph STK UIC4Tag value from file.r  rk   zinvalid UIC4TagTr  r  r   F)r   rj  r@  r?  r%  )	rq  r   r~   r  rJ  r  ru  ru   rU  s	            r   r  r  ;I  s     zzY#%%*+++F]444Q7A::"2ueU;;et Mr   ru  tuple[str, Any]c                   d! fd}d" fd}	 t           j        |         \  }}n# t          $ r d|  |            fcY S w xY wt           j        d         d         }|r                                 }	|t          d	hvrg |            }
|
d
k     rB|t
          u r|dfS |dk    r||
fS t                                          d|d|
            ||
fS                      |
           |d|z   } |            }n|t          u r |            }n||u r |            }|d         |d         z  }n|t          u rX |            }	 t          | }n~# t          $ r5}d	}t                                          d| d|d           Y d	}~nDd	}~ww xY w|t          u rt                     }n"|t
          u r |            }d|cxk    rdk     rMn nJt          j        | d                     |                    d         d	d         }t          |          }n|r(d}t                                          d|           nt!          d|           |dk    rd	}no|dk    rg }t#          |          D ]} |            }d|cxk    rdk     r_n n\t          j        | d                     |                    d         d	d         }|                    t          |                     x|r%t                                          d|           t!          d|           nd|z   }d|v r||z  }d|v r?                     |d          d         }|j        d         dk    r|d         |d          z  }nUt          j        |                     t          j        |                              }t-          |          dk    r|d         }|r                     |	dz              ||fS )#zeRead single UIC tag value from file and return tag name and value.

    UIC1Tags use an offset.

    r   r   c                 z    t          t          j        d                     d                    d                   S )Nr  r  r   )r   rj  r@  r?  rq  s   r   read_intzread_uic_tag.<locals>.read_intYI  s,    6=rwwqzz2215666r   tuple[int, int]c                     t          j        d                    d                    } t          | d                   | d         fS )Nz<2IrY  r   rW   )rj  r@  r?  r   )rU  rq  s    r   	read_int2zread_uic_tag.<locals>.read_int2\I  s7    eRWWQZZ0058}}uQx((r   _TagIdr  rW   NrY  r  r$  z/<tifffile.read_uic_tag> invalid offset for tag r  r	  r   z <tifffile.read_uic_tag> reading r  r9  r  r  rT  z.<tifffile.read_uic_tag> invalid string in tag zinvalid string size r  zinvalid string size: rk   z%ir	  r  r  ).rW   r  )r   r4  )r   r  r  r]  r   r   r=   rs  ra  r  r  r  rj  r@  r?  r  r   r  r   re  r   r  r   )rq  ru  r  rv   r3  r6  ru   r~   r  rr  offrU  r  rw   r	  strings   `               r   r%  r%  PI  s   7 7 7 7 7 7) ) ) ) ) ),mE*ee , , ,++++, }Q"H ggiid##(**CQwwC<<8OB;;9$  >.2> >8;> >   Sy GGCLLL }Tz

	#

	(			a58#	/	!	!		#U+EE 	 	 	EHHM4MMMMM       	
 
#	#	#!"%%	#xzzuMT***bggdmm<<Q?DEe$$EE 	<EHHIII    :D::;;;	q	%z"" 
	A 
	AA8::DD    5     $zzz2774==AA!DSbSIYv..//// A  MTMM    !!?!?!?@@@
	A e5==J&E%<<MM%++A.E{2!##ff5 M%1G1G)H)HIIE5zzQa 
a;s'   % A A	E 
F*FFc                  t          j        d|                     d                    d         }t          t          j        | d|                     |                    d                   }t          j        d|                     d                    \  }}|dk    r:t          j        d|                     d                    }|d         |d         z  }nlt          j        d|                     d                    d         }t          t          j        | d|                     |                    d                   }|||d	S )
z8Read UIC ImagePropertyEx or PlaneProperty tag from file.r  rW   r   r  z<IBr  IIrY  )ru   r=  rU  )rj  r@  r?  r  )rq  rw   ru   r=  r  rU  s         r   r  r  I  s   =bggajj))!,DV]d:::rwwt}}==a@AAD-rwwqzz22KE4qyydBGGAJJ//a58#}S"''!**--a0MT***bggdmm44Q7
 
 55999r   c               4   |dk    rt          d          t          j        d|                     d                    \  }}|dvrt          d          |                     dt
          j                   t          j        }|t          j
        |          j        k     rHg }d}	|D ]@\  }
}|	t          j
        |          j        z  }	|	|k    r n|                    |
|f           An|}t          |                     t          j
        |          |                    }t          j                                        D ]\\  }
}||                    d
|
z   d          }|dk     r(|                     |           	  ||           ||
<   M# t           $ r Y Yw xY w|S )z$Read CZ_LSMINFO tag value from file.rk   zinvalid CZ_LSMINFO structure<IIrY  >   LI LI ir   r  Nrq  )r   rj  r@  r?  ra  r  r  r   r  r  r~   r  r   r  r	  r  r:  rY  )rq  r   r~   r  rJ  magic_numberstructure_sizer  lsminforw   ru   typestrr  readerrv   s                  r   r  r  I  s    C7888#)=

#C#C L.///7888GGBJJ//888)+' 	, 	,MD'EK((11Dn$$NND'?++++
u{7++yAA F
 /5577 
 
f>HtOQ//A::
	!6"::F4LL 	 	 	D	Ms   9F
FFc                   t          j        d|                     d                    d         }|                     d|          S )z%Read LSM channel data type from file.r  r  r   r!  r  rj  r@  r?  re  rq  rw   s     r   r  r  J  s8    =rwwqzz**1-D==d=+++r   c                   t          j        d|                     d                    d         }|                     d|          S )z-Read LSM channel wavelength ranges from file.<ir  r   z<2f8rF  rG  rH  s     r   r  r  J  8    =rwwqzz**1-D==t=,,,r   c                   t          j        d|                     d                    d         }|                     d|          S )zRead LSM positions from file.r  r  r   z<3f8rF  rG  rH  s     r   r  r  J  rK  r   c               
   t          j        d|                     d                    \  }}|dd|z  z   k    r6t                                          d           t          j        dd          S |                     d|          S )zRead LSM time stamps from file.z<iirY  z;<tifffile.read_lsm_timestamps> invalid LSM TimeStamps blockr  <f8rF  )rj  r@  r?  r=   rs  r  r  re  )rq  rw   r  s      r   r  r  J  s}    -rwwqzz22KD%AII	
 	
 	
 {4'''==e=,,,r   list[tuple[float, int, str]]c               Z   t          j        d|                     d                    d         }g }|dk    rtt          j        d|                     d                    \  }}}t          |                     |dz
                      }|                    |||f           |dz  }|dk    t|S )zCRead LSM events from file and return as list of (time, type, text).r=  rY  rW   r   z<IdIr  )rj  r@  r?  r  r   )rq  r  eventsesizeetimeetypeetexts          r   r  r  %J  s    M%,,Q/EF
!))$mFBGGBKK@@ue"''%"*--..ueU+,,,
	 !))
 Mr   c               V   dg g d}|                                  }t          j        d|                     d                    \  }}}}}}||k    r#t	                                          d           |S t          |          |d<   |                     ||z              |                     t          j
        |dz            }	|	                    |df          }	|	                                |d	<   |                     ||z              |                     ||z
            }
g }t          |
          dk    rpt          j        d
|
dd                   d         }|                    t          |
dd|z                                 |
d|z   d         }
t          |
          dk    p||d<   |S )z+Read LSM ChannelColors structure from file.F)Monor  
ColorNamesz<IIIIIIrG  zE<tifffile.read_lsm_channelcolors> invalid LSM ChannelColors structurerW  r  rF  r  r  Nr   r   rX  )r]  rj  r@  r?  r=   rs  r   ra  re  r  r  rz  r  r   r   r  )rq  r  rr  rw   ncolorsnnamescoffsetnoffsetmonocolorsr	  r  s               r   r  r  1J  s   r<<F
''))C6<m2772;;7 73T7FGWd &2	
 	
 	
 $ZZF6NGGC'M]]5;gk]::F^^WaL))F}}F8GGC'MWWTG^$$FE
f++//}T6"1":..q1Yva!d(l344555D

# f++// !F<Mr   c               R   i }t          j        d|                     d                    \  }}}}}}|dk     r#t                                          d           |S |                     d           t
                              |          |d<   ||d<   ||d<   ||d	<   g x|d
<   }t          |          D ]}	t          j        d|                     d                    d         }
|
dk    r nt          j        d|                     d                    d         dz
  }|
dk    r|                     d|          }n9|
dk    r|                     d|          }n|
dk    r|                     d|          }n|
dk    r0|                     d|dz            }|	                    d          }n|
dk    rdt          j        d|                     d                    d         }|                     d||z  dz            }|	                    ||df          }n\|
dk    r0|                     d|dz            }|	                    d          }n&t                                          d|
             n2|
                    t
                              |
          |d           |S )z!Read LSM lookup tables from file.z<iiiiiirG  <   zB<tifffile.read_lsm_lookuptable> invalid LSM LookupTables structure$   LutTypeAdvancedNumberChannelsCurrentChannel	SubBlocksrJ  r  r   rY  rW   rN  rF  r  r   z<i4)rT  r  r  r  r  z<i2r  )rT  r  z:<tifffile.read_lsm_lookuptable> invalid LSM SubBlock type )rg  Data)rj  r@  r?  r=   rs  r   r  r  re  rz  r   r  )rq  r  rw   
nsubblocks	nchannelsluttypeadvancedcurrentchannel	subblocksr	  sbtyper   nknotss                r   r  r  PJ  s   F 	i--byy1	
 	
 	
 GGENNN++G44F9!F:(F-F&((F;): 
 
tRWWQZZ003Q;;E}T2771::..q1A5Q;;==i=88DDq[[==i=88DDq[[==i=88DDq[[==i!m=<<D<<
++DDq[[]444Q7F==i&.@1.D=EED<<FA 677DDq[[==i$.>=??D<<
++DDHH6-36 6   E..v66EE	
 	
 	
 	
 Mr   c                  i }|g}t           j        }t          j        d|                     d                    d         dk    r#t                                          d           |S |                     d           	  |d|                     d	                    \  }}}|d
k    r#t          |                     |                    }nZ|dk    r& |d|                     d                    d         }n.|dk    r& |d|                     d                    d         }nd}|t          j        v r1|                    |           t          j        |         }g }	|	||<   |	}n|t          j	        v r/|                    |           i }
|                    |
           |
}nH|t          j
        v r||t          j
        |         <   n$|dk    r|                                }n	||d|d<   |sno|S )z&Read LSM ScanInfo structure from file.r  r  r   r  z;<tifffile.read_lsm_scaninfo> invalid LSM ScanInfo structurerY  Tz<IIIr  r  rJ  r  z<dr  Entry0xr  )rj  r@  r?  r=   rs  r  r   r  r   r  r~  r  )rq  blockblocksr@  entryr~   rw   rU  ru   newlistnewdicts              r   r  r  J  s    EWF]F}T2771::&&q)Z77I	
 	
 	
 GGAJJJ##VFBGGBKK88udA::bggdmm,,EEaZZF4,,Q/EEaZZF4,,Q/EEED333MM%   259D,.G!E$KEEd666MM%   &(GLL!!!EEd999@EE$5e<==j  JJLLEE */E%E%%%& 	G#H Lr   c                  i }t          j        d|                     d                    \  }}}}	}
}}}|dk    rt          d          t	          |          |d<   	 t          d|z   |
dz   |	||          |d<   n# t          $ r Y nw xY w|                     d	|z            }t          d
|d	z  d	          D ]}t          j        d|||d	z                      \  }}}|                     |           |dk    r~t          j        d|                     d                    \  }}}}}}t          j	        d|          }||z  |d<   ||z  |d<   ||d<   t	          |          |d<   t	          |          |d<   |dk    rƌ|S )ziRead OlympusSIS structure from file.

    No specification is available. Only few fields are known.

    z<4s6xhhhhh6x32shr`  s   SIS0zinvalid OlympusSIS structureru   il  rW   rT   rY  r   z<hhIz<10xhdd8xd2x34s32sp   r  
pixelsizex
pixelsizeymagnification
cameranamepicturetype)
rj  r@  r?  r   r  rn  r  ra  rx  pow)rq  r   r~   r  rJ  r  magicminutehourdaymonthyearru   tagcountr   r  tagtyperv   lenexpxcalycalr  camnamepictyperN  s                            r   r  r  J  s     F>DmBGGBKK? ?;UFD#udD( 7888t__F6N%4KCv
 
z     771x<  D1hlA&&  !'vtAAI!G!G
a<<:@-$bggcll; ;7VT4gw V$$A#'!8F< #'!8F< &)F?##,W#5#5F< $-g$6$6F=!!]]  Ms   A9 9
BBc                   	 t          t          |                     |                              S # t          $ r1}t	                                          d|d           i cY d}~S d}~ww xY w)z%Read OlympusSIS INI string from file.z&<tifffile.olympusini_metadata> raised r9  N)olympusini_metadatar  r?  r  r=   rs  )rq  r   r~   r  rJ  r  s         r   r  r  J  sy    "9RWWU^^#<#<===   N#NNNOOO						s   .1 
A,&A'!A,'A,c                   i }t           j        }|                     t          j        |          |          }|D ]"\  }}	||                                         ||<   #|d         dk    rt           j        }
|                     t          j        |
          |          }|d         dk    r#t                                          d           i S |
D ]d\  }}	|		                    d          r-t          ||                                         dd	          ||<   G||                                         ||<   ed
D ](}|d|z   xx         dz  cc<   |d|z   xx         dz  cc<   )n.|j        dk    r#t                                          d           i S |S )z%Read TVIPS EM-MENU headers from file.r  r  r  rZ  l   *UU z:<tifffile.read_tvips_header> invalid TVIPS v2 magic numberr*  r  ignorer|  r      eA	PixelSizerW   z9<tifffile.read_tvips_header> unknown TVIPS header version)r   r!  r	  r  r~   r  r[  r=   rs  r  r  r  rJ  )rq  r   r~   r  rJ  r  	header_v1rI  ru   rC  	header_v2r  s               r   r  r  	K  s     F$I^^EK	22i^HHF" - -gd|**,,tiA(	I 6 6)LL'?j((HHL   I& 	5 	5MD'!!#&& 5(4L((**Hh   t  &d|2244t 	. 	.D&-...#5...;%&&&#-&&&&	. 
1		G	
 	
 	
 	Mr   c               j   i }i }t          |                     |                    }|                                D ]w}|                                }|                    d          ri }|||dd         <   ;	 |                    d          \  }	}
n# t          $ r Y aw xY wt          |
          ||	<   x|S )z'Read FEI SFEG/HELIOS headers from file.r  rW   rT  rQ  )r  r?  
splitlinesr=  r  r  r   r5   )rq  r   r~   r  rJ  r  sectionr   r  rn   rU  s              r   r  r  3K  s      F GRWWU^^$$D!! 
% 
%zz||??3 	G!(F4":	CJC 	 	 	H	e}}Ms   7B
BBc          	     n   ddi}d}t          |                     |                    }|                                D ]v}|                                r|                                },|r	 |                    d          \  }	}
n<# t          $ r/ 	 |                    dd          \  }	}
n# t          $ r Y Y {w xY wY nw xY w|
                                }
d}	 |
                                \  }}t          |t          t          f          }||k    r|}
|}nA# t          $ r4 t          |
t          t          f          }||
k    r|}
|
dv rd}
n|
d	v rd
}
Y nw xY w|	                                |
f||<   |r||xx         |fz  cc<   d}K|dxx         t          |t          t          f          fz  cc<   x|S )zRead Zeiss SEM tag from file.

    See https://sourceforge.net/p/gwyddion/mailman/message/29275000/ for
    unnamed values.

    r  r   NrQ  r  rW   >   NoOffF>   OnYesT)r  r?  r  isupperr  r  r   r  r=  r5   r   r  )rq  r   r~   r  rJ  r  rn   r   r  ru   rU  r  r  r  numbers                  r   r  r  MK  s    !"XF
CRWWU^^$$D!!  8  8<<>> 	8**,,CC 	8"jjooee   "&**S!"4"4KD%%    HH  %
 KKMMED!{{}}1C<00Q;;"ED ! ! !U|44U??"EM))!EEm++ E!  ::<</F3K 'sw&CC2JJJ6$e5577JJJJMsH   -B
B?B+*B?+
B95B?8B99B?>B?=D;EEc               $   |                      t          j        |          }|                    |j                            |                    }t          |          }|d         d|d                  |d<   |d         d|d                  |d<   |S )z*Read NIH_IMAGE_HEADER tag value from file.r  r  Nr  r  r  )r	  r   r  r  r~   r  r  )rq  r   r~   r  rJ  arrr  s          r   r  r  K  s     ...).
D
DC
((39)))44
5
5C3FWo&;{(;&;<F7O$< 2&"2 23F4LMr   *tuple[dict[str, Any], dict[str, Any], int]c                  |                      d           	 t          j        d|                     d                    \  }}|dk    s|dk    rt	          d          |                      d           t          j        d|                     d                    \  }}}}|d	k    s|d
vrt	          d| d| d          n?# t
          $ r}t	          d          |d}~wt          $ r}t	          d          |d}~ww xY wt          t          |                     |          dd                             }|dk    rt          | dd|d          ni }|||fS )aQ  Read ScanImage BigTIFF v3 or v4 static and ROI metadata from file.

    The settings can be used to read image and metadata without parsing
    the TIFF file.

    Frame data and ROI groups can alternatively be obtained from the Software
    and Artist tags of any TIFF page.

    Parameters:
        fh: Binary file handle to read from.

    Returns:
        - Non-varying frame data, parsed with :py:func:`matlabstr2py`.
        - ROI group data, parsed from JSON.
        - Version of metadata (3 or 4).

    Raises:
        ValueError: File does not contain valid ScanImage metadata.

    r   z<2sHr  rU  rX  znot a BigTIFF filer  z<IIIIir  zinvalid magic z or version z numberz"file must be opened in binary modeNz%not a ScanImage BigTIFF v3 or v4 filerT  rW   rk   )
ra  rj  r@  r?  r   r  r  r>   r  r  )	rq  r   rJ  r  size0size1r  
frame_dataroi_datas	            r   r   r   K  s   . GGAJJJK#]62771::>>	7B1222
'-}Wbggbkk'J'J$wuI!6!6DDDGDDD   "7  H H H=>>CG K K K@AAsJK iss(;<<==J27!))yS!UA...Hx((s$   B(C   
C<
CC<'C77C<r  Container[str] | NoneFileHandle | IO[bytes]c                  |h d}|                      d           	 ddd|                     d                   }|                      d           t          j        |d	z   |                     d                    \  }}n"# t          $ r}t          d
          |d}~ww xY wi }|dk    r*||d<   	 t          j        |d	z   |                     d                    \  }}|dk    rN||d<   |dk    rt          d|           t          j        |dz   |                     d                    d         }d|v r\|                     |          }	t          |	          |k    rt          d          t          j        t          |	d                    |d<   n?# t          $ r2}t                                          d| d|d           Y d}~nd}~ww xY w|S 	 t          j        |dz   |                     d                    \  }
}}}}}n<# t          $ r/}t                                          d|d           Y d}~nd}~ww xY wd|v r	 |dk    rt          d|           |                     |          }	t          |	          |k    rt          d          t          j        t          |	d                    |d<   n<# t          $ r/}t                                          d|d           Y d}~nd}~ww xY wd|v r	 |dk    rt          d|           |                      |           t          j        |d	z   |                     d                    \  }}|d k    rt          d!          |                     |d"z            }	t          j        |	|d#z   |d$z                                d%d$          |d<   n<# t          $ r/}t                                          d&|d           Y d}~nd}~ww xY wd'|v rk	 |
d(k    rt          d)|
           |                      |           t          j        |d	z   |                     d                    \  }}|d*k    r[|                      |d+z              t          j        |d	z   |                     d                    \  }}|d*k    rt          d,          |                     |          }	t          |	          |k    rt          d          t          j        t          |	d                    |d'<   nQ# t          j        j        $ r Y n;t          $ r/}t                                          d-|d           Y d}~nd}~ww xY wd|d<   	 |d.k    rd/|v r |                      |           t          j        |d	z   |                     d                    \  }}|d0k    r[|                      |d+z              t          j        |d	z   |                     d                    \  }}|d0k    rt          d1          |                     |          }	t          |	          |k    rt          d          t          j        t          |	d                    |d/<   n/|dk    r||d<   n#|dk    r|dk    rnd/|v rt          d2|           n<# t          $ r/}t                                          d3|d           Y d}~nd}~ww xY w|S )4aw  Return Micro-Manager non-TIFF settings from file.

    The settings can be used to read image data without parsing any TIFF
    structures.

    Parameters:
        fh: Open file handle to Micro-Manager TIFF file.
        keys: Name of keys to return in result.

    Returns:
        Micro-Manager non-TIFF settings, which may contain the following keys:

        - 'MajorVersion' (str)
        - 'MinorVersion' (str)
        - 'Summary' (dict):
          Specifies the dataset, such as shape, dimensions, and coordinates.
        - 'IndexMap' (numpy.ndarray):
          (channel, slice, frame, position, ifd_offset) indices of all frames.
        - 'DisplaySettings' (list[dict]):
          Image display settings such as channel contrast and colors.
        - 'Comments' (dict):
          User comments.

    Notes:
        Summary metadata are the same for all files in a dataset.
        DisplaySettings metadata are frequently corrupted, and Comments are
        often empty.
        The Summary and IndexMap metadata are stored at the beginning of
        the file, while DisplaySettings and Comments are towards the end.
        Excluding DisplaySettings and Comments from the results may
        significantly speed up reading metadata of interest.

    References:
        - https://micro-manager.org/Micro-Manager_File_Formats
        - https://github.com/micro-manager/NDTiffStorage

    N>   r  r  r  DisplaySettingsr   rk   rj   )rU  rV  r  rY  r;  znot a Micro-Manager TIFF fileia r_  i$# MinorVersionzinvalid summary_length r  r  r  znot enough datar  z<<tifffile.read_micromanager_metadata> failed to read NDTiffvz summary settings, raised r9  IIIIIIrG  zD<tifffile.read_micromanager_metadata> failed to read header, raised zinvalid summary_header zN<tifffile.read_micromanager_metadata> failed to read summary settings, raised r  iCzinvalid index_header i4 zinvalid headerrA	  rb  r  rT  zG<tifffile.read_micromanager_metadata> failed to read index map, raised r  izinvalid display_header idr|  zinvalid display headerzN<tifffile.read_micromanager_metadata> failed to read display settings, raised i}r  iezinvalid comments headerzinvalid comments_header zF<tifffile.read_micromanager_metadata> failed to read comments, raised )ra  r?  rj  r@  r  r   r   r  r  r  r=   rs  r  r  rz  decoderJSONDecodeError)rq  r  r   index_headerindex_offsetr  r  summary_headersummary_lengthr   display_headerdisplay_offsetcomments_headercomments_offsetrI  r  s                   r   r   r   K  s   P |EEEGGAJJJC,,RWWQZZ8	



 M)d*BGGAJJ77	
L C C C899sBC Fv!-~	 i$.

;;(()7~&!W,,$B.BB   "(y3

!K!KA!ND  ww~..t99..$%6777$(Jyw/G/G$H$Hy! 	 	 	HH')5' '&' '       	 
 M)h.<<	
N 
 
 
#"# #	
 	
 	
 	
 	
 	
 	
 	

 D	(( !K>!K!KLLL77>**D4yyN** !2333 $
9T7+C+C D DF9 	 	 	HHH;>GH H       	 T	x'' !G!G!GHHHGGL!!!"M)d*:BGGAJJGGMFE   !12227752:&&D!&!1i$&	" "gb!nn :  	 	 	HHA47@A A       	 D  	** !K>!K!KLLLGGN###"M)d*:BGGAJJGGMFE""./// &i$.>

 K KY&&$%=>>>775>>D4yyE!! !2333(,
9T73K3K(L(LF$%%|+ 	 	 	D 	 	 	HHH;>GH H       	 F>
h&&T!!((( &i$.>

 K KX%%GGOe3444$*M)d2BBGGAJJ$O$OMFE))()BCCCwwu~~t99%%$%6777%)Z	$0H0H%I%Iz"&&%4F>""!!o&:&:4IIIJJJ 
 
 
#"# #	
 	
 	
 	
 	
 	
 	
 	

 Ms   A!A? ?
B	BB0C"F 
G(G

G2H 
I%H<<I	A4J> >
K7%K22K7?B;N; ;
O4%O//O4=DT U$,	U$5%UU$-D<Z* *
[#4%[[#RIterator[tuple[dict[str, int | str], str, int, int, int, int, int, int, int, int]]c             #  b  K   t          | d          5 }	 |                    d          }t          |          dk    rnt          j        d|          d         }t          j        |                    |                    }t          j        d|                    d                    d         }|                    |                                          }t          j        d|                    d                    \  }}}	}
}}}}|||||	|
||||f
V  	 ddd           dS # 1 swxY w Y   dS )	ax  Return iterator over fields in Micro-Manager NDTiff.index file.

    Parameters:
        file: Path of NDTiff.index file.

    Yields:
        Fields in NDTiff.index file:

        - axes_dict: Axes indices of frame in image.
        - filename: Name of file containing frame and metadata.
        - dataoffset: Offset of frame data in file.
        - width: Width of frame.
        - height: Height of frame.
        - pixeltype: Pixel type.
          0: 8-bit monochrome;
          1: 16-bit monochrome;
          2: 8-bit RGB;
          3: 10-bit monochrome;
          4: 12-bit monochrome;
          5: 14-bit monochrome;
          6: 11-bit monochrome.
        - compression: Pixel compression. 0: Uncompressed.
        - metaoffset: Offset of JSON metadata in file.
        - metabytecount: Length of metadata.
        - metacompression: Metadata compression. 0: Uncompressed.

    rN  Tr  rJ  r   z	<IiiiiIiir  N)r  r?  r   rj  r@  r  r  r  )r   rq  r	  r   r  r   r  r!  r^  r  r  r   r  r  r  s                  r   r   r   |L  s     @ 
dD		 R	

A1vv{{dA&&q)A
2771::..IdBGGAJJ//2Awwqzz((**H k2772;;77	    %	 	                 s   DD$$D(+D(dict[str, str] | Nonec               *   |                      d           	 |                     d          dvrt          d          |                      ddd|                     d                              |                     d	                                          }|d
d         dk    rd
S t	          |dd                   }|                     |                                          }n# t
          $ r Y d
S w xY wi }	 |                                D ]H}d|v rB|                    dd          \  }}|                                ||                                <   In=# t
          $ r0}t                      
                    d|d           Y d
}~d
S d
}~ww xY w|S )zRead non-TIFF GDAL structural metadata from file.

    Return None if the file does not contain valid GDAL structural metadata.
    The metadata can be used to optimize reading image data from a COG file.

    r   r  >   rU  rV  znot a TIFF filerY  r  )   *   +rW   rX  Nr  zGDAL_STRUCTURAL_METADATA_SIZE=ra  rQ  z0<tifffile.read_gdal_structural_metadata> raised r9  )ra  r?  r   r  r   r  r  r  r=  r=   rs  )	rq  rI  rw   linesr  r  rn   rU  r  s	            r   r   r   L  s    GGAJJJ
771::^++.///
q##BGGAJJ/000##%%#2#;:::46"R%=!!$$&&   tt  F	$$&& 	4 	4Dd{{!ZZQ//
U&+kkmmsyy{{#	4    KsKKK	
 	
 	
 ttttt	
 Ms1   BC$ %>C$ $
C21C28AE 
F %FFr  c                   t           )zRead MetaSeries non-TIFF hint catalog from file.

    Raise ValueError if the file does not contain a valid hint catalog.

    rM  r2  s    r   read_metaseries_catalogr  L  s
     r   Ktuple[tuple[int, int, int, bytes, bool], tuple[int, int, int, bytes, bool]]c          
     (   | sdS ddd|         g}dg}g }d-d}d.d}d/d}d0d}dd|fdd|fdd|fdd|fdd|fdd|fdd|fd d!|ff}	|	D ]3\  }
}}|
                                 | v r|
                                 }
n|
| vr7|d"k    r|d#d#d$         }| |
         }t          |t                    r.d% |                                D             }t	          |          }n*t          |t
                    rt	          |          }n|g}d&}|                    |t          j        |d'z   |          z              |D ]E} |||          }|                    |           |                    t	          |                     F5|sdS d(	                    |          }d(	                    |          }||z   }t	          |          |d<   t          j        |d't	          |          z  z   g|R  }d)d&t	          |          |d*fd+d,t	          |          d,z  |d*ffS )1aa  Return IJMetadata and IJMetadataByteCounts tags from metadata dict.

    Parameters:
        metadata:
            May contain the following keys and values:

            'Info' (str):
                Human-readable information as string.
            'Labels' (Sequence[str]):
                Human-readable label for each image.
            'Ranges' (Sequence[float]):
                Lower and upper values for each channel.
            'LUTs' (list[numpy.ndarray[(3, 256), 'uint8']]):
                Color palettes for each channel.
            'Plot' (bytes):
                Undocumented ImageJ internal format.
            'ROI', 'Overlays' (bytes):
                Undocumented ImageJ internal region of interest and overlay
                format. Can be created with the
                `roifile <https://pypi.org/project/roifile/>`_ package.
            'Properties' (dict[str, str]):
                Map of key, value items.

        byteorder:
            Byte order of TIFF file.

    Returns:
        IJMetadata and IJMetadataByteCounts tags in :py:meth:`TiffWriter.write`
        `extratags` format.

    r      IJIJ   JIJIri   r   r   r   r   r  r   r  c               D    |                      dddd|         z             S Nr  beleri   )rm  r   r   s     r   _stringz$imagej_metadata_tag.<locals>._stringM  &    {{8Dt&<&<Y&GGHHHr   Sequence[float]c               J    t          j        | t          |            dg| R  S )Nr  )rj  rk  r   r  s     r   _doublesz%imagej_metadata_tag.<locals>._doublesM  s.    {i5T555=====r   r   c               *    |                                  S r   )r  r  s     r   _ndarrayz%imagej_metadata_tag.<locals>._ndarrayM  s    ||~~r   c                   | S r   r   r  s     r   _bytesz#imagej_metadata_tag.<locals>._bytesM  r  r   r     infor     lablr     rangr     lutsr     plotr     roi r     overr     proprk   NrT  c                6    g | ]}|D ]}t          |          S r   rC  )r   r(  r  s      r   r:  z'imagej_metadata_tag.<locals>.<listcomp>7M  s+    FFFFFAc!ffFFFFr   rW   r  r   r  Tr  r  )r   r   r   r  r   r  )r   r  r   r  r   r  )r   r   r   r  r   r  r   r  r   r  r   r  )
r  r   r  r:  r   rA  r   rj  rk  r   )r   r   header_listr&  	body_listr  r  r  r  metadata_typesrn   mtyper  rT  r  rU  r   bodyrI  r  s                       r   r<   r<   L  s   H  r w//	:;KSNII I I I> > > >       
'"	7G$	7H%	(#	&!	 	Wf%	w(		  + - -UD99;;(""))++CC  $$B$KE#fd## 	FFFFFFKKEE%% 	KKEEXFE56;y3#F#FFGGG 	- 	-E4y))DT"""!!#d)),,,,	-
  r88IDXXk""FD=DFN1S3~.../2@  J 
3t99dD)	3z??a'T: r   r  r  c          	     L   d%d}d&d	}d'd}d(d}d|fd|fd|fd|fd|fd|fd|fd|fd}|                     d |                                D                        t          |          dk    rt          d          | dd         dvrt          d          |d         }|dk     s|dk    rt          d          |dz
  d z  }	t	          j        |d!|	z  z   | dd|	d z  z                      }
d|	d z  z   }d}i }t          |
ddd"         |
d#dd"                   D ]\  }}g }|                    |t          |          |f          \  }}t          |          D ];}|d#z  }|||         z   }|
                     || ||         |                     |}<|d#k    r|d         n|||                                <   |                    d          rPt                    d"z  dk    r:t          fd$t          dt                    d"          D                       |d<   |S ))a8  Return IJMetadata tag value.

    Parameters:
        bytes:
            Encoded value of IJMetadata tag.
        bytecounts:
            Value of IJMetadataByteCounts tag.
        byteorder:
            Byte order of TIFF file.

    Returns:
        Metadata dict with optional items:

            'Info' (str):
                Human-readable information as string.
                Some formats, such as OIF or ScanImage, can be parsed into
                dicts with :py:func:`matlabstr2py` or the
                `oiffile.SettingsFile()` function of the
                `oiffile <https://pypi.org/project/oiffile/>`_  package.
            'Labels' (Sequence[str]):
                Human-readable labels for each channel.
            'Ranges' (Sequence[float]):
                Lower and upper values for each channel.
            'LUTs' (list[numpy.ndarray[(3, 256), 'uint8']]):
                Color palettes for each channel.
            'Plot' (bytes):
                Undocumented ImageJ internal format.
            'ROI', 'Overlays' (bytes):
                Undocumented ImageJ internal region of interest and overlay
                format. Can be parsed with the
                `roifile <https://pypi.org/project/roifile/>`_  package.
            'Properties' (dict[str, str]):
                Map of key, value items.

    r   r  r   r  r   r   c               D    |                      dddd|         z             S r  )r  r  s     r   r  z imagej_metadata.<locals>._stringzM  r  r   tuple[float, ...]c               X    t          j        |dt          |           dz  z  z   |           S )Nr  rY  )rj  r@  r   r  s     r   r  z!imagej_metadata.<locals>._doubles}M  s(    }Y#Ta*@A4HHHr   NDArray[numpy.uint8]c               h    t          j        | t           j                                      dd          S )NrT  r  )r  r  r  rz  r  s     r   _lutzimagej_metadata.<locals>._lutM  s'    ek22::2sCCCr   c                   | S r   r   r  s     r   r  zimagej_metadata.<locals>._bytesM  r  r   r  r  r  r  r  r  r  r  )r  r  r  r  r  r  r  r  c                ,    i | ]\  }}|d d d         |S )NrT  r   r
  s      r   r  z#imagej_metadata.<locals>.<dictcomp>M  s(    III$!Q1TTrT7AIIIr   r   zno ImageJ metadataNr  >   r  r  zinvalid ImageJ metadatar  i$  z#invalid ImageJ metadata header sizerY  4sIr  rW   c              3  2   K   | ]}||d z            V  dS rr
  r   )r   r  r  s     r   r   z"imagej_metadata.<locals>.<genexpr>M  s@       $
 $
 !DQUO$
 $
 $
 $
 $
 $
r   )r   r  r   r  r   r   )r   r  r   r  r   r  )r   r  r   r  r   r  r  )r  r:  r   r   rj  r@  r  rY  r  r  r   r=  r  )r   r  r   r  r  r  r  r  header_sizentypesrI  rr  counterr  r  r  rT  ru   r  r	  pos1r  s                        @r   r  r  SM  s   NI I I II I I ID D D D    '"G$H%$&!f%(		 		  II.2F2F2H2HIIIJJJ
:!-...BQBx)))2333Q-KR;,,>???Ao!#F]EFN"DQ!^);$< F fqj.CGFF33Q3K166 C Cu#''	%0@0@&/IJJ
du 	 	AqLGG,,DMM$$tCH~y99:::CC,1QJJvayyFtzz||::l##D 
D		A""# $
 $
 $
 $
%*1c$ii%;%;$
 $
 $
  
  
| Mr   c                  d
d}i }|                                  D ]}	 |                    d          \  }}n# t          $ r Y (w xY w|                                }|                                }t          t
          |fD ]}	  ||          } n# t          $ r Y w xY w|||<   d|vrd|vrt          d	|          |S )a0  Return metatata from ImageJ image description.

    Raise ValueError if not a valid ImageJ description.

    >>> description = 'ImageJ=1.11a\nimages=510\nhyperstack=true\n'
    >>> imagej_description_metadata(description)  # doctest: +SKIP
    {'ImageJ': '1.11a', 'images': 510, 'hyperstack': True}

    r  r   r   r   c               <    ddd|                                           S )NTF)r
  r
  r=  )r  s    r   _boolz*imagej_description_metadata.<locals>._boolM  s    u--ciikk::r   rQ  ImageJSCIFIOz not an ImageJ image description )r  r   r   r   )r  r  r  r=  r   r  r   )r   r  r  r  rn   r  r~   s          r   r  r  M  s   ; ; ; ;  F&&((  	zz#HC 	 	 	H	iikkiikk5%( 	 	EeCjj   sv(&"8"8FFFFGGGMs!   7
AAB
BBr  r  r  c                  |                     dd          }|                     dd          }|                     dd          }|                     dd          }|rd}d}t          | ||          } | d	         d
v }g }	d| g}
|
                    dt          | dd                               |d}|	                    d           n7|	                    dt	          |                                                      | d         dk    r|
                    d| d                     ||s|sd}|r|r|	                    d|            | d         dk    r|
                    d| d                     | d         dk    r5|
                    d| d                     ||	                    d           |7|	                    dt	          |                                                      |                                D ]k\  }}|dvrbt          |t                    r!t          |                                          }|	                    |                                 d|            ld	                    |
|	z   dgz             S )a  Return ImageJ image description from data shape and metadata.

    Parameters:
        shape:
            Shape of image array.
        axes:
            Character codes for dimensions in `shape`.
            ImageJ can handle up to 6 dimensions in order TZCYXS.
            `Axes` and `shape` are used to determine the images, channels,
            slices, and frames entries of the image description.
        rgb:
            Image is RGB type.
        colormaped:
            Image is indexed color.
        **metadata:
            Additional items to be included in image description:

            hyperstack (bool):
                Image is a hyperstack.
                The default is True unless `colormapped` is true.
            mode (str):
                Display mode: 'grayscale', 'composite', or 'color'.
                The default is 'grayscale' unless `rgb` or `colormaped` are
                true. Ignored if `hyperstack` is false.
            loop (bool):
                Loop frames back and forth. The default is False.
            finterval (float):
                Frame interval in seconds.
            fps (float):
                Frames per seconds. The inverse of `finterval`.
            spacing (float):
                Voxel spacing in `unit` units.
            unit (str):
                Unit for `spacing` and X/YResolution tags.
                Usually 'um' (micrometer) or 'pixel'.
            xorigin, yorigin, zorigin (float):
                X, Y, and Z origins in pixel units.
            version (str):
                ImageJ version string. The default is '1.11a'.
            images, channels, slices, frames (int):
                Ignored.

    Examples:
        >>> imagej_description((51, 5, 2, 196, 171))  # doctest: +SKIP
        ImageJ=1.11a
        images=510
        channels=2
        slices=5
        frames=51
        hyperstack=true
        mode=grayscale
        loop=false

    rt   N
hyperstackloopr  z1.11aFr  rT  r  r|  zimages=r  Tzhyperstack=truezhyperstack=r  rW   z	channels=	grayscalezmode=zslices=r   zframes=z
loop=falsezloop=>   r  rx  rk  r  r  rQ  rA  r  )
r  rZ  r   rD   r   r  r:  r   r   r   )r   r  r  r  r   rt   r  r  rJ  r   r  rn   rU  s                r   r;   r;   M  s   | <<%%DlD11J<<%%Dll8W--G 
Cd333E
)v
CF!!!"F
MM1GE#2#J//11222
'((((6D$4$466<<>>???Qx!||,%(,,---|C|
| &d &ndnn%%%Qx!||*a**+++Qx!||*a**+++<MM,'''*d4jj**0022333nn&& 4 4
UJJJ%&& +E

((**MMSYY[[2252233399Vf_t+,,,r   r  r  c              d   t          d | D                       } t          |           }d|cxk    rdk    rn nt          d          |rt          |          |k    rt          d          d}|                                }|D ].}d                    |          }||k     rt          d          |}/t          |          }g }d}dD ]J}||k     r-|||         k    r!|                    | |                    |dz  }5|                    d           K|d	         d
vrt          d          t          |          S || d	         dv o|dk    }|r| d	         dvrt          d          |s!|dk    r| d	         dk    rt          d          |s| d	         dk    rdd|z
  z  | z   S dd|z
  z  | z   dz   S )zReturn shape normalized to 6D ImageJ hyperstack TZCYXS.

    Raise ValueError if not a valid ImageJ hyperstack shape or axes order.

    >>> imagej_shape((2, 3, 4, 5, 3), rgb=False)
    (2, 3, 4, 5, 3, 1)

    c              3  4   K   | ]}t          |          V  d S r   r  r  s     r   r   zimagej_shape.<locals>.<genexpr>TN  s(      ((Q#a&&((((((r   rW   r  z)ImageJ hyperstack must be 2-6 dimensionalz-ImageJ hyperstack shape and axes do not matchr   TZCYXSz.ImageJ hyperstack axes must be in TZCYXS orderrT  >   rW   r   r  z1ImageJ hyperstack must contain 1, 3, or 4 samplesNr  r  z$ImageJ hyperstack is not a RGB imagez*ImageJ hyperstack is not a grayscale imager  r  )r  r   r   rT  r  r   )	r   r  r  r  r  rv  r6  ndimsnewshapes	            r   rZ  rZ  EN  s$    ((%(((((Eu::D4||||!|||||DEEE t99LMMMzz|| 	 	Bb!!A1uu D   AAD		 	# 	#B5yyR47]]a)))Q""""B<y((C   X
{Bi6!.dQh
 AuRy&&?@@@ G4199raEFFF
 )eBi1nnq4x 5((1t8u$t++r   r?  #tuple[int | None, int | str | None]c                   d}d}|rn9| dk    rd}n0| dk    r|sd}d}n#| dk    rd}n| dk    rt          |           j        }|dk    rd}||fS )z>Return JPEG and output color space for `jpeg_decode` function.Nr  r  r  r  r   rW   )r&   ru   )r   r   r   r?  r  r  s         r   r  r  N  s     "J&*M 6						 	J				q#K005q}$$r   jpegrZ  c                  d}|t          |           k     rt          j        d| ||dz                      d         }|dz  }|dk    rE|dk    rnd|cxk    rdk    rn n]|dk    rdt          j        d| ||dz                      d         }|dz  }d	|cxk    rd
k    r#n n t          j        d| ||dz                      S |dk    rn||dz
  z  }|t          |           k     t          d          )z(Return bitdepth and shape of JPEG image.r   r  r              i  >BHHBr    zno SOF marker found)r   rj  r@  r   )r  r  markerr_  s       r   r   r   N  s:   	A
c$ii--tT!a!e)_55a8	QVVV%%%%v%%%%%VtT!a!e)_55a8	QV%%%%v%%%%%=$q1q5y/:::V 	
VaZ9 c$ii--< *
+
++r   tuple[int, int, bytes]c                  d}d}d}d}|t          |           k     rut          j        d| ||dz                      d         }|dz  }|dk    rF|dk    rn;d|cxk    rdk    rn n_|dk    rft          j        d| ||dz                      d         }|dz  }|d	k    r't          j        d| ||dz                      d         }n|d
k    r|dz   }t          j        d| ||dz                      \  }}}	}
|dz  }d}d}t          |
          D ]G}t          j        d| ||dz                      \  }}}|dz  }|dz	  |k    r|dz	  }|dz  |k    r|dz  }H|dz  }|dz  }|dz
  }n|dk    r	||z   dz
  }n||dz
  z  }|t          |           k     u|dk    s|dk    s|dk    rt	          d          |}||z  }| d|         t          j        d||          z   | |dz   |         z   }|||fS )zAReturn tile shape and JPEG header from JPEG with restart markers.r   r  r  r  r  r  r  r  i  r  rW   r  r  z>BBBr   r  r  rY  r  zmissing required JPEG markersNr  )r   rj  r@  r  r   rk  )r  restartinterval	sofoffset	sosoffsetr  r	  r_  r1  r]  r^  ncomponentsmcuwidth	mcuheightr	  cidfactortabler  r  r  s                       r   r-  r-  N  s    OIIA
c$ii--tT!a!e)_55a8	QVVV%%%%v%%%%%VtT!a!e)_55a8	QV$mD$q1q5y/BB1EOOvAI8>a!a%i9 95Ix+ FAHI;'' 4 4%+]64AE	?%K%K"VUQQ;))%{HJ&22 & 3IMHNIAAAvF
QI 	
VaZe c$ii--h !yA~~a8999 J(*IZiZ
+eZ
3
3	4
y1}y(
)	* 
 y*,,r   c               V    |                     |            t          j        |          S )zReturn JSON image description from data shape and other metadata.

    Return UTF-8 encoded JSON.

    >>> shaped_description((256, 256, 3), axes='YXS')  # doctest: +SKIP
    '{"shape": [256, 256, 3], "axes": "YXS"}'

    rf  )r  r  dumps)r   r   s     r   rl  rl  O  s(     OO%O   :hr   c                  | dd         dk    r8t          d | dd                             d          D                       }d|iS | dd	         d
k    r"| dd         dk    rt          j        |           S t	          d|           )a  Return metatata from JSON formatted image description.

    Raise ValueError if `description` is of unknown format.

    >>> description = '{"shape": [256, 256, 3], "axes": "YXS"}'
    >>> shaped_description_metadata(description)  # doctest: +SKIP
    {'shape': [256, 256, 3], 'axes': 'YXS'}
    >>> shaped_description_metadata('shape=(256, 256, 3)')
    {'shape': (256, 256, 3)}

    Nr  ry  c              3  4   K   | ]}t          |          V  d S r   r  r  s     r   r   z.shaped_description_metadata.<locals>.<genexpr>)O  s(      CCc!ffCCCCCCr   r  rT  r  r   rW   rx  }zinvalid JSON image description)r  r  r  r  r   )r   r   s     r   r  r  O  s     2A2(""CCk!B$&7&=&=c&B&BCCCCC2A2#+bcc"2c"9"9z+&&&
5{
C
CCr   ignoresectionsc               ,   |                      d          st          d          |ddh}i }|g}d}|                                 D ]}|s|                                }|s|d         dk    r|dd         d	k    rv|d
= |d
         }|dd         }|rd                    ||                   ||<   |dd         dk    r2t          j        ||         t
          j                  }d|_        |||<   d}|dd
         }|dd         dk    rg }n||v rg }d}ni }|	                    |           |||<   |r|	                    |           |
                    dd          }	t          |          dk    rd||	d                                         <   P|	\  }
}|
dd         dk    r3|                    d |
                                D                        t          |                                          ||
                                <   |S )au  Return metatata from FluoView image description.

    The FluoView image description format is unspecified. Expect failures.

    >>> descr = (
    ...     '[Intensity Mapping]\nMap Ch0: Range=00000 to 02047\n'
    ...     '[Intensity Mapping End]'
    ... )
    >>> fluoview_description_metadata(descr)
    {'Intensity Mapping': {'Map Ch0: Range': '00000 to 02047'}}

    r  z"invalid FluoView image descriptionNzRegion Info (Fields)zProtocol DescriptionFr   z End]rT  rW   rA  r  zLUT r~  )rT  r   TrQ  zRGB c              3  4   K   | ]}t          |          V  d S r   r  )r   r  s     r   r   z0fluoview_description_metadata.<locals>.<genexpr>tO  s(      ==3s88======r   )r  r   r  r=  r   r  r^  r  r   r   r  r   rQ  r5   )r   r  r  sectionscommentr  r  ru   r  r  rn   rU  s               r   fluoview_description_metadatar   1O  sX   " !!#&& ?=>>>02HI  FxHG&&(( +9 +9 	 ::<<D 	7c>>BCCyG##RL"2,AbDz =$(IIgdm$<$<GDM8v%%GDMEEEA#AG$%GDMG":DBQBx6!!''OOG$$$"F4L 	NN4   

3""t99>>(,GE!HNN$$%
Urr7fNN==u{{}}=======#)%++--#8#8GCIIKK  Mr   c               `   i }|                      d          s|S dD ]}|                     |d          } |                     d          D ]`}|dd         dk    r|                                d         }d         t          j        vrY	 t          d                              d	          |d
<   n0# t          $ r# d                    dd                   ||<   Y nw xY wt          j        d                  \  }t          |d         t                    r|d                  }nfd|D             }t          u r|d         dk    rdg}t          fd|D                       }t          u rd                    |          }nt          |          dk    r|d         }|||<   b|S )a  Return metatata from Pilatus image description.

    Return metadata from Pilatus pixel array detectors by Dectris, created
    by camserver or TVX software.

    >>> pilatus_description_metadata('# Pixel_size 172e-6 m x 172e-6 m')
    {'Pixel_size': (0.000172, 0.000172)}

    r  z#:=,()r!  rA  Nr  r?  r   %Y-%m-%dT%H %M %S.%frn  rW   c                     g | ]
}|         S r   r   )r   r  r  s     r   r:  z0pilatus_description_metadata.<locals>.<listcomp>O  s    ///!d1g///r   notNaNc              3  .   K   | ]} |          V  d S r   r   r   r  r~   s     r   r   z/pilatus_description_metadata.<locals>.<genexpr>O  s+      00AuuQxx000000r   )r  r  r  r   r  rH   r   r  r   ra  r  r  r   r   )	r   r  r  r  ru   r  rT  r~   r  s	          @@r   r  r  zO  s     F!!$''  2 2!))!S11""4((  !9{{}}Aw7$---2%-HHTNN$:& &z""  2 2 2"xxQRR11t2,T!W5gaj%(( 	0'!*%FF////w///FE>>fQi500WF000000000C<<XXf%%FF[[AAYFtMs   &B66*C#"C#c               L   |                      d          st          d          i }|                     d          }|d         |d<   |dd         D ]R}|                    dd	          \  }}t          |                                          ||                                <   S|S )
zReturn metatata from Aperio image description.

    The Aperio image description format is unspecified. Expect failures.

    >>> svs_description_metadata('Aperio Image Library v1.0')
    {'Header': 'Aperio Image Library v1.0'}

    r  z invalid Aperio image descriptionrR  r   HeaderrW   NrQ  )maxsplit)r  r   r  r5   r=  )r   r  r:  r(  rn   rU  s         r   svs_description_metadatar+  O  s     !!),, =;<<<Fc""EQxF8abb	 4 4ZZaZ00
U$U[[]]33syy{{Mr   c                  |                                  } | sg S g }|                     d          D ]}i }|                    d          D ]}|                    dd          }t          |          dk    r<|\  }}t          |                                           ||                                 <   g|d                                          }|r&d|v r|d                             |           |g|d<   |                    |           |S )zReturn metadata from MetaMorph image description.

    The MetaMorph image description format is unspecified. Expect failures.

    r  
r  rW   r   r  )r=  r  r   r5   r   )r   r  planer  r  r  ru   rU  s           r   stk_description_metadatar/  O  s    ##%%K 	 F""6**  KK'' 	( 	(DJJsA&&E5zzA~~#e"("7"7$**,,a(( (Qww"U++++!&"aMr   c               .   |                      d          st          d          ddl}ddlm} |                    |           }t          t          d d |j        ddfd |i           }d|v r|d         	                    dd          |d<   |S )z2Return metatata from MetaSeries image description.r  z$invalid MetaSeries image descriptionr   Nr  c                $    t          | dd          S )Nonr8  )asboolr  s    r   r  z1metaseries_description_metadata.<locals>.<lambda>O  s    &D%00 r   c                "    t          | d          S )N%Y%m%d %H:%M:%S.%f)rH   r  s    r   r  z1metaseries_description_metadata.<locals>.<lambda>O  s    (1&:;; r   )r  r   r   r-
  guidrS  etree.Elementr  r  r   c                   | D ]p}|j         }|s |i           ||j        <    d|v rL|d         }|d         }|d         }|v r+	  |         |          ||<   V# t          $ r |||<   Y gw xY w|||<   q|S )Nr  r~  rU  )r*  r9  r  )	rS  r  childr*  r  r  r  rI	  typess	          r   rI	  z.metaseries_description_metadata.<locals>.parseO  s      	" 	"E\F $)E%$4$4uy!v~~4L6N7O::&$,E!HQKKq		$ & & &$%q			& !"F1Is   AA,+A,r
  z
&#13;&#10;rA  )rS  r7  r  r  r   r  )
r  r   r  r  r  r  r  r   r`  r  )r   r  r  rS  adictrI	  r:  s        @@r   r  r  O  s    !!,// A?@@@KKK......K((D00;;	, ,E      , E$OOE$]3;;L$OOmLr   c                    t          |           S )z1Return metatata from ScanImage image description.)r>   r  s    r   scanimage_description_metadatar=  P  s    $$$r   artistc                   	 t          j        |           S # t          $ r/}t                                          d|d           Y d}~nd}~ww xY wdS )z*Return metatata from ScanImage artist tag.z,<tifffile.scanimage_artist_metadata> raised r9  N)r  r  r   r=   rs  )r>  r  s     r   scanimage_artist_metadatar@  P  s    
z&!!! 
 
 
G3GGG	
 	
 	
 	
 	
 	
 	
 	

 4s    
A%A

Ainistrc          
        d#d}i }g }d}d}|                                  D ]}|                                }|dk    s|d         d	k    r*|d         d
k    r|d         dk    r|dd         }i x||<   }|dk    rg x|d<   }	g x|d<   }
h|dk    rg ||<   t|dk    rd|v rg x||         d<   }|dk    rd|v rg x||         d<   }|dk    r.|d         d         }d t          |          D             }|||<   d}|                    d          \  }}|                                dk    rd}n@d|v r-t	          d |                    d          D                       }nt          |          }|dk    r1|||<   |	                    |           |
                    |           |dk    r2|dk    ri g|z  |d<    ||          \  }}||d         |         |<   |dk    r|dd         dk    r|||         d         }t          j        d|          }|                    t          |dd                   t          |dd                   t          |dd                   g           K ||          \  }}|||         |<   f|dd          dk    r||                    |           |dd!         dk    r||                    |           |||<   d|v rdd"i}g }	g }
t          |d         |d                   D ]a\  }}|dk    rV|	                    |                    ||d                                                              |
                    |           bd                    |	          |d<   t	          |
          |d<   	 t          j        |d         d         d|d         d                  t          j                  |d         d<   n# t"          $ r Y nw xY w	 t          j        |d         d         d|d         d                  t          j                  |d         d<   n# t"          $ r Y nw xY w|D ]*}t          j        |d         t          j                  |d<   +|S )$zUReturn OlympusSIS metadata from INI string.

    No specification is available.

    rn   r   r   tuple[str, int]c                   d}t          |                     d                    }|t          |           k     r$t          | |d                    dz
  }| d |         } | |fS )Nr   
0123456789rW   )r   r  r   )rn   r  r  s      r   keyindexz%olympusini_metadata.<locals>.keyindex%P  s^    

<(())s3xx<<ABBLL1$Ebqb'CEzr   Nr  r   ;r  rT  r  rW   	Dimensionr  r   ASDr  r  r  TimePosBandc                    g | ]}d g iS )LUTr   )r   r	  s     r   r:  z'olympusini_metadata.<locals>.<listcomp>GP  s    <<<%<<<r   rQ  r  c              3  4   K   | ]}t          |          V  d S r   )r5   r  s     r   r   z&olympusini_metadata.<locals>.<genexpr>OP  s(      BBAfQiiBBBBBBr   Countr   rM  r  r  r  r  r  )rn   r   r   rC  )r  r=  r  r  r  r5   r   rj  rk  ordr  rY  rT  r   r  r^  rO
  r  r  r  )rA  rF  r  bandszpostposr  section_namer  r  r   nbandsibandrn   rU  r  lutsisaxesr  r  bands                        r   r  r  P  s0        F"$E!D!D!!## 9% 9%zz||2::aC7c>>d2h#oo":L-//F< 7{**(**v*,,w%%&&')|$$$$&((:<<F<(04''&((=??F<(3d'',V4<<eFmm<<<',|$CJC{{}}""BBS1A1ABBBBBu{**$C   U####&&'>>%'D5LF5MM!)#JC05F5M%(--''rr7e##,u-C"Ke44EJJU1Q3Z#eAaCj//3uQqSz??K    "*#JC(-E%L%%RaRF""t'7E""""RaRI%%$*:E""""$3-w88 	  	 DAq1uuGKK1Q4::<<88999Qv,,w#k3K :&"5c": :;U]
 
sF    $)K6N9%&C{(;F(C&CDK%
 %
vy!!     < <k$u+u{;;UMs&   AO 
O'&O'+AP4 4
Q Qr  sepc                 	 d}i }i }|                                  D ]8}|                                }|s|dd                                         }|dd         }|                    d          s>|| dz   |vr|||| dz   <   d||<   n"|||| ||          z   <   ||xx         dz  cc<   |dd         }d|v r.|                    dd          \  }}|                                }nd}|                                }|sd}n|d	         d
k    rt	          |          dk     r+t                                          || d|z              5|d         d
k    r|dd         }nqd
|v rd|v s+t                                          || d|z              |dd                                         dd                             d
d          \  }}|                    dd          d                                         }n|d	         dk    rW|d         dk    rK|dd         }d|v rt          nt          	t          	fd|                    d          D                       }nq|dk    rd}nh|dk    rd}n_d|v rt          |          }nK	 t          |          }n:# t          $ r- t                                          || d|z              Y w xY w||v r't                                          || dz              |||<   |rH|||| dz   <   |d	         dk    r1d|v r-|dd                             dd          d	         ||| dz   <   :|S )z1Return metatata from AstroTIFF image description.z*<tifffile.astrotiff_description_metadata> NrY  rQ  0rW   /r  r   r   r  z: invalid string rT  r<  r	  r  r  c              3  R   K   | ]!} |                                           V  "d S r   )r=  r'  s     r   r   z1astrotiff_description_metadata.<locals>.<genexpr>P  s5      EEq%%		**EEEEEEr   r  r  Tr}
  Fz: invalid value z: duplicate keyCOMMENTr  r  UNIT)r  r=  r  r  r   r=   rs  r  r   r  r  )
r   rZ  logmsgcountsr  r  rn   rU  r  r~   s
            @r   r  r  P  s    :FFF&&(( GJ GJzz|| 	2A2hnnQRR$$ 	YYYf,,*/sYYY's6;s2VC[2223sq abb	%<<"[[a00NE7mmooGGG $	EE1X__5zzA~~  S*L*L5*L*L!LMMMRyCad w3'>>HH$$C!C!C%!C!CC   !%abb!1!1!""!5!;!;C!C!Cw!--Q//399;;1X__rc!1!1!B$KE E\\EEsEEEEEEKK4D4DEEEEEEEc\\EEc\\EEE\\%LLEEE

     S*K*K%*K*K!KLLL &==HHV&=&=&==>>>s 	J,3F3C()qzS  SG^^-4QRR[->->sA-F-Fq-Is\\\)*Ms   J  3KKc                  t          j        dt           j                  }t          j        d          }i }|                    |                                           D ]\  }}i }|                    |          D ]\  }                                rdk    rdn"d         dk    rd         dk    r
dd         dv r@	 t          fd	                    d          D                       nV# t          $ r Y nJw xY wd
v r!	 t                    n1# t          $ r Y n%w xY w	 t                    n# t          $ r Y nw xY w||<   |||<   |j
        s|                                }	dD ]\}
	 |d         |
dz            \  }}|                    |           |                    d|          |d         |
<   M# t          $ r Y Yw xY w|                    |	           |S )z8Return metatata from Hamamatsu streak image description.z!\[([a-zA-Z0-9 _\-\.]+)\],([^\[]*)z4([a-zA-Z0-9 _\-\.]+)=(\"[^\"]*\"|[\+\-0-9\.]+|[^,]*)r	  Nr   rT  rW   r  c              3     K   | ]<}d v rt          |          n$t          |d         dk    r
|dd         n|          V  =dS )r  r   #rW   N)r  r   r  s     r   r   z.streak_description_metadata.<locals>.<genexpr>P  so       " "   #e|| "!HHH!$adckkQqrrUUq!A!A	" " " " " "r   r  )ScalingXScalingScalingYScalingr,  Filez<f4)r~   r  )recompileDOTALLr  r=  r  r  r   r  r   r  r]  ra  re  r  )r   rq  section_patternproperties_patternr  r  rT  
propertiesrn   rr  scalingrv   r  rU  s                @r   r  r  P  s    j,bi O ?   F*22;3D3D3F3FGG % %
,44V<< 	$ 	$JCKKMME $ESLLqSU2Y#%5%5ade||
! " " " " "'S!1!1" " "  EE "   D!%LLEE!   DJJEE!   D#JsOO$w9 ggii= 	 	G &y 1'F2B C-/]]u .; . .y!'**    
MsI   .C44
D D	D
D&%D&*D::
EE6A	G  
GGTrescalec          	     p   |d}dt          j                  t          t          j        |                    dk    rt	          fd|D                       st          d|           t          fddD                       }t          j        | j        |z             }t          j	        |j
        t          |          fj                  }t          |          D ]\  }}|t          t          j        ||d	z   d                             z	  }	|	t          d
d|z  z   d          z  }	|rbj        dz  |z  d	z   |z  }
|
|j        j        dz  k    r|	                    d          }	|	d|
z  d	z
  d|z  d	z
  z  z  }	|	d|
j        dz  z
  z  z  }	|	|dd|f<   |                    d          S )a  Return array from bytes containing packed samples.

    Use to unpack RGB565 or RGB555 to RGB888 format.
    Works on little-endian platforms only.

    Parameters:
        data:
            Bytes to be decoded.
            Samples in each pixel are stored consecutively.
            Pixels are aligned to 8, 16, or 32 bit boundaries.
        dtype:
            Data type of samples.
            The byte order applies also to the data stream.
        bitspersample:
            Number of bits for each sample in pixel.
        rescale:
            Upscale samples to number of bits in dtype.

    Returns:
        Flattened array of unpacked samples of native dtype.

    Examples:
        >>> data = struct.pack('BBBB', 0x21, 0x08, 0xFF, 0xFF)
        >>> print(unpack_rgb(data, '<B', (5, 6, 5), False))
        [ 1  1  1 31 63 31]
        >>> print(unpack_rgb(data, '<B', (5, 6, 5)))
        [  8   4   8 255 255 255]
        >>> print(unpack_rgb(data, '<B', (5, 5, 5)))
        [ 16   8   8 255 255 255]

    Nr  z<Br  c              3  4   K   | ]}|j         d z  k    V  dS rY  N)r  )r   r  r~   s     r   r   zunpack_rgb.<locals>.<genexpr>GQ  s/      JJq1 22JJJJJJr   zsample size not supported: c              3  \   K   | ]&}t          j        |          j        d z  k    "|V  'dS rs  )r  r~   r  )r   r  r  s     r   r   zunpack_rgb.<locals>.<genexpr>JQ  s=      FFA%+a.."9A"="E"Ea"E"E"E"EFFr   BHIrW   0b1r  rY  r  rT  )r  r~   r   r  rr  r   r  r  r   r  rw   r   r%  r  r  r5   rz  )r   r~   r   rp  r  rr  r  r  r-  r  r	  r  s    `         @r   r  r  Q  s   L !}KEuy''((D

sJJJJMJJJJJ
F}FFGGG	FFFFFFF	F	FB!$"(<==J[*/3}+=+=>
KKFM** 	 	3#eia!egg(>??@@@	Sc	!1%%% 	2.1$,q0C7A:#,q000HHSMM!Q$(3
++A!U^a/011Aqqq!t>>"r   r
  rD  c                   t          j        || d          } t          j        | d| j                  } |rt          j        |           } | S )a  Return palette-colored image.

    The image array values are used to index the colormap on axis 1.
    The returned image array is of shape `image.shape+colormap.shape[0]`
    and dtype `colormap.dtype`.

    Parameters:
        image:
            Array of indices into colormap.
        colormap:
            RGB lookup table aka palette of shape `(3, 2**bitspersample)`.
        contig:
            Return contiguous array.

    Examples:
        >>> import numpy
        >>> im = numpy.arange(256, dtype='uint8')
        >>> colormap = numpy.vstack([im, im, im]).astype('uint16') * 256
        >>> apply_colormap(im, colormap)[-1]
        array([65280, 65280, 65280], dtype=uint16)

    rW   r  r   )r  takerollaxisr  r  )rD  r   r
  s      r   r  r  ZQ  sL    2 JxQ///EN5!UZ00E /'..Lr   )r	  Sequence[str]r	  Mtuple[tuple[str, ...], tuple[int, ...], list[tuple[int, ...]], Sequence[str]]c         	     D   |dnt          |          }||Ot          |          dk    s|d         t          |           k     r#t          dt          |           f d|           dt          |           fd t          t          |                     D             | fS t          j                            ||          }|st          d          t          |t                    rt          j
        |          n"t          |d	          r|nt          d          i dfd}d | D             }t          |          dk    r&t          j                            |d                   }nt          j                            |          }t          |          }	dg }
|D ]} |||	d                   \  }o|jt                    t                    k    s5t!          fdt          t                              D                       rt          dd          n|k    rt          d          t          fdD                       |
                               щJ t          fdD                       t%          j        |
t$          j                  }t%          j        |
d          }|Qt%          j        |d          }||z  }||z  }|dz  }t          d |                                D                       }n\t          |          t          |          k    s't!          d t1          ||          D                       rt          d| d|           |                                }d |D             }
||
| fS )a}  Return shape and axes from sequence of file names matching pattern.

    Parameters:
        files:
            Sequence of file names to parse.
        pattern:
            Regular expression pattern matching axes names and chunk indices
            in file names.
            By default, no pattern matching is performed.
            Axes names can be specified by matching groups preceding the index
            groups in the file name, be provided as group names for the index
            groups, or be omitted.
            The predefined 'axes' pattern matches Olympus OIF and Leica TIFF
            series.
        axesorder:
            Indices of axes in pattern. By default, axes are returned in the
            order they appear in pattern.
        categories:
            Map of index group matches to integer indices.
            `{'axislabel': {'category': index}}`
        _shape:
            Shape of file sequence. The default is
            `maximum - minimum + 1` of the parsed indices for each dimension.

    Returns:
        - Axes names for each dimension.
        - Shape of file series.
        - Index of each file in shape.
        - Filtered sequence of file names.

    Examples:
        >>> parse_filenames(
        ...     ['c1001.ext', 'c2002.ext'], r'([^\d])(\d)(?P<t>\d+)\.ext'
        ... )
        (('c', 't'), (2, 2), [(0, 0), (1, 1)], ['c1001.ext', 'c2002.ext'])

    NrW   r   zshape z does not fit provided shape )r  c                    g | ]}|fS r   r   r  s     r   r:  z#parse_filenames.<locals>.<listcomp>Q  s    ---aaT---r   zinvalid pattern
groupindexr  r   r   'tuple[tuple[str, ...], tuple[int, ...]]c                  	J g }g }d 
j                                         D             }
                    |           }|t          d|           d }t	          |                                          D ]\  }}||dz   |v r||dz            }n|d                                         r|}8|d}	 |	v r	|         |         }t          |          }n%# t          $ r}t          d|          |d }~ww xY w|	                    |           |	                    |           d }t          |          t          |          fS )Nc                    i | ]\  }}||	S r   r   r
  s      r   r  z2parse_filenames.<locals>.parse.<locals>.<dictcomp>Q  s    KKKtq!aKKKr   z!pattern does not match file name rW   r   r  zinvalid index )r  r:  searchr   r  groupsisalphar   r  r   r  )r  r  r  r  matchrv  r  rN  r  rz   pattern_compileds            r   rI	  zparse_filenames.<locals>.parseQ  s   %%%KK'7'B'H'H'J'JKKK
 ''..=JJJKKKellnn-- 	 	DAqy1u
""A&1 zB##"2q)AFF B B B !7!!7!788cABNN1KKOOOBBT{{E'NN**s   6!C
C:"C55C:c                L    g | ]!}t           j                            |          "S r   )r  r  normpathr>  s     r   r:  z#parse_filenames.<locals>.<listcomp>Q  s(    444!!!$$444r   c              3      K   | ]}|vV  	d S r   r   )r   r  ry   s     r   r   z"parse_filenames.<locals>.<genexpr>Q  s(      DDaq	)DDDDDDr   zinvalid axesorder z for z'dims do not match within image sequencec              3  (   K   | ]}|         V  d S r   r   )r   r  r  s     r   r   z"parse_filenames.<locals>.<genexpr>Q  s'      221A222222r   c              3  (   K   | ]}|         V  d S r   r   r  s     r   r   z"parse_filenames.<locals>.<genexpr>R  s'      00T!W000000r   r~  r  c              3  4   K   | ]}t          |          V  d S r   r  r  s     r   r   z"parse_filenames.<locals>.<genexpr>R  s(      ;;c!ff;;;;;;r   c              3  (   K   | ]\  }}||k    V  d S r   r   r5  s      r   r   z"parse_filenames.<locals>.<genexpr>R  s;       / /!QA/ / / / / /r   zparsed shape c                ,    g | ]}t          |          S r   r  )r   r  s     r   r:  z#parse_filenames.<locals>.<listcomp>R  s    666uU||666r   )r  r   r   r  )r  r   r   r  r   rN  rY  r   r   ri  rj  r;  r  r  r  rj	  r@  r   r  r^  intprq  r  r  r  )r   rx   ry   rz   r	  r   rI	  	normpaths
prefix_strr  r  r  lblr  parsedshape
startindexindices_listr  r  r  s     ``             @@@r   rA   rA   zQ  s8   d NDDfE#e**//U1XE

5J5JL#e**LLULL   ZZM--5U,,---	
 	
  $$Wg66G ,*+++'3 ,:g..	,	'	' ,"*+++
+ + + + + + +> 54e444I
9~~W__Yq\22

W''	22
__F#'D%'G  5vww((S<D$I#d))++DDDD5T3C3CDDDDD , !CCC4CC   S[[FGGG 2222	22222Cs0000i00000 Kuz:::M)G!,,,K}Y}1555
#z!q;;k&8&8&:&:;;;;;	[		SZZ	'	'3 / /e[11/ / / , ,	' MKMMeMM
 
 	

 !''))L66666G&&r   Iterator[NDArray[Any]]c             #     K   | E d{V  dS )z=Return iterator over pages in data array of normalized shape.Nr   )r   s    r   rz  rz  R  s      OOOOOOOOOr   pageiterIterator[NDArray[Any] | None]r	  c             #     K   |d         |z   dz
  |z  }| D ]`}|t          j        ||          }n|                    |          }|D ].}|D ])}t          |          D ]}	||	|z  |	dz   |z           V  */adS )z%Return iterator over strips in pages.r  rW   N)r  r|  rz  r  )
r  r   r~   r   r  r  pagedatar.  r`  r  s
             r   r  r  !R  s       r\)A-,>I K K {5%00HH''..H 	K 	KE K Ky)) K KAL 0AE\3I IJJJJJKK	KK Kr   r  c             #    K   dt          |          cxk     rdk     r#n n t          |          t          |          k    rt          d          || j        d         fz   }t          |          }| j        }| j        dd         \  }}}t          |          dk    r|\  }	}
| D ]}|D ]}t          |d                   D ]}||	z  }t          |	||z
            }t          |d                   D ]`}||
z  }t          |
||z
            }|d|||z   |||z   f         }|j        |k    r"t          j	        ||          }||d|d|f<   |}|V  adS |\  }}	}
| D ]}|D ]}t          |d                   D ]}||z  }t          |||z
            }t          |d                   D ]}||	z  }t          |	||z
            }t          |d                   D ]v}||
z  }t          |
||z
            }||||z   |||z   |||z   f         }|j        |k    r%t          j	        ||          }||d|d|d|f<   |}|dk    r|d         n|V  w׌dS )	zqReturn iterator over full tiles in data array of normalized shape.

    Tiles are zero-padded if necessary.

    rW   r  zinvalid tile or tiles shaperT  r  r  r   N)
r   r   r   rD   r~   r  r  rw   r  r|  )r   r   r  r}   r
  r~   szsysxr  r  r  r.  tycytxcxr  chunk_rK  tzczs                         r   rw  rw  9R  s)      s4yy1D		SZZ 7 76777B))J
##IJEAaCJBB
4yyA~~1 	$ 	$D $ $a// $ $B!GBQRB#E!Hoo $ $a BG__ %ab2grBG|&C D :22%*[U%C%CF/4F3B38,$*E#$$$	$ 	$ 1a 	@ 	@D @ @a// @ @B!GBQRB#E!Hoo @ @a BG__"'a// 
@ 
@B!GB!$QRB$) "R"Wb27lBbL H%E  %zY66).Z)G)G8=ssCRC"} 5(../1ff%((%????
@@@@	@ 	@r   r	  	chunkiterrm  Callable[[NDArray[Any]], bytes]istiler  c             #  r   K    dk    rdS t                    j        z  |r
dfd}ndfd}||d	k     s d	k     r1t                     D ]}	t                    }
 ||
          V  ~
 dS |t          j        d	z  }t          ||z            } |k    rTd fd}t          |          5 }|                    | |                      E d{V  ddd           n# 1 swxY w Y   dS t          |          5 }d}g }t                     D ]e}	t                    }
|
|dz  }|	                    |
           ||k    r2|                    ||          E d{V  |
                                 d}f|r|                    ||          E d{V  ddd           dS # 1 swxY w Y   dS )z$Return iterator over encoded chunks.r   Nr  r	  r   r  c                   | dS t          j        |           } | j        k    rAt          d t	          | j                  D                       }t          j        | |          }  |           S )Nr   c              3  *   K   | ]\  }}d ||z
  fV  dS r4  r   r5  s      r   r   z.encode_chunks.<locals>.func.<locals>.<genexpr>R  s.      KK41aQAJKKKKKKr   )r  r  r  r  r  r   r  )r  r  r
  r~   rm  r   s     r   r  zencode_chunks.<locals>.funcR  su    }s+E599E|y(( KK3uek3J3JKKKKK	%--6%== r   c               L    | dS t          j        |           }  |           S )Nr   )r  r  )r  r~   rm  s    r   r  zencode_chunks.<locals>.funcR  s-    }s+E599E6%== r   r  r  c               3  X   K   t                    D ]} t                    }|V  ~d S r   )r  r  )r	  r  r  r	  s     r   r	  zencode_chunks.<locals>.chunksR  sA      9%%  YE	 r   rW   )r  r	  r   r  )r   r  )rD   r  r  r  r   r	  rq  rS   r  r   r	  )r	  r  rm  r   r~   rr   rs   r  r  r	  r  	maxchunksr	  r  r  
chunk_listr
  s   `````           @r   r  r  qR  s      A~~/I !		! 		! 		! 		! 		! 		! 		! 		! 		! 		!	! 	! 	! 	! 	! 	! 	! Z!^^y1}}y!! 	 	AOOE$u++ _q(
J
i 788II	 	 	 	 	 	 	  
++ 	4x||D&&((333333333	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4	J	'	' 68
y!! 		 		AOOE 
e$$$	!!#<<j999999999  """ 	6||D*5555555556 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6s%   :%C++C/2C/BF,,F03F0orientationORIENTATION | int | strc                  t          t          t          t          |                    }|t          j        k    r| S |t          j        k    r| ddddddf         S |t          j        k    r| ddddddddf         S |t          j        k    r| dddddddddf         S |t          j        k    rt          j	        | dd          S |t          j
        k    r$t          j	        | dd          ddddddf         S |t          j        k    r't          j	        | dd          ddddddddf         S |t          j        k    r(t          j	        | dd          dddddddddf         S | S )a  Return reoriented view of image array.

    Parameters:
        image:
            Non-squeezed output of `asarray` functions.
            Axes -3 and -2 must be image length and width respectively.
        orientation:
            Value of Orientation tag.

    .NrT  r  r}  )r\   r%   r7   r  r  r  r  r  r  swapaxesr  r  r  )rD  r  s     r   reorientr  R  s    {GK$E$EFFKk)))k***S$$B$\""k)))S$$B$111_%%k***S$$B$"aaa'((k)))~eR,,,k***~eR,,S$$B$\::k***~eR,,S$$B$111_==k)))~eR,,S$$B$"aaa-?@@Lr   r  rf   repeatsc               |   g }g }g }t          j        |           } t          | j        | j        |          D ]L\  }}}|                    ||f           |                    |df           |                    ||z             Mt           j        j        	                    | ||d          
                    |          S )a  Return read-only view into input array with elements repeated.

    Zoom image array by integer factors using nearest neighbor interpolation
    (box filter).

    Parameters:
        a: Input array.
        repeats: Number of repetitions to apply along each dimension of input.

    Examples:
        >>> repeat_nd([[1, 2], [3, 4]], (2, 2))
        array([[1, 1, 2, 2],
               [1, 1, 2, 2],
               [3, 3, 4, 4],
               [3, 3, 4, 4]])

    r   F)	writeable)r  r   r  stridesr   rQ  r   libstride_tricks
as_stridedrz  )r  r  rz  r   r  r  r6  r   s           r   rE   rE   R  s    $ GEGaAqy!'733  1aaV1vq1u9"--	5'U .  ggr   data_or_shaper  c                   d S r   r   r  r  s     r   rG   rG   S  s	     cr   c                   d S r   r   r  s     r   rG   rG   
S  s    KN3r   tuple[int, ...] | NDArray[Any]c                   t          | t                    r| }n| j        }t          |          |k    r| S d|t          |          z
  z  |z   }t          | t                    r|S |                     |          S )a  Return image array or shape with at least `ndim` dimensions.

    Prepend 1s to image shape as necessary.

    >>> import numpy
    >>> reshape_nd(numpy.empty(0), 1).shape
    (0,)
    >>> reshape_nd(numpy.empty(1), 2).shape
    (1, 1)
    >>> reshape_nd(numpy.empty((2, 3)), 3).shape
    (1, 2, 3)
    >>> reshape_nd(numpy.empty((3, 4, 5)), 3).shape
    (3, 4, 5)
    >>> reshape_nd((2, 3), 3)
    (1, 2, 3)

    r  )r   r  r   r   rz  )r  r  r   s      r   rG   rG   S  s    ( -'' $#
5zzTD3u::%&.E-''   '''r   r  -tuple[tuple[int, ...], str, tuple[bool, ...]]c                   d S r   r   r   r  r  s      r   r  r  .S  s	     58Cr   Sequence[str] | None7tuple[tuple[int, ...], Sequence[str], tuple[bool, ...]]c                   d S r   r   r  s      r   r  r  7S  s
     ?Bcr   r	  str | Sequence[str]=tuple[tuple[int, ...], str | Sequence[str], tuple[bool, ...]]c                  t          |           t          |          k    rt          d          |st          |           |dfS |d}g }g }g }t          | |          D ]d\  }}|dk    s||v r@|                    d           |                    |           |                    |           O|                    d           et          |          dk    r;d|d	<   |                    | d	                    |                    |d	                    t          |t                    rd
                    |          }nt          |          }t          |          |t          |          fS )aW  Return shape and axes with length-1 dimensions removed.

    Remove unused dimensions unless their axes are listed in `skip`.

    Parameters:
        shape:
            Sequence of dimension sizes.
        axes:
            Character codes for dimensions in `shape`.
        skip:
            Character codes for dimensions whose length-1 dimensions are
            not removed. The default is 'XY'.

    Returns:
        shape:
            Sequence of dimension sizes with length-1 dimensions removed.
        axes:
            Character codes for dimensions in output `shape`.
        squeezed:
            Dimensions were kept (True) or removed (False).

    Examples:
        >>> squeeze_axes((5, 1, 2, 1, 1), 'TZYXC')
        ((5, 2, 1), 'TYX', (True, False, True, True, False))
        >>> squeeze_axes((1,), 'Q')
        ((1,), 'Q', (True,))

    z)dimensions of axes and shape do not matchr   N)r  r  r^  r  r_  rW   TFr   rT  r  )r   r   r  r  r   r   r   r   )r   r  r  r  r	  r	  rw   rv  s           r   r  r  @S  sx   D 5zzSYYDEEE &U||T2%%|4H "N!Mt$$ # #b!88rTzzOOD!!!!!$'''  $$$$OOE""""
>aeBi(((T"X&&&$ $ww}%%]##.!!4x99r   asaxesc                   |d}D ]}||vrt          d|           | j        }t          |          D ]}|vr
|z   d|z   }|                     |          } |                     fd|D                       } | S )a  Return image array with its axes permuted to match specified axes.

    Parameters:
        image:
            Image array to permute.
        axes:
            Character codes for dimensions in image array.
        asaxes:
            Character codes for dimensions in output image array.
            The default is 'CTZYX'.

    Returns:
        Transposed image array.
        A length-1 dimension is added for added dimensions.
        A view of the input array is returned if possible.

    Examples:
        >>> import numpy
        >>> transpose_axes(
        ...     numpy.zeros((2, 3, 4, 5)), 'TYXC', asaxes='CTZYX'
        ... ).shape
        (5, 2, 1, 3, 4)

    NCTZYXzunknown axis r  c                :    g | ]}                     |          S r   r	  )r   rv  r  s     r   r:  z"transpose_axes.<locals>.<listcomp>S  s#    ===TZZ^^===r   )r   r   r  rz  	transpose)rD  r  r  rv  r   s    `   r   rI   rI   }S  s    < ~ 3 3V1R11222  KEv ! !T>>9D5LEMM%  EOO====f===>>ELr   unknownr  c                   d S r   r   r  r   r  r  s       r   rF   rF   S  s	     #r   c                   d S r   r   r  s       r   rF   rF   S  s	     Cr   c               F   t          |          }t          |          }t          |           t          |          k    rt          d          t          |          }t          |          }||k    rt          d| d|           | r|s%t	          | t
                    rdnt                      S t          dt          |          t          |          z
            }|r|d|z  z   }t          |          dz
  }d}d}	g }
|ddd	         D ]}||z  }|dk    r/||         dk    r#|dk    r|dz  }|dk    r||         dk    r|dk    |||         k    r;||	||         z  k    r,|	||         z  }	|
                    | |                    |dz  }|r|
                    |           d
}|
                    |           t	          | t
                    r+d                    t          |
|d                             } n$t          t          |
|d                             } | S )am  Return axes matching new shape.

    Parameters:
        axes:
            Character codes for dimensions in `shape`.
        shape:
            Input shape matching `axes`.
        newshape:
            Output shape matching output axes.
            Size must match size of `shape`.
        unknown:
            Character used for new axes in output. The default is 'Q'.

    Returns:
        Character codes for dimensions in `newshape`.

    Examples:
        >>> reshape_axes('YXS', (219, 301, 1), (219, 301))
        'YX'
        >>> reshape_axes('IYX', (12, 219, 301), (3, 4, 219, 1, 301, 1))
        'QQYQXQ'

    rT
  zcannot reshape rY  r  r   r  rW   NrT  r  )
r  r   r   rD   r   r   rq  r   r   r  )r  r   r  r  rw   r  lendiffr  prodnsprodsr  nss               r   rF   rF   S  sF   < %LLEXH
4yyCJJ23335>>DhGw@5@@h@@AAA 8x 8c**7rr7!SZZ#h--/00G -dWn,E

QAFEFtttn # #"!eeaA"''FA !eeaA"''q>>fa(888U1XEMM$q'"""FAA 	#MM'""""GMM'""""$ 1wwxwxx 01122XfWXX.//00Kr   r  c          	     X   t          j        t          j        t          j        | d                    d                                          t          t          t          t                              j	                            }|rt          fd|D                       }|S )a@  Return order of axes sorted by variations in indices.

    Parameters:
        indices:
            Multi-dimensional indices of chunks in array.
        squeeze:
            Remove length-1 dimensions of nonvarying axes.

    Returns:
        Order of axes sorted by variations in indices.
        The axis with the least variations in indices is returned first,
        the axis varying fastest is last.

    Examples:
        First axis varies fastest, second axis is squeezed:
        >>> order_axes([(0, 2, 0), (1, 2, 0), (0, 2, 1), (1, 2, 1)], True)
        (2, 0)

    r   r  r  c              3  4   K   | ]}|         d k    |V  dS r4  r   )r   r  r  s     r   r   zorder_axes.<locals>.<genexpr>"T  s+      77A$q'Q,,a,,,,77r   )
r  r  r
  r  r  r  r|  r  r   rY  )r  rq   r  r  s      @r   r  r  T  s    0 9UYuz':::;;!DDDKKMMD&s4yy))t/?@@@AAE 8777777777Lr   r  series_shapec                f   t          |           }t          |          }|dk    r|dk    rdS |dk    s|dk    rdS ||z  rdS t          t          |                    }d}dx}}t          |           D ]=}||z  }||d         D ]+}|dz  }||z  }||k    s||k    r n|dk    r!||k    r  dS ,>dS )z0Return if page and series shapes are compatible.r   TFrW   N)rD   r  r  )r  r  pipjr  r  r6  s          r   r  r  &T  s	    
		B			B	Qww277t	Qww"''u	Bw u,//00L	AKBj!!  
a abb! 	 	AFA!GBAvvrAvvRxxuuu 4r   r  r  r]  r   r	  c                   d S r   r   r  r	  r]  r   s       r   subresolutionr  FT  	     r   c                   d S r   r   r  s       r   r  r  LT  r  r   TiffPage | TiffPageSeriesc                  | j         |j         k    s| j        |j        k    rdS d}t          | j                                         | j        |j                  D ]\  }}}|dv ro|Bt          |          D ].}||z  }	|	|k    r  dS t          ||	z  |z
            dk     r|} n/ dS N||z  }	|	|k    r dS t          ||	z  |z
            dk    r dS y||k    r dS |S )z7Return level of subresolution of series or page b vs a.Nxyz      ?)r  r~   r  r  r   r  r
  )
r  r	  r]  r   rp   rv  r  r6  r0  r  s
             r   r  r  RT  s,    	v17ag--tE99  Aq;;}q    A1A1uu#tttAEQ;''#-- ! .  44  uHq5544A{##s**44 +!VV44 Lr   r  rl  c                  d}d}|t          |           k     r| |         }d}|dz   }|j        j        r|dz  }4|t          |           k     r| |         }|r|j        j        s|dz  }/|1|D ]'}t	          |j        d         ||          dk    r|} n(|dz  }an't	          |j        d         ||          dk    r|dz  }|j                            |           | |= |t          |           k     |dz  }|t          |           k     dS dS )aN  Pyramidize list of TiffPageSeries in-place.

    TiffPageSeries that are a subresolution of another TiffPageSeries are
    appended to the other's TiffPageSeries levels and removed from the list.
    Levels are to be ordered by size using the same downsampling factor.
    TiffPageSeries of subifds cannot be pyramid top levels.

    )r  r   r  r   NrW   rT  r$  )r   rb  r  r=  r  r   r   )	ro   r  samplingfactorsr  r  r]  r6  r	  r  s	            r   r  r  tT  sZ     O	A
c&kk//1IE: 	FA#f++ooq	A !6 Qy(  A$QXb\1:::a?? @ FA  qx|Q!44499QHOOAq	% #f++oo& 	
Q7 c&kk//////r   )re	  r  rr   r   r"  r	  re	  TiledSequence | Noner  r  c                 t          |           }|dk    rt          d          |dk    r$||d<   | d         J  | d         j        dd|i|S t          d | D                       }|J ||f|j        z   }n|j        }|j        }	|	J t          |||	          }||dk     rh|j        }
t          |t          j
                  }|dk    s|
dk     rdx}}
nY|dk     rd}nP|
d	k    r$|j        dk    r|j        dk    r|j        dk    rd}n&d}
n#|dk    rdx}}
n||k    s|j        d	k     rd}
n|}
d}|
|d<   |j        j        }2|j        }|s|dk    s|
dk    r|                    d
           |j        nd
}t'          t)          d|                    }||||fdfd}|d	k     r"t+          |           D ]\  }} |||           n|j         t/          |          5 }|                    || t3          |                    D ]}	 ddd           n# 1 swxY w Y   n|||fdfd}|d	k     r5t5          |                                |           D ]\  }} |||           n[|j         t/          |          5 }|                    || |                                          D ]}	 ddd           n# 1 swxY w Y   |                                 |s|                    d           |S )ae  Return vertically stacked image arrays from sequence of TIFF pages.

    Parameters:
        pages:
            TIFF pages or frames to stack.
        tiled:
            Organize pages in non-overlapping grid.
        lock:
            Reentrant lock to synchronize seeks and reads from file.
        maxworkers:
            Maximum number of threads to concurrently decode pages or segments.
            By default, use up to :py:attr:`_TIFF.MAXWORKERS` threads.
        out:
            Specifies how image array is returned.
            By default, a new NumPy array is created.
            If a *numpy.ndarray*, a writable array to which the images
            are copied.
            If a string or open file, the file used to create a memory-mapped
            array.
        **kwargs:
            Additional arguments passed to :py:meth:`TiffPage.asarray`.

    r   zno pagesrW   rr   Nr   c              3  (   K   | ]}||j         V  d S r   r  r\  s     r   r   zstack_pages.<locals>.<genexpr>T  s$      <<ammmmm<<r   r   r  Tr  )rw   r  r  rA  r  r   rb   	filecacher-   r   r  r   r  c                   | V|                     | j        j                    | j        d||         d| |                    | j        j                   d S d S )N)r  r   r   r  rO  r  r   r  r  r  r   r  r   r  s        r   r  zstack_pages.<locals>.funcT  sj     t{5666A$CJAA&AAA 677777  r   r^	  c                   | R|                     | j        j                    | j        ddi|||<   |                    | j        j                   d S d S )Nr  r   r  r  s        r   
func_tiledzstack_pages.<locals>.func_tiledU  sg     t{5666)T\>>t>v>>E
 677777  r   Fr   )r  rA  r  r   r   rb   r  r-   r   r  r   r  )r  rA  r  r^	  r   rb   r  r-   r   r  r   r  )r   r   r   r  r   r~   r6   rr   r  r   r  r   r  r   rO  r  r	  r	  r  r-   rq  r  r  rS   r  r  r  r  r	  )r"  re	  r  rr   r   r   r  ri  r   r~   page_maxworkersrq  haslockr  r  r  r  r  r	  r  index_tileds     `                  r   rf  rf  T  sn   B ZZF{{$$${{)|Qx###uQx22C26222<<U<<<<<E}	EK'KE
UE
*
*C Z!^^*11
??o11+,,JaZZJJq  !Q&&1$$1$$JJOO	q'((
__	*		 01 4 4$
*F<		 B|+ 	:>>_q-@-@KKws1j11===I}
 #,%+	8 	8 	8 	8 	8 	8 	8 >>(// " "tT5!!!!" LL#J// 8!dE5==AA  A               #,%+	8 	8 	8 	8 	8 	8 	8 >>%(%?%? . .!T
4----. LL#J// 8!j%HH  A               OO 
EJs$   !(HHH=-J77J;>J;zw+)rt   suffixr   rg   Literal['r+', 'w+', 'r', 'c']r  %NDArray[Any] | numpy.memmap[Any, Any]c              R   t          |          }| L|t          j        ||          S |rt          j        ||          } || dd<   | S t          j        ||          S t	          | t          j                  rrt          |          t          | j                  k    rt          d          t          j	        || j
                  st          d          |                     |          S t	          | t                    r| dd         dk    ryddl}t          |           dk    r
| dd         nd}|d}|                    ||	          5 }t          j        ||||
          } |r|| dd<   | cddd           S # 1 swxY w Y   t          j        | |||
          } |r|| dd<   | S )a  Return NumPy array where images of shape and dtype can be copied.

    Parameters:
        out:
            Specifies kind of array to return:

                `None`:
                    A new array of shape and dtype is created and returned.
                `numpy.ndarray`:
                    An existing, writable array compatible with `dtype` and
                    `shape`. A view of the array is returned.
                `'memmap'` or `'memmap:tempdir'`:
                    A memory-map to an array stored in a temporary binary file
                    on disk is created and returned.
                `str` or open file:
                    File name or file object used to create a memory-map
                    to an array stored in a binary file on disk.
                    The memory-mapped array is returned.
        shape:
            Shape of NumPy array to return.
        dtype:
            Data type of NumPy array to return.
        suffix:
            Suffix of `NamedTemporaryFile` if `out` is 'memmap'.
            The default suffix is 'memmap'.
        fillvalue:
            Value to initialize newly created arrays.
            If *None*, return an uninitialized array.

    Nzincompatible output shapezincompatible output dtyper  r   r   r  z.memmap)rG  r  )r   r~   rt   )r  r  r  r|  r   r<  rD   r   r   r)  r~   rz  r   tempfiler   NamedTemporaryFiler   )	r   r   r~   rt   r  r   r  tempdirrq  s	            r   r6   r6   2U  s	   P %LLE
{;ue,,, 	+eU++CCFJ{5%(((#u}%% "5>>WSY////8999~eSY// 	:8999{{5!!!#s 
BQB8 3 3 XX\\#abb''t>F((WV(DD 	,re$GGGC #"AAA		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	
 ,s%u4
@
@
@C AAAJs   #E;;E?E?	matlabstrc                  dfdddddddfd}d| v sd| v ri }|                                  D ]|}|                                }|r|d         dk    r%|                    dd          \  }                                t          fddD                       rn ||          |<   }|S  ||           S )a/  Return Python object from Matlab string representation.

    Use to access ScanImage metadata.

    Parameters:
        matlabstr: String representation of Matlab objects.

    Returns:
        Matlab structures are returned as `dict`.
        Matlab arrays or cells are returned as `lists`.
        Other Matlab objects are returned as `str`, `bool`, `int`, or `float`.

    Examples:
        >>> matlabstr2py('1')
        1
        >>> matlabstr2py("['x y z' true false; 1 2.0 -3e4; NaN Inf @class]")
        [['x y z', True, False], [1, 2.0, -30000.0], [nan, inf, '@class']]
        >>> d = matlabstr2py(
        ...     "SI.hChannels.channelType = {'stripe' 'stripe'}\n"
        ...     "SI.hChannels.channelsActive = 2"
        ... )
        >>> d['SI.hChannels.channelType']
        ['stripe', 'stripe']

    r  r   r   r  c               D   dg}	  |           \  }}|nt|dk    r|                     d           nM|dk    r|                     d           n1|dk    r|                     d           n|                    |           | |d          } |                    d           |S )Nr  TrG  )r  r  )r  r  r  )r  r  )rQ  r   )r  tokensr  r  
next_tokens       r   lexzmatlabstr2py.<locals>.lexU  s    	:a==DAqyCxxj))))cj))))cj))))a   !""A	 	cr   tuple[str | None, int]c               ^   t          |           }|dk    rdS d}||k     r#| |         dk    r|dz  }||k     r| |         dk    ||k    rd |fS | |         dv r| |         |dz   fS | |         dk    r@|dz   }||k     r#| |         dk    r|dz  }||k     r| |         dk    | ||dz            |dz   fS | |         dk    r@|dz   }||k     r#| |         dk    r|dz  }||k     r| |         dk    | ||dz            |dz   fS |}||k     r| |         d	vr|dz  }||k     r
| |         d	v| ||         |fS )
Nr   r  r!  rW   z{[;]}r   rk   rj   z {[;]}r:  )r  r_  r  r6  s       r   r  z matlabstr2py.<locals>.next_tokenU  s   QQ;;7&jjQqTS[[FA &jjQqTS[[;;7NQ47??Q4Q;Q43;;AAf**1Q f**1QQY<Q&&Q43;;AAf**1Q f**1QQY<Q&&&jjQqT11FA &jjQqT111vqyr   Ffailr   rb   c               b                                        s S t                     dk    r3	 t                     S # t          $ r}|rt          | cY d }~S d }~ww xY w d         dk    r+|r d         dk    sd dd         v rt           dd         S  d         dk    r#|r d         dk    sd dd         v rt           S |r"t           fddD                       rt           d         d	k    r S  d
v rdS  dv rdS  d d         dk    rKt          j        d  dd                             d          D                       	                                S  d d         dk    rKt          j
        d  dd                             d          D                       	                                S d v sd v r 	 t                     S # t          $ r Y nw xY w	 t                     S # t          $ r Y nw xY w	 t                     S # t          $ r}|rt          |Y d }~nd }~ww xY w S )NrW   r   r   rT  rk   rj   c              3      K   | ]}|v V  	d S r   r   )r   r  r  s     r   r   z.matlabstr2py.<locals>.value.<locals>.<genexpr>U  s'      221Q222222r   z ';[]{}rC	  >   Truer
  T>   Falser
  Fr  zzeros(c                ,    g | ]}t          |          S r   r  r  s     r   r:  z/matlabstr2py.<locals>.value.<locals>.<listcomp>U  s    CCC1ACCCr   r  r  zones(c                ,    g | ]}t          |          S r   r  r  s     r   r:  z/matlabstr2py.<locals>.value.<locals>.<listcomp>U  s    BBB!s1vvBBBr   r  r
  )r=  r   r   r  r   r@  r  r|  r  r  onesr  )r  r  r  s   `  r   rU  zmatlabstr2py.<locals>.valueU  s   GGII 	Hq66Q;;1vv    .$#- Q43;; !"q2w  QrT7NQ43;; !"q2w  H 	C2222	22222 	Q43;;H   4"""5RaR5H;CC!B$c0B0BCCCDDKKMMMRaR5G:BBq2w}}S/A/ABBBCCJJLLL!88saxxQxx   	q66M 	 	 	D		*88O 	* 	* 	* * c)* * * * *	* sW   = 
AAAA?G 
GGG. .
G;:G;?H 
H,
H''H,c                  |                                  } 	  | d          S # t          $ r Y nw xY wg x}}|g} |           D ]}|dv rg }|                    |           |dv r|                                }|d         }t	          |          dk    r>t          |d         t          t          f          r|                    |d                    |                    |           |                     |                     t	          |          dk    r*t          |d         t          t          f          r|d         S |S )NTz[{z]}rT  rW   r   )r=  r   r   r  r   r   rA  r   )r  r  addtor   r  r  r  rU  s         r   rI	  zmatlabstr2py.<locals>.parseU  sT   GGII	5D>>! 	 	 	D	 Q 	' 	'ADyye$$$$dJJLLr
q66Q;;:adT3K#@#@;LL1&&&&LLOOOOUU1XX&&&&v;;!
6!9tSk B B!9s   # 
00rA  r   %rQ  rW   c              3      K   | ]}|v V  	d S r   r   )r   r  r   s     r   r   zmatlabstr2py.<locals>.<genexpr>V  s'      //a16//////r   z	 ';[]{}<>)r  r   r   r  )r  r   r   r  r$  )r  r   r  r   r   rb   )r  r   r   rb   )r  r=  r  r@  )	r  rI	  r  r  r  r   r  r  rU  s	        @@@@r   r>   r>   zU  sD   :     &   6. . . . .`      8 yDI--((** 	 	D::<<D 47c>>::c1%%DAq		A////;///// 588AaDD5r   datetime_stringrL  rn  c                   ddddddddd	d
dddddd}|d||<   t          |                                d           D ],\  }}	 t          j        | |          c S # t          $ r Y )w xY wt	          d| d          )a   Return datetime corresponding to date string using common formats.

    Parameters:
        datetime_string:
            String representation of date and time.
        format:
            Format of `datetime_string`.
            By default, several datetime formats commonly found in TIFF files
            are parsed.

    Raises:
        ValueError: `datetime_string` does not match any format.

    Examples:
        >>> strptime('2022:08:01 22:23:24')
        datetime.datetime(2022, 8, 1, 22, 23, 24)

    rW   r  r   r  r  r  r  rY  r<  r  rY  r  r  r  r  )r  r5  r"  z%Y-%m-%dT%H:%M:%S.%fz%Y-%m-%dT%H:%M:%Sz%Y:%m:%d %H:%M:%S.%fz%d/%m/%Y %H:%M:%Sz%d/%m/%Y %H:%M:%S.%fz%m/%d/%Y %I:%M:%S %pz%m/%d/%Y %I:%M:%S.%f %pz%Y%m%d %H:%M:%Sz%Y/%m/%d %H:%M:%Sz%Y/%m/%d %H:%M:%S.%fz%Y-%m-%dT%H:%M:%S%zz%Y-%m-%dT%H:%M:%S.%f%zNr   c                    | d         S r  r   )r(  s    r   r  zstrptime.<locals>.<lambda>GV  s
    d1g r   r  z
time data z does not match any format)r|  r:  rn  rH   r   )r  rL  formatsr	  s       r   rH   rH   !V  s    (  ! ! ! ! !#% "!"$ G" GMMOO1E1EFFF  		$_f===== 	 	 	D	
B_BBB  s   A
A('A()r  nullr9  r  c                  d S r   r   r9  r  r  s      r   rN   rN   QV  s	     Cr   c                  d S r   r   r  s      r   rN   rN   WV  s	     #r   str | bytesc                  |t          | t                    rd}nd}|r'|                     |          }|dk     r| n	| d|         S |                     |          S )a  Return string truncated at first null character.

    Use to clean NULL terminated C strings.

    >>> stripnull(b'bytes\x00\x00')
    b'bytes'
    >>> stripnull(b'bytes\x00bytes\x00\x00', first=False)
    b'bytes\x00bytes'
    >>> stripnull('string\x00')
    'string'

    Nr1  r  r   )r   r  r  r  )r9  r  r  r  s       r   rN   rN   ]V  sl    2 |fe$$ 	DDD /KKQvvF2A2J.==r   c               ~    t          |           }|r|dz  }d| |         cxk     rdk     rn nn|d}| d|dz            S )zReturn string truncated at last byte that is 7-bit ASCII.

    Use to clean NULL separated and terminated TIFF strings.

    >>> stripascii(b'string\x00string\n\x01\x00')
    b'string\x00string\n'
    >>> stripascii(b'\x00')
    b''

    rW   rY     rT  Nr:  )r9  r  s     r   
stripasciir   V  sl     	FA
 	Qvay3  
 'AE'?r   r
  r
  rU  c                   d S r   r   rU  r
  r
  s      r   r3  r3  V  	     3r   Sequence[bytes] | Nonec                   d S r   r   r"  s      r   r3  r3  V  r#  r   Sequence[str | bytes] | Nonebool | bytesc               $   |                                                                  } d}|)t          | t                    r| dk    rdS d}n| dk    rdS n| |v rdS |)|st          | t                    r	| dk    rdS n| dk    rdS n| |v rdS t          )zReturn string as bool if possible, else raise TypeError.

    >>> asbool(b' False ')
    False
    >>> asbool('ON', ['on'], ['off'])
    True

    FNs   trueTr
  s   falser
  )r=  r  r   r  r   )rU  r
  r
  isbytess       r   r3  r3  V  s     KKMM!!EG|eU## 	tGGf__4 	$t} 	j.. 	  u !g5 	%u
Or   r:  Sequence[Any] | Nonec                   |t           t          t          t          f}|D ]2}	  ||           c S # t          t
          t          t          f$ r Y /w xY w| S )zReturn argument as one of types if possible.

    >>> astype('42')
    42
    >>> astype('3.14')
    3.14
    >>> astype('True')
    True
    >>> astype(b'Neee-Wom')
    'Neee-Wom'

    )r   r  r3  r  r   r?  r   r  )rU  r:  typs      r   r5   r5   V  sn     }UFI-  	3u::NI7IJ 	 	 	D	Ls   
/AAr0  float | tuple[int, int]r4  c               P   ddl m} t          | t                    r || d         | d                   }n|                    |           }|                                \  }}|dk    s|dk    r7dt          ||          z  }t          ||z            }t          ||z            }||fS )zEReturn rational numerator and denominator from float or two integers.r   r  rW   r  )r  r  r   rR   
from_floatas_integer_ratiorq  r  )r0  r  r  	numeratordenominatorr  s         r   ru  ru  V  s    """"""#x   %HSVSV$$$$//11I{:z!9!9Y444)a-((	K!O,,k!!r   stringsrm	  c             #     K   t                      }t          |           D ]4\  }}||v r|t          |          z  }|                    |           |V  5dS )ztReturn iterator over unique strings.

    >>> list(unique_strings(iter(('a', 'b', 'a'))))
    ['a', 'b', 'a2']

    N)r	  r  r   r  )r3  knownr  r9  s       r   r,	  r,	  V  sl       EEEw''  	6U??c!ffF		&	 r      	thresholdr  c               P    | |k     r|  dS dD ]}| dz  } | |k     r
| dd| c S dS )zReturn file size as string from byte size.

    >>> format_size(1234)
    '1234 B'
    >>> format_size(12345678901)
    '11.50 GiB'

    z B)KiBMiBGiBTiBPiBg      @z.2fr!  	ginormousr   )rw   r7  r  s      r   r9   r9   W  se     i{{{3 ( ()'''''''' ;r   r;  c                   | S )zOSingle argument identity function.

    >>> identityfunc('arg')
    'arg'

    r   )r0  r;  r   s      r   r
  r
  W  s	     Jr   c                     dS )z<Null function.

    >>> nullfunc('arg', kwarg='kwarg')

    Nr   r?  s     r   r@   r@    W  s	     Fr   Sequence[Any]c               D    t          | t          t          f          r| n| fS )zReturn tuple containing value if value is not tuple or list.

    >>> sequence(1)
    (1,)
    >>> sequence([1])
    [1]
    >>> sequence('ab')
    ('ab',)

    )r   r  rA  rI  s    r   rS  rS  )W  s#     uudm44B555(Br   iterableIterable[int]c               8    d}| D ]}|t          |          z  }|S )zReturn product of integers.

    Equivalent of ``math.prod(iterable)``, but multiplying NumPy integers
    does not overflow.

    >>> product([2**8, 2**30])
    274877906944
    >>> product([])
    1

    rW   r  )rC  prodr  s      r   rD   rD   7W  s.     D  AKr   iteratorIterator[Any]tuple[Any, Iterator[Any]]c               F    t          |           }|| fdd}| |            fS )zReturn first item of iterator and iterator.

    >>> first, it = peek_iterator(iter((0, 1, 2)))
    >>> first
    0
    >>> list(it)
    [0, 1, 2]

    r  rb   rG  rH  r   c              3  "   K   | V  |E d {V  d S r   r   )r  rG  s     r   newiterzpeek_iterator.<locals>.newiterUW  s/       r   )r  rb   rG  rH  r   rH  r  )rG  r  rL  s      r   r}  r}  IW  sB     NNE h     ''))r   Iterable[str]r  c               Z    dfd}t          j        d          t          | |          S )	zReturn human-sorted list of strings.

    Use to sort file names.

    >>> natural_sorted(['f1', 'f2', 'f10'])
    ['f1', 'f2', 'f10']

    r  r   r   list[int | str]c               B    d t          j        |           D             S )Nc                X    g | ]'}|                                 rt          |          n|(S r   )isdigitr   )r   r  s     r   r:  z3natural_sorted.<locals>.sortkey.<locals>.<listcomp>iW  s/    MMM1199;;-QAMMMr   )ri  r  )r  numberss    r   sortkeyznatural_sorted.<locals>.sortkeyhW  s#    MM!8L8LMMMMr   z(\d+)r  )r  r   r   rP  )ri  rj  r|  )rC  rU  rT  s     @r   r?   r?   ^W  sK    N N N N N N j""G(((((r   secnsecc               <    t          j        | dz   |dz  z             S )zReturn datetime object from epicsTSSec and epicsTSNsec tag values.

    >>> epics_datetime(802117916, 103746502)
    datetime.datetime(2015, 6, 2, 11, 31, 56, 103746)

    i%r  )rn  fromtimestamp)rV  rW  s     r   epics_datetimerZ  oW  s"     !#	/D3J">???r   	timestampr  epochc               R    |d}t          j        |          t          |           z   S )zReturn datetime object from timestamp in Excel serial format.

    Use to convert LSM time stamps.

    >>> excel_datetime(40237.029999999795)
    datetime.datetime(2010, 2, 28, 0, 43, 11, 999982)

    NiZ
 )rn  fromordinalr8
  )r[  r\  s     r   excel_datetimer_  yW  s,     }&&9)=)===r   	juliandaymillisecondc          
     Z   | dk    rt          d| d          | dz   }|dk    r(t          j        |dz
  dz            }|d|z   |dz  z
  z  }||dk    rd	nd
z   }t          j        |dz
  dz            }t          j        d|z            }t          j        ||z
  dz            }||z
  t          j        d|z            z
  }||dk     rdndz
  }	||	dk    rdndz
  }
t          |d          \  }}t          |d          \  }}t          |d          \  }}t	          |
|	|||||dz            S )zReturn datetime from days since 1/1/4713 BC and ms since midnight.

    Convert Julian dates according to MetaMorph.

    >>> julian_datetime(2451576, 54362783)
    datetime.datetime(2000, 2, 2, 15, 6, 2, 783000)

    iOD z%no datetime before year 1 (julianday=r  rW   i# g   @}<Ag    @r  i  i  gfffff^@g     v@gaTR'>@g      +@r  g      @il  ik  i6 i`  r  )r   rx  truncr  rn  )r`  ra  r  r  r	  r  r  r
  r  r  r  r  r  seconds                 r   r  r  W  sf    GDyDDDEEEAA7{{
A
Nh677	QY!##	Q[[TTd+A
AI'((A
6A:A
AEW$%%A
a%$*Wq[))
)Ca$hhB'E.D{N;;D+ i88FK d33FKD%dFFK$<NOOOr   c                   | dt           j        hv rdS ddd}|                    | |           |t           j                 k    S )z_Return if byteorder matches system's byteorder.

    >>> byteorder_isnative('=')
    True

    rQ  Trj   rk   r  rS  )rd  r   rY  )r   r  s     r   rJ  rJ  W  sH     S#-(((t#&&D88Iy))T#--@@@r   rh  c                   | |dhv s|dk    rdS | dk    rdddt           j                 } n|dk    rdddt           j                 }| |k    S )z}Return if byteorders match.

    >>> byteorder_compare('<', '<')
    True
    >>> byteorder_compare('>', '<')
    False

    rR  TrQ  rj   rk   rf  )rd  r   )r   rh  s     r   byteorder_comparerh  W  si     UCL  ESLLtC3//>			#s++CM:r   recarrayr	  c               @   i }| j         j        D ]}|dd         \  }}| |         }|j        dk    r0|                                }|d         dk    rt	          |          }n7|j        dk    r,|                                }|d         dk    rd |D             }|||<   |S )aD  Return numpy.recarray as dictionary.

    >>> r = numpy.array(
    ...     [(1.0, 2, 'a'), (3.0, 4, 'bc')],
    ...     dtype=[('x', '<f4'), ('y', '<i4'), ('s', 'S2')],
    ... )
    >>> recarray2dict(r)
    {'x': [1.0, 3.0], 'y': [2, 4], 's': ['a', 'bc']}
    >>> recarray2dict(r[1])
    {'x': 3.0, 'y': 4, 's': 'bc'}

    Nr  r   rW   r  c                ,    g | ]}t          |          S r   )r  r  s     r   r:  z!recarray2dict.<locals>.<listcomp>W  s    555!1555r   )r~   descrr  r  r  )ri  r  rl  ru   r~   rU  s         r   r  r  W  s     F%  BQBie:??LLNNEQx3!%((Z1__LLNNEQx355u555tMr   r  )sanitizer  rZ  r
  rm  r  tuple[str, str] | Nonec                  	 ddl m} n# t          $ r	 ddlm} Y nw xY w|r|nd\  dfddfd
 |                    |                     S )a  Return XML as dictionary.

    Parameters:
        xml: XML data to convert.
        sanitize: Remove prefix from from etree Element.
        prefix: Prefixes for dictionary keys.
        sep: Sequence separator.

    Examples:
        >>> xml2dict(
        ...     '<?xml version="1.0" ?><root attr="name"><key>1</key></root>'
        ... )
        {'root': {'key': 1, 'attr': 'name'}}
        >>> xml2dict('<level1><level2>3.5322,-3.14</level2></level1>')
        {'level1': {'level2': (3.5322, -3.14)}}

    r   r  )r  r  rU  rb   r   c               |   t          | t                    s| S rf| v rbg }|                               D ];} |          }t          |t                    r| c S |                    |           <t	          |          S t
          t          t          fD ]&}	  ||           c S # t          t          f$ r Y #w xY w| S r   )
r   r   r  r   r  r   r  r3  r   r   )rU  rT  r  r  r  r5   rZ  s        r   r5   zxml2dict.<locals>.astypeX  s    %%% 	L 	!3%<<F{{3'' ! !F3KKa%% ! LLLa    == uf% 	 	Aqxxz*   s   
B%%B98B9r  r  c                  | j         }r|                    dd          d         }|| j        ri nd i}t          |           }|rt	          j        t                    }t          |          D ]@}|                                D ])\  }}||                              	|                     *A|	fd|                                D             i}| j        r?||         	                    	
fd| j                                        D                        | j
        rJ| j
                                        }|s| j        r|r 	|          ||         dz   <   n 	|          ||<   |S )Nr  rW   rT  c                v    i | ]5\  }}|t          |          d k    r |d                   n
 |          6S )rW   r   r:  )r   r   r  r5   s      r   r  z0xml2dict.<locals>.etree2dict.<locals>.<dictcomp>'X  sU       1 s1vv{{vvad|||q		  r   c              3  >   K   | ]\  }}|z    |          fV  d S r   r   )r   r   r  r5   ats      r   r   z/xml2dict.<locals>.etree2dict.<locals>.<genexpr>-X  s8      KK$!Q2666!99-KKKKKKr   rU  )r9  rsplitr*  rA  collectionsdefaultdictr  r:  r   r  r
  r=  )r  rn   r  childrendddcr   r  r
  r5   rt  
etree2dictrm  r  s            r   r{  zxml2dict.<locals>.etree2dictX  s   e 	)**S!$$R(C ":""d;77 
	(..B*h// , ,HHJJ , ,DAqqELL++++,      "

  A 8 	LcFMMKKKKK!(..:J:JKKKKKK6 	&6<<>>D &18 & 8+16$<<AcF2<(#r   )rU  rb   r   rb   )r  rb   r   r  )
defusedxmlr  r
  r  r  )	r
  rm  r  rZ  r  r5   rt  r{  r  s	    ` ` @@@@r   rL   rL   W  s    233333333 3 3 3222222223 +VV8FB      (         : :e&&s++,,,s    ""K   rG  g      ?)r^  r  snipatrd  ellipsisr^  r  r~  rd  r  c                 t          |           }|dk     s|dk     s|dk     rdS |dk    r6d}t          ||t          |          z
  dz  |z  z  |          }|dk     rdS d}	nldt          d|z            z  }t          ||t          |dz            z
  dz  |z  z  |          }|dk     rdS d|z  t          |dz            z   }|dz
  |z  dz   }	||dk    r|}nAd
t          |          cxk     rdk     r'n n$t          t	          j        ||z                      }|d
k     r||z  }t          |t                    sJ |dk    s|	dk    rd
| d	|         fg}
d}d}d|z  }n|r|	|k    rd
| fg}
n|d
k    r||	|z
  z  }|| |d	         fg}
ni||k    s|dk     r||z  }d
| d	|         fg}
nJ||z  }|||z
  dz
  z  }||z  r	|||z  z  }n||z  }d
| d	|         f||z
  |z
  d	f||z
  | ||z
  d	         fg}
|2|r-|dk    r'dt          |dz            |dz  dz  z   dz
  z  }|dz  }nd}n|                    d          }g }|
D ]\  }}||                    |           t          j
        |          }t          j        dd|          }t          d
t          |          |          D ]}|d|z  d|z  |dz  z            |dk    r|||z   z  n|}|d                    fdt          d
d|z  d          D                       z  }|d|t          |          z
  z  z  }|||||z            z  }|                    |           d                    |                              d          S )a  Return hexdump representation of bytes.

    Parameters:
        data:
            Bytes to represent as hexdump.
        width:
            Maximum width of hexdump.
        height:
            Maximum number of lines of hexdump.
        snipat:
            Approximate position at which to split long hexdump.
        modulo:
            Number of bytes represented in line of hexdump are modulus
            of this value.
        ellipsis:
            Characters to insert for snipped content of long hexdump.
            The default is '...'.

    Examples:
        >>> import binascii
        >>> hexdump(binascii.unhexlify('49492a00080000000e00fe0004000100'))
        '49 49 2a 00 08 00 00 00 0e 00 fe 00 04 00 01 00 II*.............'

    rW   r  r  r   r  s   %%0%ix: s   %xr   Nr          ...r  s   [^\x20-\x7f]   .c              3  2   K   | ]}||d z            V  dS rr
  r   )r   r  r&  s     r   r   zhexdump.<locals>.<genexpr>X  s/      OOA1QQY<OOOOOOr      
r  )r   r  r
  r   rx  r'  r   rm  r   binasciihexlifyri  subr  r   r  )r   r^  r  r~  rd  r  rw   addrbytesperlinenlinesrs  r  r%
  end1end2elpsr  bstrhexstrstrstrr  r0  r&  s                         @r   r:   r:   :X  s   D t99Daxx5199

r{{D		)a/F:;T
 
 !2S...D1H-!3>?
 
 !2L 3tax==0(|+a/~1	
S[[				1					TZ0011zz&fc""""" {{fkkd=L=)*+L  
v''d)	10$uvv,'(	6		VaZZV#d4C4j/"f$v23, 	!D<''DDL DUdUD[4&D[$td{}}-.
  	L1$$3tax==<1+<q+@@1DEDFNDDDDx((F  t<MM$!$''($55q#d))\22 	 	Aq1uq1u|a'7778A(.

U##AOOOOq!l:JA1N1NOOOOOOAQ((AA,,--AMM!	 ::f$$W---r   c                   |                                  } | sdS 	 |                                 S # t          $ r Y nw xY w	 |                                                                 S # t          $ r Y nw xY wdS )zReturn if all characters in string are printable.

    >>> isprintable('abc')
    True
    >>> isprintable(b'\01')
    False

    TF)r=  isprintabler  r  )r9  s    r   r  r  X  s     \\^^F t!!###   }}**,,,   5s   . 
;;%A% %
A21A2compactc                  |                      dd                               dd                               dd                               dd                               dd                               dd                               dd          } |rf|                      dd                               d	d
                               dd                               dd                               dd          } |                                 S )zfReturn string with compressed whitespace.

    >>> clean_whitespace('  a  \n\n  b ')
    'a\n b'

    r-  rA  r  rI  	r!  r?  z 
z[ r  )r  r=  )r9  r  s     r   clean_whitespacer  X  s     	vt$$	t						s			s			s					   
NN4%%WT3WT3WT3WT3 	 <<>>r   c                     d                     d | D                       }d                     d |                                D                       dd         S )zReturn joined string representations of objects with indented lines.

    >>> print(indent('Title:', 'Text'))
    Title:
      Text

    rA  c              3  4   K   | ]}t          |          V  d S r   rC  )r   r0  s     r   r   zindent.<locals>.<genexpr>X  s(      ..#SXX......r   c              3  ,   K   | ]}||rd |z   n|V  dS )r?  Nr   )r   r  s     r   r   zindent.<locals>.<genexpr>X  sH        ,0	&$     r   r  N)r   r  )r;  r
  s     r   r  r  X  sl     99.......D99  48OO4E4E    bb
 
r   c               ,   	 ddl m} t          | t                    s|                                 } |                    t          j        |                     }|                    |dd|j	        j
                  } t          | t                    sJ t          |           } nJ# t          $ r= t          | t                    rt          |           } |                     dd          } Y nw xY w|                     dd                              d	d          S )
zReturn pretty formatted XML.r   r
  T)r
  r
  r	  z><z>
<r?  r!  r  )r
  r  r   r  rm  rI	  r  r  r  docinfor	  r  r  r  )r
  r  r  s      r   pformat_xmlr  X  s   (#u%% 	**,,C{{2:c??++nn \*	  
 
 #u%%%%%nn ( ( (c5!! 	!C..Ckk$''( ;;tS!!))$444s   BB" "AC)(C)r7  r  )r  r^  	linewidthr  r  c              t   ||dk     rd}||dk     rd}dk     r|t          j                    }t          j        d|           t          | t                    r=| dd                                         dk    s| d	d         d
k    rt          |           } t          | t                    rgt          |           rt          |           } t          |           } n$t          j        di | t          | ||d          S | 
                                } nt          | t                    re| dd                                         dk    s| d	d         dk    r"|dk    r| dd|z           nt          |           } | 
                                } nKt          | t           j                  r|                                 } nddl}|                    | ||          } t          j        di | |dk    r(| d||z           } t          | d          } | d         S t!          |                                           }t%          |          |k    r@d                    fd|d|dz           dgz   || dz  d         z   D                       } n)d                    fd|d|         D                       } | S )z{Return pretty formatted representation of object as string.

    Whitespace might be altered. Long lines are cut off.

    NrW   r  r  r  )r7  r  r  r
  r  s   OME>)r^  r  rd  r
  r2  r  r   )r^  r  T)r  rA  c              3  ,   K   | ]}|d          V  d S r   r   r   r  r  s     r   r   zpformat.<locals>.<genexpr>DY  s@       
 
 )
 
 
 
 
 
r   r  z...c              3  ,   K   | ]}|d          V  d S r   r   r  s     r   r   zpformat.<locals>.<genexpr>IY  s,      CCTZiZ(CCCCCCr   r   )r  get_printoptionsset_printoptionsr   r  r  r  r  r  r:   r  r   r  r	  pprintrC   rA  r  r   r   )r0  r  r^  r  r  npoptr  argls      `    r   rC   rC   Y  s    ~!}		IMM	"$$E	SE::::#u !rr7==??h&&#bcc(g*=*=C..C#u @s 	FC..C"3''CC"++U+++3eF1EEEEjjll	C		 @rr7==??g%%RSSV););&,kk#kE	k""{37G7GC jjll	C	&	& @jjllnnSwn??	##U###{{/EEM/"sD111:I:  !!D
4yy6ii 
 
 
 
]v{]+ug5fW\^^8LL
 
 
 
 

 iiCCCCT'6']CCCCCJr   )r~  r  c              p   |d}|t          | t                    rd}nd}t          |          }|                                 }g }|D ]}||                    |           t          |          }||k    r|                    |            F||dk    r|}	nQdt          |          cxk     rdk     r(n n%t          t          j        ||z                      }	nt          |          }	|	dk     r|	|z  }	t          |	d          }	|dk    s	||dz   k     rD|	dk    r|                    | | d                    |                    | d|                    |	dk    r%|                    || ||z
  d         z              ;|	|k    s	||dz   k     r%|                    | d||z
           |z              o||z
  |z   }
|	|
dz  z
  }||
z   }|                    | d|         |z   | |d         z              t          | t                    rd	
                    |          S d

                    |          S )a  Return string cut to specified length.

    Parameters:
        string:
            String to snip.
        width:
            Maximum length of returned string.
        snipat:
            Approximate position at which to split long strings.
            The default is 0.5.
        ellipsis:
            Characters to insert between splits of long strings.
            The default is '...'.

    Examples:
        >>> snipstr('abcdefghijklmnop', 8)
        'abc...op'

    N      ?r  u   …rW   r   r  r  r  rA  )r   r  r   r  r   r
  r   rx  r'  rq  r   )r9  r^  r~  r  rR  r  r  r  linelenr  splitlenr  r  s                r   r   r   MY  s   6 ~fe$$ 	 HHHMME""$$J F !D !D<MM(###d))eMM&!!!>Vq[[EEV    q     
7V#34455EEKKE199WEqMMEA::**zzfeVWWo....fVeVn----aZZMM(VEEMOO%<<====g!2!2MM&55=1H<====.H8q=(D(?DMM&$-(2VDEE]BCCCC&%   "zz&!!!99Vr   r:  c               6    | j         }|t          |           }|S )zdReturn short string representation of Enum member.

    >>> enumstr(PHOTOMETRIC.RGB)
    'RGB'

    )ru   r   )r:  ru   s     r   r8   r8   Y  s      9D|4yyKr   r4  enum.IntEnumc                   	  | |          S # t           $ rC 	 | |                                         cY S # t           $ r}t          d|          |d}~ww xY ww xY w)a  Return enum member from its name or value.

    Parameters:
        enum: Type of IntEnum.
        arg: Name or value of enum member.

    Returns:
        Enum member matching name or value.

    Raises:
        ValueError: No enum member matches name or value.

    Examples:
        >>> enumarg(PHOTOMETRIC, 2)
        <PHOTOMETRIC.RGB: 2>
        >>> enumarg(PHOTOMETRIC, 'RGB')
        <PHOTOMETRIC.RGB: 2>

    zinvalid argument N)r  rT  r   )r:  r0  r  s      r   r7   r7   Y  s    (CtCyy C C C	C		$$$$ 	C 	C 	C88899sB	CCs(   
 
A4A
AAAA	keyvaluesc                   i }|D ]}|| v r| |         ||<   | |= |                                 D ]\  }}|| v r| |         ||<   | |= |||<   |S )aZ  Return dict with keys from keys|keyvals and values from kwargs|keyvals.

    Existing keys are deleted from `kwargs`.

    >>> kwargs = {'one': 1, 'two': 2, 'four': 4}
    >>> kwargs2 = parse_kwargs(kwargs, 'two', 'three', four=None, five=5)
    >>> kwargs == {'one': 1}
    True
    >>> kwargs2 == {'two': 2, 'four': 4, 'five': 5}
    True

    r  )r   r  r  r  rn   rU  s         r   rB   rB   Y  s     F  &== +F3Ksoo''    
U&== +F3KsF3KKMr   c               L    |                                 D ]\  }}|| vr|| |<   dS )zUpdate dict with keys and values if keys do not already exist.

    >>> kwargs = {'one': 1}
    >>> update_kwargs(kwargs, one=None, two=2)
    >>> kwargs == {'one': 1, 'two': 2}
    True

    Nr  )r   r  rn   rU  s       r   rJ   rJ   Y  s@      oo''    
UfF3K   r   c                 X    t          d |                                 D                       S )zoReturn dict of kwargs which values are not None.

    >>> kwargs_notnone(one=1, none=None)
    {'one': 1}

    c              3  *   K   | ]}|d          
|V  dS r  r   )r   r(  s     r   r   z!kwargs_notnone.<locals>.<genexpr>Y  s+      GG473F3F3F3F3FGGr   )r  r:  )r   s    r   r   r   Y  s)     GGGGGGGGr   logging.Loggerc                 *    t          j        d          S )z"Return logger for tifffile module.tifffile)logging	getLoggerr   r   r   r=   r=   Y  s    Z(((r   jhover  Collection[str] | Nonec               R   ddl }|ddh}|d}|                    || ddg          }d|v ry|                                D ]f}|                                }|                    d          r9|d	d                                         }|D ]}||v r n	t          |           dS edS dS )
aJ  Validate TIFF file with ``jhove -m TIFF-hul``.

    JHOVE does not support the BigTIFF format, more than 50 IFDs, and
    many TIFF extensions.

    Parameters:
        filename:
            Name of TIFF file to validate.
        jhove:
            Path of jhove app. The default is 'jhove'.
        ignore:
            Jhove error message to ignore.

    Raises:
        ValueError:
            Jhove printed error message and did not contain one of strings
            in `ignore`.

    References:
        - `JHOVE TIFF-hul Module <http://jhove.sourceforge.net/tiff-hul.html>`_

    r   NzMore than 50 IFDszPredictor value out of ranger  z-mzTIFF-huls   ErrorMessage: r  )
subprocesscheck_outputr  r=  r  r  r   )r  r  r  r  r   r  rB  r  s           r   rK   rK   Z  s    8 ~%'EF}

!
!5(D*"E
F
FCCNN$$ 		 		D::<<D011 RSS	((** , ,AEzz " %U+++  		 		r   r  r  tagcodeint | str | Nonec                  |d}|d}|dnd}t          | |          5 }|j        |         }t          |t                    st	          d| d          |j                            |d          }|#t          dt          j	        |          d	          ||j
        cddd           S |                    |           	 ddd           dS # 1 swxY w Y   dS )
a  Return or replace ImageDescription value in first page of TIFF file.

    Parameters:
        arg:
            Specifies TIFF file to open.
        comment:
            7-bit ASCII string or bytes to replace existing tag value.
            The existing value is zeroed.
        pageindex:
            Index of page which ImageDescription tag value to
            read or replace. The default is 0.
        tagcode:
            Code of tag which value to read or replace.
            The default is 270 (ImageDescription).

    Returns:
        None, if `comment` is specified. Else, the current value of the
        specified tag in the specified page.


    Nr   r  r  )rt   r  z
 not foundzno z
 tag found)r   r"  r   r   r  r  rY  r   r   r  rU  r  )r0  r  r  r  rt   r   r  r9  s           r   r   r   1Z  sW   8 	TD	#D	!	!	! 
Sy#$)) 	@>>>>???immGT**;A49W#5AAABBB?9
 
 
 
 
 
 
 
 	g
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
s   A>C+CCC)
r   rn   ro   rp   r   r   r   rq   	groupnamerJ  urlr  rJ  c      
   
     "   |t          j        |           dz   }t          |           5 }|                    |||||||	          5 }|                    |||
|           ddd           n# 1 swxY w Y   ddd           dS # 1 swxY w Y   dS )ar  Write fsspec ReferenceFileSystem in JSON format for data in TIFF file.

    By default, the first series, including all levels, is exported.

    Parameters:
        filename:
            Name of TIFF file to reference.
        url:
            Remote location of TIFF file without file name(s).
        out:
            Name of output JSON file.
            The default is the `filename` with a '.json' extension.
        key, series, level, chunkmode, fillvalue, zattrs, squeeze:
            Passed to :py:meth:`TiffFile.aszarr`.
        groupname, version:
            Passed to :py:meth:`ZarrTiffStore.write_fsspec`.

    Nz.json)rn   ro   rp   r   r   r   rq   )r  rJ  )r  r  r   rm   write_fsspec)r  r  r   rn   ro   rp   r   r   r   rq   r  rJ  r   r   s                 r   r   r   _Z  sP   D {i!!G+	(		 OsZZ  
 
 		O sC9gNNN		O 		O 		O 		O 		O 		O 		O 		O 		O 		O 		O 		O 		O 		O 		OO O O O O O O O O O O O O O O O O Os5   BA, B,A0	0B3A0	4BBB)r   verbosebinfilelsmfiler  c                 |rt           nt          }|d}|| }n|                                dk    rd}|r|dz  } |ddd           t                      }t	          |           5 }|j        s |d	|d
           t          d          |j        d         }|                    d          }|	                    d          }	|j
        }
t          |          |
j        z  } ||            |t          dd|	 d| d|
 d|           d
           |	dk    rd|z   }nn|	dk    rd|z   }nb|	dk    r|dd         dz   |dd         z   }nC|	dk    r|dd         dz   |dd         z   }n$|	                    d          st          d           |ddd           |                                 |d         |d         z  |d         |d         z  f}|r!||d         |d          |d         |d!         fz  }dd"t!          |          z
  z  |z   }t#          j        |d#d         |
$          }t#          j        |d         |d          |d         |d!         f|
$          }t'          |j                  }t+          |d                   D ]}t+          |d!                   D ]}t+          |d                   D ]}t+          |d#                   D ],}t-          |          }|J |                                ||<   -t+          |d                   D ]}t+          |d!                   D ]m}|d%||d         z  |d!z   |d         z  ||d!         z  |d!z   |d!         z  f         |dd<   |r|                    ||||||fz              |d&dd           n ||d
           ddd           dS # 1 swxY w Y   dS )'aU  Convert [MP]TZCYX LSM file to series of BIN files.

    One BIN file containing 'ZCYX' data is created for each position, time,
    and tile. The position, time, and tile indices are encoded at the end
    of the filenames.

    Parameters:
        lsmfile:
            Name of LSM file to convert.
        binfile:
            Common name of output BIN files.
            The default is the name of the LSM file without extension.
        tile:
            Y and X dimension sizes of BIN files.
            The default is (256, 256).
        verbose:
            Print status of conversion.

    N)r  r  r	  z*_(z%ic%iy%ix%i)_m%%ip%%it%%03iy%%ix%%i.binz
Opening LSM file... r  Tr)
  rA  )r  znot a LSM filer   Frn  zaxes:  zshape: zdtype: zsize:  CYXr  r  r  MPCYXr  MPZCYXr  znot a *TZCYX LSM filez#Copying image from LSM to BIN filesr}  rT  r  r  rW   r  r   r~  .r  )r,
  r@   r  r3   r   rC  r   ro   rc  r  r~   rD   r  r  rP  r  r   r  r  r-  r"  r  r  r   r	  )r  r  r   r  printstimerrn  ro   r   r  r~   rw   r  r   r   r"  rN  r]  r  rK  r  r  r  s                          r   r   r   Z  s   6 #0%%F|	F	"	" @??
F#48888GGE	'		 ?"cz 	/F4D))))-...A  ''u%%u~~.u $  !%!!!%!! $    		
 		
 		
 		
 5==UNEEV^^5LEEW__"1"I&qrr2EEX"1"I$uQRRy0EEw'' 	645554"DIIIIb	T"X%uRyDH'<< 	IrE"ItAwQ HHGCJJ'%/{59E222k2Yb	47DG4E
 
 
 V\""uQx 	< 	<A58__ < <uQx < <A"58__ 1 1#E{{#///"&,,..Q"58__ 	< 	<!&uQx < <A%) # !DGq1uQ.? ? !DGq1uQ.? ?!A&CF
  ' F #

7aAq!_+D E E E"F3Bd;;;;;<	<<<  	uD!!!!?" ?" ?" ?" ?" ?" ?" ?" ?" ?" ?" ?" ?" ?" ?" ?" ?" ?"s   &M N33N7:N7`   )r   r   r   r  interpolationr  vminvmaxfiguresubplotr7  window_titledpimaxdim
backgroundshowr  r  r  r  r  r  r  r7  r  r  r  r  'tuple[float, float, float] | str | Noner  tuple[Any, Any, Any]c                 	 !"#$%& |d}|d}|dv } j         dk    r                     t          j                    j         j        dk    rd}|r- j        d         d	v s j        d
k    r j        d         d	v sd}d}                                  |dv rt           d
           nt           d            j        ""d
k     rt          d          "d
k    rd"d}n|rK j        d         d	v r< j        d         d	vr-t          j
         dd           t          j
         dd           nl|sj j        d          j        d         dz  k     rK j        d          j        d         dz  k     r,t          j
         dd           t          j
         dd           |o j        d         d	v }"|rdnd
z  "|d}nt          |t                    r|}nd}|r< dd|d|d|f          |r' j        d         |k    s j        d         |k    rd}n;d}n8 dd|d|f          |r' j        d         |k    s j        d         |k    rd}nd}|dk    rN|rL	 t          j                   }n# t          $ r d}Y nw xY w|dk    r dz	                        dd           n j         j        dv r|r j         j        dk    r|g	 t          t          j        t          j                                         d
                              }nO# t$          $ r  j         j        dz  }Y n4w xY wt          |t          t          j        f          s j         j        dz  }|J d
|z  }|r4|dk     r	 d|z
  z   n|dk    r |dz
  z	                        dd           n j         j        dk    r|r'                                  t          j          |k    <   	 t          j                   }n# t          $ r d}Y nw xY w|r6|dk    r0 j         j        dk    r                     d            |z   ne |z   n_ j         j        dk    rd}nL j         j        d k    r<t          j                    	 t          j                   }n# t          $ r d}Y nw xY w|rd}n||}| j         j        d!k    rkt          j         j                   j        }	 t          j                   }n# t          $ r d}Y nw xY w||k    rt          j          |k                       }n j         j        dk    rxt7          t          j         j                   j                  }	 t          j                   }n# t          $ r d"}Y nw xY w||k    rt          j          |k                       }nd}dd#lm% dd$l m! 	%"                    d%d&d'd(           %#                    |d)d*d+d,-          	|6	 	j$        j%        j&        '                    |           n# t$          $ r Y nw xY w|r!tQ          |)                                          nd}%*                    d."d
z   z  d/|d.z  z
  d0d1d2d"3           |
d4}
%+                    |
          }
|d5}|
,                    |           |rAt          |tZ                    r|.                    d6          }%'                    |d78           |7 j         j        d9k    rd:}n j         j        d;v s|dk    rd<}nd=}|d>k    r|d?z  } %j/        t          j0         d@"z                                                     f||||dA|#|s%1                                 dQ ! "fdG}dRdJ}||
_2        |#_3        |#_4        "rtk          d@"z            !d tm          !                                                   g  %fdKto          "          D             }|D ]	}d|_8        
| f 	#fdL	& !f &fdM	$ !f $fdN	}	j$        9                    dO|           tu          |          D ]\  }}|;                    |f$fdP	            |r%<                                 	|
#fS )Sa  Plot n-dimensional images with `matplotlib.pyplot`.

    Parameters:
        data:
            Image array to display.
        photometric:
            Color space of image.
        planarconfig:
            How components of each pixel are stored.
        bitspersample:
            Number of bits per channel in integer RGB images.
        interpolation:
            Image interpolation method used in `matplotlib.imshow`.
           The default is 'nearest' for image dimensions > 512,
           else 'bilinear'.
        cmap:
            Colormap mapping non-RGBA scalar data to colors.
            See `matplotlib.colors.Colormap`.
        vmin:
            Minimum of data range covered by colormap.
            By default, the complete range of the data is covered.
        vmax:
            Maximum of data range covered by colormap.
            By default, the complete range of the data is covered.
        figure:
            Matplotlib figure to use for plotting.
            See `matplotlib.figure.Figure`.
        subplot:
            A `matplotlib.pyplot.subplot` axis.
        title:
            Subplot title.
        window_title:
            Window title.
        dpi:
            Resolution of figure.
        maxdim:
            Maximum image width and length.
        background:
            Background color.
        show:
            Display figure.
        **kwargs:
            Additional arguments passed to `matplotlib.pyplot.imshow`.

    Returns:
        Matplotlib figure, subplot, and plot axis.

    NrN  r  >   rN  rO  float16r	  FrT  r  r  r  rL  >
   Nrc  r  rd  r  rP  r  rL  rM  r  r   znot an imager   r}  rY  r  .bilinearnearestrP  rW   r  r  r  uir  r  r  r  r  r*
  pyplot)Sliderfontz
sans-serifnormal)familyweightrw   )g$@g333333@Tz1.0rP  )r  figsizeframeon	facecolor	edgecolorQ?g\(\?g?gffffff?g?)bottomtopleftrighthspacewspaceo   )禛 r?r  r  zWindows-1252rY  )rw   r   graybufviridiscoolwarmrM  _rr  )r  r  r  r  r  r  r  r   r   c                   t          | dz             } t          |dz             }	 rd         || f          d d|dd| ddS || f          d|dd| ddS # t          $ r Y d	S w xY w)
Nr  rW   z @ z [4r   r  z @ [r  )r   r  )r  r  curaxdatcurrentr   r  s     r   format_coordzimshow.<locals>.format_coord\  s    CLLCLL	 I"1+ad+HHHH1HHH!HHHHH1a4j33a333Q33333 	 	 	22	s   A A 
A*)A*r+  rb   c                    dS )Nr  r   )r+  s    r   r	  zimshow.<locals>.none"\  s    rr   c                    g | ]P}                      d d|dz   z  ddf          d| dj        |         dz
  ddj        |          d	          QS )
g      ?r  rW   g333333?g?z
Dimension r   z%.0f [r  )rv  rm  valminvalmaxvalinitvalfmt)r  r   )r   r  r  r   r  s     r   r:  zimshow.<locals>.<listcomp>,\  s     

 

 

  F;;ttax'8%GHH)4))z$'!+3
4 0333  

 

 

r   c                6   |t          |                                                    d<                       d                    t          ||           D ](\  }}d|_        |                    |           d|_        )j                                         d S )NrW   FT)r  rq   set_datar  eventsonset_valcanvasdraw)r  slidersr   ctrlr  r  r  rD  s        r   	set_imagezimshow.<locals>.set_image:\  s    uW~~.6688HQKNN8A;'''"7G44 % %e %U### $M     r   c                    t          t          |                     } |d<   | ||         k    rd S | |j        |         k    rd} n| dk     r|j        |         dz
  } | ||<    |           d S )Nr   rW   )r   r  r   )r  r  r   r  r  r  s       r   
on_changedzimshow.<locals>.on_changedD\  s    e%%EHQK%%
4(((
4(1,!GDMIgr   c                   | j         }d         }t          |          dv r ||           d S |dk    r ||         dz   |           d S |dk    r ||         dz
  |           d S |dk    r'|t          |j                  dz
  k    rdn|dz   d<   d S |dk    r'|dk    rt          |j                  dz
  n|dz
  d<   d S |dk    r |j        |         dz
  |           d S |d	k    r d|           d S d S )
Nr   rE  r  rW   r  updownr%
  home)rn   r   r   r   )r+  r   r  rn   r  r  r  s        r   on_keypressedzimshow.<locals>.on_keypressedQ\  sN   )CA;D3xx<''
3%%%%%
74=1,d33333
74=1,d33333#'3tz??Q+>#>#>aaD1H59QYYc$*oo11D1H
4:d+a/66666
1d##### r   key_press_eventc                     | |          S r   r   )r   r  r  s     r   r  zimshow.<locals>.<lambda>g\  s    **Q"2"2 r   )r  r  r  r  r   r   )r+  rb   r   r   )=r~   r5   r  r  rW  r   r  rq   rG   r   r  r   r   rq  r  rx  ry  logr  r`  rj  nannanmaxr%  absoluteiinfor  r  finfonanmin
matplotlibr  matplotlib.widgetsr  rcr  r  managerwindowr7  r   r  subplots_adjustr  set_facecolorr  r  r   
atleast_2dcolorbarr  get_cursor_dataformat_cursor_datarA  r  r  drawonmpl_connectr  r  r  )'r   r   r   r   r  r  r  r  r  r  r  r7  r  r  r  r  r  r   r  r7  datamaximinfminrw   r  r	  r
  sliderr  r  r  r  r  r  r  rD  r  r  r  s'   `        `                     @@@@@@@@r   r   r   Z  s
   P ~++EzY{{5=))z# #
2&  IMMdjn66"<<>>D    $""$""9Daxx(((qyy 	0TZ^v--$*R.2N2N>$B//D>$B//DD 	0JrNTZ^q000
2B1!444>$B//D>$B//D2$*R.F2U!!			M3	'	' !			 *C&'6'7F723 	*z"~	))TZ^i-G-G * )C&'6')* 	*z"~	))TZ^i-G-G * )iE	iooGG 	 	 	GGG	S==19D{{3U{++	D	 	  	4$*-22}7L8 #DIdhtxxzz1.E.E$F$F G G 8 8 8 $
 3a 78MC+?@@ 	4 J/!3M(((]" 	0q  M 12"" 12;;s;//D	C		 	-99;;D#(9D 	l4((GG 	 	 	GGG	 	&Ws]]z#%%{{3''g~	C			C		~d##	l4((GG 	 	 	GGG	  <D<z#%%{4:..2 9T??DD!   DDD4<< 9T$+%677DC''U[44899 <--DD!   DDD4<< <TD[(9::D!!!!!!))))))~		&hQ	GGG  
 
 #%,22<@@@@   */6s5##%%&&&Q4!8$td{" 	 	
 	
 	
 nnW%%G*
*%%% %eU## 	1LL00EU$$$|:?c!!DDZ_%%DDD,&&DLDFMdTk*224455#   E  	 	 	 	 	 	 	 	 	    (G E#E ?td{##tE'NN+33556

 

 

 

 

 

 d

 

 

  	" 	"F!FMM'.T 	! 	! 	! 	! 	! 	! 	! 	! *.w 	 	 	 	 	 	 	 '+G 	$ 	$ 	$ 	$ 	$ 	$ 	$& 	!!"3]CCC#G,, 	 	JD$OO 22222     7E!!s   I( (I76I7AL L$#L$O& &O54O5)Q> >RRS! !S0/S0U) )U87U8&$X 
XXc                     ddl m}m}  |            }|                                 |                                  |j        di | }|                                 |S )z4Return file name(s) from Tkinter's file open dialog.r   )Tk
filedialogr   )tkinterr/  r0  withdrawr  r4   destroy)r   r/  r0  rS  r  s        r   r4   r4   p\  sj    &&&&&&&&244DMMOOOKKMMM*
*44V44ILLNNNr   c                    ddl } t                                          t          j                   |                     dddt           d          }|j        } |dd	d
ddd            |dddddd            |dddddd            |ddddd            |ddddd             |d!d"d#dd$%            |d&d'dd(d)            |d*d+ddd,            |d-d.ddd/            |d0d1d2dd3            |d4d5ddd6            |d7d8ddd9            |d:d;d<dd=>            |d?d@dAdB           |                                \  }}dC	                    |          s2t          dDt          j        E          s|                    dF           t          fdGdHD                       r/t          j                  }|st!          dI           dS |d         |j        st!          dJdCdKL           t%                      }	 t'          |j         M          }n?# t*          $ r2}|j        r t!          dN|j        j         dO|            Y d}~dS d}~ww xY w|j        st!          |           |j        rdK|_        g }|j        dk    r|j        st!          dPdCdKL           dodT}	|                                 	 |j        dk    r7|                    |j        |j        U          |j         |j                 dfg}n|j!        dk    r|j!        |j!                 }
|j"        dk    r|j"        }nM|
j#        rDtI          |
j%                  dVk    r,d}|
j&        D ]!}|dWz  }tI          |j%                  dVk     r n"nd}|                    |j!        ||j        X           |	|j!        |j!                 j'                  |j!        |j!                 fg}ntQ          |j!        d|j                           D ]\  }}|j"        dk     r,d}|j&        D ]!}|dWz  }tI          |j%                  dYk     r n"n|j"        }	 |)                    |                    |||j        X           |	|j'                  |j!        |         f           # t*          $ rQ}|)                    d |	|j                   df           |j        r t!          dZ| d[|d\d]d^_           Y d}~d}~ww xY wn=# t*          $ r0}|j        r t!          |j        j         dO|            Y d}~nd}~ww xY w|j        st!          |           |j        st!          d`dadKL           |                                 	 tU          j+                    d         }n# t*          $ r db}Y nw xY w|,                    t[          |j.                  |dWz
  c          }t!          |           t!                       t!          |           t!                       |r|j        dk    r	 dddl/m0} |D ]o\  }}}
|
|j1        }|j2        |j3        }}|j4        rr	 |j5        j6        dek    r-tn          j8        |||j4        k    <   to          j9        |          }n#to          j:        |||j4        k                       }n# tv          $ r Y nw xY w|j<        r@	 |j=        df         }|j=        dg         }||k    r|j2        |j3        }}n# t|          $ r Y nw xY w|
r| dh| dh|
 }|j?         di|
j@         }n| dh| }|j?         dj|j@         }dk}|jA        dlk    rt          |jA                  jC        }t          ||||||jE        |jF        |j4        ||jG        |jH        dm           q|I                                 n<# t          $ r/}t                      K                    dn|d\           Y d}~nd}~ww xY w|L                                 dS )pz*Tifffile command line usage main function.r   Nzusage: %prog [options] pathz(Display image and metadata in TIFF file.z%prog r  )usager   rJ  progz-pz--pager  r   rT  zdisplay single page)destr~  r  helpz-sz--seriesro   zdisplay select seriesz-lz--levelrp   zdisplay pyramid level of seriesz--nomultifilenomultifile
store_trueFz*do not read OME series from multiple files)r7  actionr  r8  z
--maxplotsmaxplotsr  zmaximum number of plot windowsz
--interpolinterpolINTERPOLzimage interpolation method)r7  metavarr  r8  z--dpir  r  zplot resolutionz--vminr  zminimum value for colormappingz--vmaxr  zmaximum value for colormappingz--cmapr  r   z(colormap name used to map data to colorsz--maxworkersrr   zmaximum number of threadsz--debugr  zraise exception on failuresz-vz--detailr8  r  )r7  r~  r  z-qz--quietquiet)r7  r;  r!  zSelect a TIFF file)r7  	filetypeszNo file specifiedc              3      K   | ]}|v V  	d S r   r   )r   r  r  s     r   r   zmain.<locals>.<genexpr>\  s'      
#
#19
#
#
#
#
#
#r   z?*zNo files match the patternz
Reading TIFF header:Tr)
  )r   rI  r  zReading image data:r  rb   r   c               4    t          d | D                       S )Nc              3     K   | ]}||V  	d S r   r   r  s     r   r   z(main.<locals>.notnone.<locals>.<genexpr>]  s"      66a66r   rM  r  s    r   notnonezmain.<locals>.notnone]  s    661666666r   )rn   rr   r|  rW   )ro   rp   rr   rI  z
Series r  r9  z... r  r/
  zGenerating report:r@  P   rE  r  r  r  r  rA  z series z page rL  r   )r7  r  r  r  r  r   r  r   r  r  r  z<tifffile.main> raised )r  rb   r   rb   )Moptparser=   setLevelr  INFOOptionParserr   
add_option
parse_argsr   r4   r   r_  rB  r@  r   r,
  r@  r3   r   r9  r  r  r-  r*  r>  norgbr<  r  r  r   rr   r"  ro   rp   r  rD   r   r   r  r  r   r  get_terminal_sizer4  r   r8  r  r  rb  r  r  r  r~   rW  r  r  r  r  r   rZ  r  r  r  r  r   r&   ru   r   r  r   r=  r  r  r
  rs  r  )rG  r
  optr  	path_listr  r   r  rk  rE  ro   rp   r0  r  r  r^  r  r  imgr  rb  r  r  r7  r  r   r  s                             @r   mainrR  |\  s
   OOO
HHgl###""+>&&&	 #  F 
CC"    C$    C.    C9    C-    C)    Ce%:KLLLLC-    C-    C7    C(    C*    CjxeQ????Cigl;;;; ++--Hi88ID .&$2F
 
 
  	.LL,---

#
#
#
#d
#
#
### IdOO	 	.///1|> =&Ct<<<<GGEtH,@(@AAA   > 	4S]+44s44555qqqqq	 > e
z )+F1~ 	>'S====	7 	7 	7 	7 	@	6}!!  ((:M $   	(-0 A%%HO4>Q&&$NEE( WV\-B-BU-J-JE#] " "
"17++e33!E 4 E #+?"''/': $  
  
8? ; BCC
8?3
 &cj1D83D1D&EFF O ODAq~)) "!" & &A!QJE&qw//%77 %  8 !)O #+,*//7/B !, !" !"
 !( 1 1 #
1
 
 
 
 % O O OtWWQW-=-=t&DEEE#> "!E!EESEEEE2NNNNNNNNN	O
  	6 	6 	6~ S]+44s4455555555	6
 ~ 	%LLL> "T::::	(**1-EE 	 	 	EEE	xxs8?33519xEEed 8(#a''7	)))))) &, 1 1!T6;=%]HMd? 9>S00:?)Cx 67#(<#4#4DD#(9Sx1F-G#H#HD%   : FF"/&   #/&   4<<)1$D	 $   
  G"66d66f66E&)l#J#JFL#J#JLL",,d,,E&)l#F#F$*#F#FL*'1,,"-h.B"C"C"HK!-!"*"8#? +"*"3      KKMMMMk  	E 	E 	EHHCsCCCDDDDDDDD	En IIKKK1s   H% %
I!/'II!E9S. ARS. 
S*AS% S. %S**S. .
T(8&T##T(/V	 	VV^  A Z!!
Z.-Z.9[((
[54[5
_)%__strictr	  errorsc               8   |d|vr&|                      d          }|dk    r
| d|         } n+|                      d          }|dk    r| d||dz  z            } 	 |                     |dn||          S # t          $ r | |                     d|          cY S w xY w)	zDReturn Unicode string from encoded bytes up to first NULL character.N16r1  r   r  r  r  r  )r  r  r  )r	  r	  rT  r  s       r   r  r  ]  s     4x//FF7OO66"1"A FF;66+AAI+A*xx8#36JJJ * * *xx&)))))*s   A3 3#BBr  r  c               Z    t          | t                    r|                     |          n| S )z4Return bytes from Unicode string, else pass through.)r   r   rm  )r  r	  s     r   bytestrrX  ]  s(    !+As!3!3:188H:r   )rf	  	ZarrStorerj  __main__r   )Dr   r   rl   r   rm   r   rn   r   ro   r   rp   r   rq   r   rr   r   rs   r   rt   r   ru   r   rv   r   rw   r   rx   r   ry   r   rz   r   r   r   r{   r   r|   r   r}   r   r~   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rb   r   r   )Fr   r   rl   r   rm   r   rn   r   ro   r   rp   r   rq   r   rr   r   rs   r   rt   r   ru   r   rv   r   rw   r   rx   r   ry   r   rz   r   r   r   r   r   r{   r   r|   r   r}   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rb   r   r   )Fr   r   rl   r   rm   r   rn   r   ro   r   rp   r   rq   r   rr   r   rs   r   rt   r   ru   r   rv   r   rw   r   rx   r   ry   r   rz   r   r   r   r   r   r{   r   r|   r   r}   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rb   r   r   )Pr   r   r   r   rt   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r~   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rT   r   r   r  r   r  r   r  r   r  r   r   r   r  r   r   r   r   r   r   rr   r   rs   r   r   r   r   r   )r  r  r   r   r~   r   r  r   ro   r   rp   r   rt   r  r   rb   r   r  )r   r  rJ  r   r  r   rq  r.   r  r   r  r   r   r  )rq  r.   r   r  r~   r   r  r   rJ  r   r   r  )rq  r.   r   r  r~   r   r  r   rJ  r   r   r  )rq  r.   r   r  r~   r   r  r   rJ  r   r   r   )rq  r.   r   r  r~   r   r  r   rJ  r   r   r   )rq  r.   r   r  r~   r   r  r   rJ  r   r   rb   r  )r  r   rq  r.   r   r  r~   r   r  r   rJ  r   r   r  )rq  r.   r   r  r~   r   r  r   rJ  r   r   r  )
rq  r.   ru  r   r  r   rv   r   r   r/  )rq  r.   r   r  )rq  r.   r   r   )rq  r.   r   rO  )rq  r.   r   r  )r  r  rq  r  r   r  )r   r  r   r  )rq  r  r   r  )rq  r  r   r  )r   r  r   r  r   r  )r   r  r  r  r   r  r   r  )r   r   r   r  )NNF)r  r   r  r   r  r   r   r  r   rb   r   r   )r   r  r  r   r  r   r   r  )
r   r   r   r   r   r  r?  r   r   r  )r  r  r   rZ  )r  r  r   r
  )r   r  r   rb   r   r   )r  r  r   r   r   r  )r   r   r   r  )r   r   r   rb   )r>  r   r   r   )rA  r   r   r  )r  )rZ  r   r   r   r   r  )r   r   rq  r.   r   r  )NNT)
r~   r   r   r   rp  r   r   r  r   r   rk  )r
  r   rD  r   r   r   r   r   rD	  )rx   r   ry   r   rz   r   r   r{  r	  r   r   r|  )r   r   r   r  )
r  r  r   r  r~   r	  r   r   r   r  )r   r   r   r  r  r  r   r  )r	  r   r  r  rm  r  r   r  r~   r	  rr   r   rs   r   r  r   r   r  )rD  r   r  r  r   r   )r  rf   r  r  r   r   )r  r  r  r   r   r  )r  r   r  r   r   r   )r  r  r  r   r   r  )r  r   r   r  r  r   r   r  )r  r  r   r  r  r{  r   r  )r  r	  r   r  r  r  r   r  )r  r  rD  r   r  r   r   r   )
r  r   r  r   r   r  r  r  r   r   )
r  r   r  r{  r   r  r  r  r   r{  )
r  r   r  r  r   r  r  r  r   r  r$  )rq   r   r  rf   r   r  )r  r  r  r  r   r   r  )
r]  r   r   r   r  r   r	  r   r   r   )
r]  r   r   r   r  r
   r	  r
   r   r   )
r]  r   r   r   r  r  r	  r  r   r   )r  r   ro   rl  r   r  )r"  r	  re	  r  r  r  rr   r   r   r   r   rb   r   r   )r   r  r~   rg   r   r   rt   r  r  r   r   r   r   r  )r  r   r   rb   )r  r   rL  r   r   rn  )r  r   r9  r  r  r   r   r  )r  r   r9  r   r  r   r   r   )r  r   r9  r  r  r   r   r  )r9  r  r   r  r  )r
  r  r
  r  rU  r   r   r   )r
  r$  r
  r$  rU  r  r   r   )r
  r&  r
  r&  rU  r  r   r'  )r:  r*  rU  rb   r   rb   )r0  r-  r   r4  )r3  rm	  r   rm	  )r6  )r7  r  rw   r  r   r   )r0  rb   r;  rb   r   rb   r   rb   )r;  rb   r   rb   r   r  )rU  rb   r   rA  )rC  rD  r   r   )rG  rH  r   rI  )rC  rN  r   r  )rV  r   rW  r   r   rn  )r[  r  r\  r   r   rn  )r`  r   ra  r   r   rn  )r   r   r   r   )r   r   rh  r   r   r   )ri  r	  r   r  )
r
  r   rm  r   r  rn  rZ  r   r   r  )r   r  r^  r   r  r   r~  r   rd  r   r  r   r   r   )r9  r  r   r   )r  r   r9  r   r   r   )r;  rb   r   r   )r
  r  r   r   )r0  rb   r  r   r^  r   r  r   r  r   r   r   )r7  )
r^  r   r9  r   r~  r   r  r   r   r   )r:  rb   r   r   )r:  r4  r0  rb   r   r  )r   r  r  r   r  rb   r   r  )r   r  r  rb   r   r  )r   rb   r   r  )r   r  )r  r   r  r  r  r   r   r  )
r  r   r  r   r  r  r0  r   r   r   )r  r   r  r  r   r   rn   r   ro   r   rp   r   r   r   r   r   r   r   rq   r   r  r   rJ  r   r   r  )
r  r   r  r   r   r   r  r   r   r  )&r   r   r   r   r   r   r   r   r  r  r  r   r  r   r  r   r  r   r  rb   r  rb   r7  r   r  r   r  r   r  r   r  r  r  r   r   rb   r   r  )r   rb   r   r   r  )NrS  )r	  r   rT  r   r	  r  r   r   )r  )r	  r   r  r  r   r  )r-  
__future__r   r   __all__r  rv  r:  r   r  r  r  rx  r  ri  rj  rd  r	  r-
  rm  collections.abcrO   rP   rQ   rR   concurrent.futuresrS   rT   rn  rU   r8
  	functoolsrV   r  r/  r
  r  rY   typingrZ   r[   r\   r]   r^   r_   r`   ra   rb   rc   rd   re   numpy.typingrf   rg   rh   r  r   r  r   r  r   r   r  r   r   r   r  r   r   r   r   r   r   r	   r   r   r   r
   r/   r   r1   r.   r-   r0   r2   r3   r,   r+   r  r
  r1  r;  r   r    r(   r&   IntFlagr"   r$   r#   r%   r'   r)   r!   r*   r   rM   r   r  r  r  r  r  r  r  r  r  r  r  r$  r  r  r  r%  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r   r   r   r  r<   r  r  r;   rZ  r  r   r-  rl  r  r   r  r+  r/  r  r=  r@  r  r  r  r  r  rA   rz  r  rw  r  r  rE   rG   r  rI   rF   r  r  r  r  rf  r6   r>   rH   rN   r   r3  r5   ru  r,	  r9   r
  r@   rS  rD   r}  r?   rZ  r_  r  rJ  rh  r  rL   r:   r  r  r  r  rC   r   r8   r7   rB   rJ   r   r=   rK   r   r   r   r   r4   rR  r  rX  r   r   rf	  rY  rj  r*  exitr   r   r   <module>rd     s  @P Pd # " " " " "M M M^        				    				 				  



       A A A A A A A A A A A A 1 1 1 1 1 1 ) ) ) ) ) ) + + + + + + % % % % % % + + + ++1111111 + + +******+	+ < ; ; ; ; ; ; ; ; ; ; ; ; ; 
??????????444444444444::::::::::!IsBuIws|T9:Jc3hsCx(3-dBH
 
 	* ! .2!!&*&*3715-1/3)-"CG.2$($(##""Q* * * * * 
*Z 
 	+0 !.2!!&*&*3715(,-1/3)-#'CG.2$($(##""S+0 +0 +0 +0 +0 
+0\ 
 	+? !.2!!&*&*3715(,-1/3)-#'CG.2$($(##""S+? +? +? +? +? 
+?l 	S
 !.2!!&*&*3715(,-1/3)-#'CG.2$($(##""SS
 S
 S
 S
 S
 S
~ 	Y ,0"&"&"2648=A!%# $26-159*.##!%&*-1 	15)-*.&(+/!!eY Y Y Y Y Y@ #'"$(YC YC YC YC YC YCx8 8 8 8 8I 8 8 8 E)N E)N E)N E)N E)N E)N E)N E)NPR \19 \19 \19 \19 \19 \19 \19 \19~b d
 d
 d
 d
 d
 d
 d
 d
N Y(
 Y(
 Y(
 Y(
 Y(
 Y(
 Y(
 Y(
xP U; U; U; U; U; U; U; U;p V	7 V	7 V	7 V	7 V	7I-. V	7 V	7 V	7r ^
 ^
 ^
 ^
 ^
 ^
 ^
 ^
B | | | | | | | |~ p
 p
 p
 p
 p
 p
 p
 p
f c4 c4 c4 c4 c4Xh2T9: c4 c4 c4Ln
 n
 n
 n
 n
8C= n
 n
 n
b = = = = =< = = =. C% C% C% C% C% C% C% C%L T T T T T T T Tn o: o: o: o: o: o: o: o:d \
 \
 \
 \
 \
(3- \
 \
 \
~        * m m m m m m m m`F F F F F) F F F k k k k k k k k\ n n n n nwsHS&[$99: n n nb p p p p pWS(3;"778 p p pf&0 &0 &0 &0 &0t| &0 &0 &0R` ` ` ` `$, ` ` `F       .    $,   @    t|   ,       
@ 
@ 
@ 
@ 
@ 
@ 
@ 
@    $,   "
B 
B 
B 
B 
B4< 
B 
B 
B    dl   ,# # # # #$, # # #" " " " "4< " " "*" " " " " " " "PG$J G$J G$J G$J G$J G$J G$J G$JTH uww  	} } } } } }@   6	M 	M 	M 	M	M 	M 	M 	M   *	# 	# 	# 	#         "   6	. 	. 	. 	.& $ $ $ $ $N   *8 8 8 8   *t t t tn: : : : - - - -`, , , ,- - - -- - - -	- 	- 	- 	-	 	 	 	   >7 7 7 7t1 1 1 1h8 8 8 8v    ' ' ' 'T   43 3 3 3l   ")) )) )) ))Z BFy y y y yx> > > >B! ! ! !H   e e e ePb b b bJ       L g- g- g- g- g-\ 7, 7, 7, 7, 7, 7,t% % % %>!, !, !, !,HI- I- I- I-X
  
  
  
 D D D D2 -1F F F F FR+ + + +\   (       F, , , ,^% % % %
   i i i iZ %(Q Q Q Q Qh9 9 9 9~ #,0= = = = =B DH    F &*37_' $(_' _' _' _' _' _'D   
K K K K05@ 5@ 5@ 5@pO6 O6 O6 O6d   D   > 
   

 
 N N N 
 N( ( ( (@ 

 	8 8 8 8 
8 

 "&	B B B B 
B (,	:: :: :: :: ::B $(	, , , , ,^ 
     
 
     
 D D D D DT     >   @ 
68    

 
BD    
     F 8=( ( ( ( (^ #'15!P P P P P Pr +/$%E E E E E EPd d d dN- - - - -` 
+/BF     

 
'+>B     
  $!
 ! ! ! ! ! !H   , 
 "&"&	    
 
 $($(	    
 *.*.	! ! ! ! !H    ." " " ""       $      C C C C   $   *) ) ) )"@ @ @ @> > > > >P P P P PB
A 
A 
A 
A   $   F %)Q- Q- Q- Q- Q- Q-p !%r. r. r. r. r. r.j   .    6
 
 
 
5 5 5 56 D D D D D DT M
 "&M M M M M M`
 
 
 
C C C C:   :       H H H H) ) ) ) %)	- - - - -f #'  $+ + + + +f .2$($( /O /O /O /O /O /Oj i"
 $(i" i" i" i" i" i"` 3748 $ $###:>'p" p" p" p" p" p"f	 	 	 	Z Z Z Z| =E* * * * *,; ; ; ; ; 
 FEEEEEEEEEEzCHTTVV s6   4A9 9B?BB	BBBBB