-
Notifications
You must be signed in to change notification settings - Fork 155
/
tifffile.py
12680 lines (11295 loc) · 438 KB
/
tifffile.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# tifffile.py
# Copyright (c) 2008-2020, Christoph Gohlke
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""Read and write TIFF(r) 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, STK, LSM, SGI,
NIHImage, ImageJ, MicroManager, FluoView, ScanImage, SEQ, GEL, SVS, SCN, SIS,
ZIF, QPTIFF, NDPI, and GeoTIFF files.
Numpy arrays can be written to TIFF, BigTIFF, and ImageJ hyperstack compatible
files in multi-page, memory-mappable, tiled, predicted, or compressed form.
A subset of the TIFF specification is supported, mainly uncompressed and
losslessly compressed 8, 16, 32 and 64-bit integer, 16, 32 and 64-bit float,
grayscale and multi-sample images.
Specifically, reading slices of image data, CCITT and OJPEG compression,
chroma subsampling without JPEG compression, color space transformations,
samples with differing types, or IPTC and XMP metadata are not implemented.
TIFF(r), the Tagged Image File Format, is a trademark and under control of
Adobe Systems Incorporated. BigTIFF allows for files larger than 4 GB.
STK, LSM, FluoView, SGI, SEQ, GEL, QPTIFF, NDPI, and OME-TIFF, are custom
extensions defined by Molecular Devices (Universal Imaging Corporation),
Carl Zeiss MicroImaging, Olympus, Silicon Graphics International,
Media Cybernetics, Molecular Dynamics, PerkinElmer, Hamamatsu, and the
Open Microscopy Environment consortium respectively.
For command line usage run ``python -m tifffile --help``
:Author:
`Christoph Gohlke <https://www.lfd.uci.edu/~gohlke/>`_
:Organization:
Laboratory for Fluorescence Dynamics, University of California, Irvine
:License: BSD 3-Clause
:Version: 2020.5.7
Requirements
------------
This release has been tested with the following requirements and dependencies
(other versions may work):
* `CPython 3.6.8, 3.7.7, 3.8.2 64-bit <https://www.python.org>`_
* `Numpy 1.16.6 <https://www.numpy.org>`_
* `Imagecodecs 2020.2.18 <https://pypi.org/project/imagecodecs/>`_
(optional; used for encoding and decoding LZW, JPEG, etc.)
* `Matplotlib 3.1 <https://www.matplotlib.org>`_ (optional; used for plotting)
Revisions
---------
2020.5.7
Pass 2907 tests.
Add napari reader plugin (tentative).
Fix writing single tiles larger than image data (#3).
Always store ExtraSamples values in tuple (breaking).
2020.5.5
Allow to write tiled TIFF from iterator of tiles (WIP).
Add function to iterate over decoded segments of TiffPage (WIP).
Pass chunks of segments to ThreadPoolExecutor.map to reduce memory usage.
Fix reading invalid files with too many strips.
Fix writing over-aligned image data.
Detect OME-XML without declaration (#2).
Support LERC compression (WIP).
Delay load imagecodecs functions.
Remove maxsize parameter from asarray (breaking).
Deprecate ijmetadata parameter from TiffWriter.save (use metadata).
2020.2.16
Add function to decode individual strips or tiles.
Read strips and tiles in order of their offsets.
Enable multi-threading when decompressing multiple strips.
Replace TiffPage.tags dictionary with TiffTags (breaking).
Replace TIFF.TAGS dictionary with TiffTagRegistry.
Remove TIFF.TAG_NAMES (breaking).
Improve handling of TiffSequence parameters in imread.
Match last uncommon parts of file paths to FileSequence pattern (breaking).
Allow letters in FileSequence pattern for indexing well plate rows.
Allow to reorder axes in FileSequence.
Allow to write > 4 GB arrays to plain TIFF when using compression.
Allow to write zero size numpy arrays to nonconformant TIFF (tentative).
Fix xml2dict.
Require imagecodecs >= 2020.1.31.
Remove support for imagecodecs-lite (breaking).
Remove verify parameter to asarray function (breaking).
Remove deprecated lzw_decode functions (breaking).
Remove support for Python 2.7 and 3.5 (breaking).
2019.7.26
Fix infinite loop reading more than two tags of same code in IFD.
Delay import of logging module.
2019.7.20
Fix OME-XML detection for files created by Imaris.
Remove or replace assert statements.
2019.7.2
Do not write SampleFormat tag for unsigned data types.
Write ByteCount tag values as SHORT or LONG if possible.
Allow to specify axes in FileSequence pattern via group names.
Add option to concurrently read FileSequence using threads.
Derive TiffSequence from FileSequence.
Use str(datetime.timedelta) to format Timer duration.
Use perf_counter for Timer if possible.
2019.6.18
Fix reading planar RGB ImageJ files created by Bio-Formats.
Fix reading single-file, multi-image OME-TIFF without UUID.
Presume LSM stores uncompressed images contiguously per page.
Reformat some complex expressions.
2019.5.30
Ignore invalid frames in OME-TIFF.
Set default subsampling to (2, 2) for RGB JPEG compression.
Fix reading and writing planar RGB JPEG compression.
Replace buffered_read with FileHandle.read_segments.
Include page or frame numbers in exceptions and warnings.
Add Timer class.
2019.5.22
Add optional chroma subsampling for JPEG compression.
Enable writing PNG, JPEG, JPEGXR, and JPEG2K compression (WIP).
Fix writing tiled images with WebP compression.
Improve handling GeoTIFF sparse files.
2019.3.18
Fix regression decoding JPEG with RGB photometrics.
Fix reading OME-TIFF files with corrupted but unused pages.
Allow to load TiffFrame without specifying keyframe.
Calculate virtual TiffFrames for non-BigTIFF ScanImage files > 2GB.
Rename property is_chroma_subsampled to is_subsampled (breaking).
Make more attributes and methods private (WIP).
2019.3.8
Fix MemoryError when RowsPerStrip > ImageLength.
Fix SyntaxWarning on Python 3.8.
Fail to decode JPEG to planar RGB (tentative).
Separate public from private test files (WIP).
Allow testing without data files or imagecodecs.
2019.2.22
Use imagecodecs-lite as a fallback for imagecodecs.
Simplify reading numpy arrays from file.
Use TiffFrames when reading arrays from page sequences.
Support slices and iterators in TiffPageSeries sequence interface.
Auto-detect uniform series.
Use page hash to determine generic series.
Turn off TiffPages cache (tentative).
Pass through more parameters in imread.
Discontinue movie parameter in imread and TiffFile (breaking).
Discontinue bigsize parameter in imwrite (breaking).
Raise TiffFileError in case of issues with TIFF structure.
Return TiffFile.ome_metadata as XML (breaking).
Ignore OME series when last dimensions are not stored in TIFF pages.
2019.2.10
Assemble IFDs in memory to speed-up writing on some slow media.
Handle discontinued arguments fastij, multifile_close, and pages.
2019.1.30
Use black background in imshow.
Do not write datetime tag by default (breaking).
Fix OME-TIFF with SamplesPerPixel > 1.
Allow 64-bit IFD offsets for NDPI (files > 4GB still not supported).
2019.1.4
Fix decoding deflate without imagecodecs.
2019.1.1
Update copyright year.
Require imagecodecs >= 2018.12.16.
Do not use JPEG tables from keyframe.
Enable decoding large JPEG in NDPI.
Decode some old-style JPEG.
Reorder OME channel axis to match PlanarConfiguration storage.
Return tiled images as contiguous arrays.
Add decode_lzw proxy function for compatibility with old czifile module.
Use dedicated logger.
2018.11.28
Make SubIFDs accessible as TiffPage.pages.
Make parsing of TiffSequence axes pattern optional (breaking).
Limit parsing of TiffSequence axes pattern to file names, not path names.
Do not interpolate in imshow if image dimensions <= 512, else use bilinear.
Use logging.warning instead of warnings.warn in many cases.
Fix numpy FutureWarning for out == 'memmap'.
Adjust ZSTD and WebP compression to libtiff-4.0.10 (WIP).
Decode old-style LZW with imagecodecs >= 2018.11.8.
Remove TiffFile.qptiff_metadata (QPI metadata are per page).
Do not use keyword arguments before variable positional arguments.
Make either all or none return statements in a function return expression.
Use pytest parametrize to generate tests.
Replace test classes with functions.
2018.11.6
Rename imsave function to imwrite.
Readd Python implementations of packints, delta, and bitorder codecs.
Fix TiffFrame.compression AttributeError.
2018.10.18
...
Refer to the CHANGES file for older revisions.
Notes
-----
The API is not stable yet and might change between revisions.
Tested on little-endian platforms only.
Python 32-bit versions are deprecated.
Update pip and setuptools to the latest version before installing tifffile:
``python -m pip install --upgrade pip setuptools``
Tifffile relies on the `imagecodecs <https://pypi.org/project/imagecodecs/>`_
package for encoding and decoding LZW, JPEG, and other compressed images.
Several TIFF-like formats do not strictly adhere to the TIFF6 specification,
some of which allow file or data sizes to exceed the 4 GB limit:
* *BigTIFF* is identified by version number 43 and uses different file
header, IFD, and tag structures with 64-bit offsets. It adds more 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 (shape and dtype) 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* stores up to 8-dimensional data in one or multiple TIFF of BigTIFF
files. The 8-bit 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 data. Tifffile can read OME-TIFF files, except when the OME-XML
metadata are stored in a separate file.
* *LSM* stores all IFDs below 4 GB but wraps around 32-bit StripOffsets.
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 large LSM files.
* *NDPI* uses some 64-bit offsets in the file header, IFD, and tag structures.
Tag values/offsets can be corrected using high bits stored after IFD
structures. JPEG compressed tiles with dimensions > 65536 are not readable
with libjpeg. Tifffile can read NDPI files < 4 GB and decompress large JPEG
tiles using the imagecodecs library on Windows.
* *ScanImage* optionally allows corrupt 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 on Python 3 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.
Other libraries for reading scientific TIFF files from Python:
* `Python-bioformats <https://github.com/CellProfiler/python-bioformats>`_
* `Imread <https://github.com/luispedro/imread>`_
* `GDAL <https://github.com/OSGeo/gdal/tree/master/gdal/swig/python>`_
* `OpenSlide-python <https://github.com/openslide/openslide-python>`_
* `PyLibTiff <https://github.com/pearu/pylibtiff>`_
* `SimpleITK <https://github.com/SimpleITK/SimpleITK>`_
* `PyLSM <https://launchpad.net/pylsm>`_
* `PyMca.TiffIO.py <https://github.com/vasole/pymca>`_ (same as fabio.TiffIO)
* `BioImageXD.Readers <http://www.bioimagexd.net/>`_
* `CellCognition <https://cellcognition-project.org/>`_
* `pymimage <https://github.com/ardoi/pymimage>`_
* `pytiff <https://github.com/FZJ-INM1-BDA/pytiff>`_
* `ScanImageTiffReaderPython
<https://gitlab.com/vidriotech/scanimagetiffreader-python>`_
* `bigtiff <https://pypi.org/project/bigtiff>`_
Some libraries are using tifffile to write OME-TIFF files:
* `Zeiss Apeer OME-TIFF library
<https://github.com/apeer-micro/apeer-ometiff-library>`_
* `Allen Institute for Cell Science imageio
<https://pypi.org/project/aicsimageio>`_
References
----------
1. TIFF 6.0 Specification and Supplements. Adobe Systems Incorporated.
https://www.adobe.io/open/standards/TIFF.html
2. TIFF File Format FAQ. https://www.awaresystems.be/imaging/tiff/faq.html
3. MetaMorph Stack (STK) Image File Format.
http://mdc.custhelp.com/app/answers/detail/a_id/18862
4. Image File Format Description LSM 5/7 Release 6.0 (ZEN 2010).
Carl Zeiss MicroImaging GmbH. BioSciences. May 10, 2011
5. The OME-TIFF format.
https://docs.openmicroscopy.org/ome-model/5.6.4/ome-tiff/
6. UltraQuant(r) Version 6.0 for Windows Start-Up Guide.
http://www.ultralum.com/images%20ultralum/pdf/UQStart%20Up%20Guide.pdf
7. Micro-Manager File Formats.
https://micro-manager.org/wiki/Micro-Manager_File_Formats
8. Tags for TIFF and Related Specifications. Digital Preservation.
https://www.loc.gov/preservation/digital/formats/content/tiff_tags.shtml
9. ScanImage BigTiff Specification - ScanImage 2016.
http://scanimage.vidriotechnologies.com/display/SI2016/
ScanImage+BigTiff+Specification
10. 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
11. ZIF, the Zoomable Image File format. http://zif.photo/
12. GeoTIFF File Format https://gdal.org/drivers/raster/gtiff.html
Examples
--------
Save a 3D numpy array to a multi-page, 16-bit grayscale TIFF file:
>>> data = numpy.random.randint(0, 2**12, (4, 301, 219), 'uint16')
>>> imwrite('temp.tif', data, photometric='minisblack')
Read the whole image stack from the TIFF file as numpy array:
>>> image_stack = imread('temp.tif')
>>> image_stack.shape
(4, 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 sequence of TIFF files as numpy array:
>>> image_sequence = imread(['temp.tif', 'temp.tif'])
>>> image_sequence.shape
(2, 4, 301, 219)
Save a numpy array to a single-page RGB TIFF file:
>>> data = numpy.random.randint(0, 255, (256, 256, 3), 'uint8')
>>> imwrite('temp.tif', data, photometric='rgb')
Save a floating-point array and metadata, using zlib compression:
>>> data = numpy.random.rand(2, 5, 3, 301, 219).astype('float32')
>>> imwrite('temp.tif', data, compress=6, metadata={'axes': 'TZCYX'})
Save a volume with xyz voxel size 2.6755x2.6755x3.9474 micron^3 to an ImageJ
formatted TIFF file:
>>> volume = numpy.random.randn(57*256*256).astype('float32')
>>> volume.shape = 1, 57, 1, 256, 256, 1 # dimensions in TZCYXS order
>>> imwrite('temp.tif', volume, imagej=True, resolution=(1./2.6755, 1./2.6755),
... metadata={'spacing': 3.947368, 'unit': 'um'})
Get the shape and dtype of the volume stored in the TIFF file:
>>> tif = TiffFile('temp.tif')
>>> len(tif.pages) # number of pages in the file
57
>>> page = tif.pages[0] # get shape and dtype of the image in the first page
>>> page.shape
(256, 256)
>>> page.dtype
dtype('float32')
>>> page.axes
'YX'
>>> series = tif.series[0] # get shape and dtype of the first image series
>>> series.shape
(57, 256, 256)
>>> series.dtype
dtype('float32')
>>> series.axes
'ZYX'
>>> tif.close()
Read hyperstack and metadata from the ImageJ file:
>>> with TiffFile('temp.tif') as tif:
... imagej_hyperstack = tif.asarray()
... imagej_metadata = tif.imagej_metadata
>>> imagej_hyperstack.shape
(57, 256, 256)
>>> imagej_metadata['slices']
57
Read 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
(2000, 5351)
>>> tag.name
'XResolution'
>>> tag.code
282
>>> tag.count
1
>>> tag.dtype
'2I'
Read images from a selected range of pages:
>>> image = imread('temp.tif', key=range(4, 40, 2))
>>> image.shape
(18, 256, 256)
Create an empty TIFF file and write to the memory-mapped numpy array:
>>> memmap_image = memmap('temp.tif', shape=(256, 256), dtype='float32')
>>> memmap_image[255, 255] = 1.0
>>> memmap_image.flush()
>>> del memmap_image
Memory-map image data of the first page in the TIFF file:
>>> memmap_image = memmap('temp.tif', page=0)
>>> memmap_image[255, 255]
1.0
>>> del memmap_image
Successively append images to a BigTIFF file, which can exceed 4 GB:
>>> data = numpy.random.randint(0, 255, (5, 2, 3, 301, 219), 'uint8')
>>> with TiffWriter('temp.tif', bigtiff=True) as tif:
... for i in range(data.shape[0]):
... tif.save(data[i], compress=6, photometric='minisblack')
Append an image to the existing TIFF file:
>>> data = numpy.random.randint(0, 255, (301, 219, 3), 'uint8')
>>> imwrite('temp.tif', data, append=True)
Iterate over pages and tags in the TIFF file and successively read images:
>>> with TiffFile('temp.tif') as tif:
... for page in tif.pages:
... for tag in page.tags:
... tag_name, tag_value = tag.name, tag.value
... image = page.asarray()
Save two image series to a TIFF file:
>>> data0 = numpy.random.randint(0, 255, (301, 219, 3), 'uint8')
>>> data1 = numpy.random.randint(0, 255, (5, 301, 219), 'uint16')
>>> with TiffWriter('temp.tif') as tif:
... tif.save(data0, compress=6, photometric='rgb')
... tif.save(data1, compress=6, photometric='minisblack', contiguous=False)
Read the second image series from the TIFF file:
>>> series1 = imread('temp.tif', series=1)
>>> series1.shape
(5, 301, 219)
Read an image stack from a series of TIFF files with a file name pattern:
>>> imwrite('temp_C001T001.tif', numpy.random.rand(64, 64))
>>> imwrite('temp_C001T002.tif', numpy.random.rand(64, 64))
>>> image_sequence = TiffSequence('temp_C001*.tif', pattern='axes')
>>> image_sequence.shape
(1, 2)
>>> image_sequence.axes
'CT'
>>> data = image_sequence.asarray()
>>> data.shape
(1, 2, 64, 64)
Create a TIFF file from an iterator of tiles:
>>> def tiles():
... data = numpy.arange(3*4*16*16, dtype='uint16').reshape((3*4, 16, 16))
... for i in range(data.shape[0]): yield data[i]
>>> imwrite('temp.tif', tiles(), dtype='uint16', shape=(48, 64), tile=(16, 16))
"""
__version__ = '2020.5.7'
__all__ = (
'imwrite',
'imread',
'imshow',
'memmap',
'lsm2bin',
'TiffFile',
'TiffFileError',
'TiffSequence',
'TiffWriter',
'TiffPage',
'TiffPageSeries',
'TiffFrame',
'TiffTag',
'TIFF',
# utility classes and functions used by oiffile, czifile, etc
'FileHandle',
'FileSequence',
'Timer',
'lazyattr',
'natural_sorted',
'stripnull',
'transpose_axes',
'squeeze_axes',
'create_output',
'repeat_nd',
'format_size',
'astype',
'product',
'xml2dict',
'pformat',
'nullfunc',
'update_kwargs',
'parse_kwargs',
'askopenfilename',
'_app_show',
# deprecated
'imsave',
)
import sys
import os
import io
import re
import glob
import math
import time
import json
import enum
import struct
import pathlib
import warnings
import binascii
import datetime
import threading
import collections
from collections.abc import Iterable
from concurrent.futures import ThreadPoolExecutor
import numpy
try:
import imagecodecs
except Exception:
imagecodecs = None
# delay import of mmap, pprint, fractions, xml, lxml, matplotlib, tkinter,
# logging, subprocess, multiprocessing, tempfile, zipfile, fnmatch
def imread(files, **kwargs):
"""Return image data from TIFF file(s) as numpy array.
Refer to the TiffFile and TiffSequence classes and their asarray
functions for documentation.
Parameters
----------
files : str, binary stream, or sequence
File name, seekable binary stream, glob pattern, or sequence of
file names.
kwargs : dict
Parameters 'name', 'offset', 'size', 'multifile', and 'is_ome'
are passed to TiffFile().
The 'pattern', 'sort', 'container', and 'axesorder' parameters are
passed to TiffSequence().
Other parameters are passed to the asarray functions.
The first image series in the file is returned if no arguments are
provided.
"""
kwargs_file = parse_kwargs(
kwargs,
'is_ome',
'multifile',
'_useframes',
'name',
'offset',
'size',
# legacy
'multifile_close',
'fastij',
'movie',
)
kwargs_seq = parse_kwargs(kwargs, 'pattern', 'sort', 'container', 'imread',
'axesorder')
if kwargs.get('pages', None) is not None:
if kwargs.get('key', None) is not None:
raise TypeError(
"the 'pages' and 'key' arguments cannot be used together"
)
warnings.warn(
"imread: the 'pages' argument is deprecated", DeprecationWarning
)
kwargs['key'] = kwargs.pop('pages')
if not kwargs_seq:
if isinstance(files, str) and any(i in files for i in '?*'):
files = glob.glob(files)
if not files:
raise ValueError('no files found')
if not hasattr(files, 'seek') and len(files) == 1:
files = files[0]
if isinstance(files, str) or hasattr(files, 'seek'):
with TiffFile(files, **kwargs_file) as tif:
return tif.asarray(**kwargs)
with TiffSequence(files, **kwargs_seq) as imseq:
return imseq.asarray(**kwargs)
def imwrite(file, data=None, shape=None, dtype=None, **kwargs):
"""Write numpy array to TIFF file.
Refer to the TiffWriter class and its asarray function for documentation.
A BigTIFF file is created if the data size in bytes is larger than 4 GB
minus 32 MB (for metadata), and 'bigtiff' is not specified, and 'imagej'
or 'truncate' are not enabled.
Parameters
----------
file : str or binary stream
File name or writable binary stream, such as an open file or BytesIO.
data : array_like
Input image. The last dimensions are assumed to be image depth,
height, width, and samples.
If None, an empty array of the specified shape and dtype is
saved to file.
Unless 'byteorder' is specified in 'kwargs', the TIFF file byte order
is determined from the data's dtype or the dtype argument.
shape : tuple
If 'data' is None, shape of an empty array to save to the file.
dtype : numpy.dtype
If 'data' is None, datatype of an empty array to save to the file.
kwargs : dict
Parameters 'append', 'byteorder', 'bigtiff', and 'imagej', are passed
to TiffWriter(). Other parameters are passed to TiffWriter.save().
Returns
-------
offset, bytecount : tuple or None
If the image data are written contiguously, return offset and bytecount
of image data in the file.
"""
tifargs = parse_kwargs(kwargs, 'append', 'bigtiff', 'byteorder', 'imagej')
if data is None:
dtype = numpy.dtype(dtype)
size = product(shape) * dtype.itemsize
byteorder = dtype.byteorder
else:
try:
size = data.nbytes
byteorder = data.dtype.byteorder
except Exception:
size = 0
byteorder = None
bigsize = kwargs.pop('bigsize', 2**32 - 2**25)
if (
'bigtiff' not in tifargs
and size > bigsize
and not tifargs.get('imagej', False)
and not tifargs.get('truncate', False)
and not kwargs.get('compress', False)
):
tifargs['bigtiff'] = True
if 'byteorder' not in tifargs:
tifargs['byteorder'] = byteorder
with TiffWriter(file, **tifargs) as tif:
return tif.save(data, shape, dtype, **kwargs)
def memmap(filename, shape=None, dtype=None, page=None, series=0, mode='r+',
**kwargs):
"""Return memory-mapped numpy array stored in TIFF file.
Memory-mapping requires data stored in native byte order, without tiling,
compression, predictors, etc.
If 'shape' and 'dtype' are provided, existing files will be overwritten or
appended to depending on the 'append' parameter.
Otherwise the image data of a specified page or series in an existing
file will be memory-mapped. By default, the image data of the first page
series is memory-mapped.
Call flush() to write any changes in the array to the file.
Raise ValueError if the image data in the file is not memory-mappable.
Parameters
----------
filename : str
Name of the TIFF file which stores the array.
shape : tuple
Shape of the empty array.
dtype : numpy.dtype
Datatype of the empty array.
page : int
Index of the page which image data to memory-map.
series : int
Index of the page series which image data to memory-map.
mode : {'r+', 'r', 'c'}
The file open mode. Default is to open existing file for reading and
writing ('r+').
kwargs : dict
Additional parameters passed to imwrite() or TiffFile().
"""
if shape is not None and dtype is not None:
# create a new, empty array
kwargs.update(
data=None,
shape=shape,
dtype=dtype,
returnoffset=True,
align=TIFF.ALLOCATIONGRANULARITY
)
result = imwrite(filename, **kwargs)
if result is None:
# TODO: fail before creating file or writing data
raise ValueError('image data are not memory-mappable')
offset = result[0]
else:
# use existing file
with TiffFile(filename, **kwargs) as tif:
if page is not None:
page = tif.pages[page]
if not page.is_memmappable:
raise ValueError('image data are not memory-mappable')
offset, _ = page.is_contiguous
shape = page.shape
dtype = page.dtype
else:
series = tif.series[series]
if series.offset is None:
raise ValueError('image data are not memory-mappable')
shape = series.shape
dtype = series.dtype
offset = series.offset
dtype = tif.byteorder + dtype.char
return numpy.memmap(filename, dtype, mode, offset, shape, 'C')
class lazyattr:
"""Attribute whose value is computed on first access."""
# TODO: help() doesn't work
__slots__ = ('func',)
def __init__(self, func):
self.func = func
# self.__name__ = func.__name__
# self.__doc__ = func.__doc__
# self.lock = threading.RLock()
def __get__(self, instance, owner):
# with self.lock:
if instance is None:
return self
try:
value = self.func(instance)
except AttributeError as exc:
raise RuntimeError(exc)
if value is NotImplemented:
return getattr(super(owner, instance), self.func.__name__)
setattr(instance, self.func.__name__, value)
return value
class TiffFileError(Exception):
"""Exception to indicate invalid TIFF structure."""
class TiffWriter:
"""Write numpy arrays to TIFF file.
TiffWriter instances must be closed using the 'close' method, which is
automatically called when using the 'with' context manager.
TiffWriter instances are not thread-safe.
TiffWriter's main purpose is saving nD numpy array's as TIFF,
not to create any possible TIFF format. Specifically, SubIFDs, ExifIFD,
and GPSIFD tags are not supported.
"""
def __init__(self, file, bigtiff=False, byteorder=None, append=False,
imagej=False):
"""Open a TIFF file for writing.
An empty TIFF file is created if the file does not exist, else the
file is overwritten with an empty TIFF file unless 'append'
is true. Use 'bigtiff=True' when creating files larger than 4 GB.
Parameters
----------
file : str, binary stream, or FileHandle
File name or writable binary stream, such as an open file
or BytesIO.
bigtiff : bool
If True, the BigTIFF format is used.
byteorder : {'<', '>', '=', '|'}
The endianness of the data in the file.
By default, this is the system's native byte order.
append : bool
If True and 'file' is an existing standard TIFF file, image data
and tags are appended to the file.
Appending data may corrupt specifically formatted TIFF files
such as LSM, STK, ImageJ, or FluoView.
imagej : bool
If True, write an ImageJ hyperstack compatible file.
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.
When using compression, use ImageJ's Bio-Formats import function.
"""
if append:
# determine if file is an existing TIFF file that can be extended
try:
with FileHandle(file, mode='rb', size=0) as fh:
pos = fh.tell()
try:
with TiffFile(fh) as tif:
if append != 'force' and not tif.is_appendable:
raise TiffFileError('cannot append to file'
' containing metadata')
byteorder = tif.byteorder
bigtiff = tif.is_bigtiff
self._ifdoffset = tif.pages.next_page_offset
finally:
fh.seek(pos)
except (OSError, FileNotFoundError):
append = False
if byteorder in (None, '=', '|'):
byteorder = '<' if sys.byteorder == 'little' else '>'
elif byteorder not in ('<', '>'):
raise ValueError(f'invalid byteorder {byteorder}')
if imagej and bigtiff:
warnings.warn('writing nonconformant BigTIFF ImageJ', UserWarning)
self._byteorder = byteorder
self._imagej = bool(imagej)
self._truncate = False
self._metadata = None
self._colormap = None
self._descriptionoffset = 0
self._descriptionlen = 0
self._descriptionlenoffset = 0
self._tags = None
self._shape = None # normalized shape of data in consecutive pages
self._datashape = None # shape of data in consecutive pages
self._datadtype = None # data type
self._dataoffset = None # offset to data
self._databytecounts = None # byte counts per plane
self._tagoffsets = None # strip or tile offset tag code
if bigtiff:
self._bigtiff = True
self._offsetsize = 8
self._tagsize = 20
self._tagnoformat = 'Q'
self._offsetformat = 'Q'
self._valueformat = '8s'
else:
self._bigtiff = False
self._offsetsize = 4
self._tagsize = 12
self._tagnoformat = 'H'
self._offsetformat = 'I'
self._valueformat = '4s'
if append:
self._fh = FileHandle(file, mode='r+b', size=0)
self._fh.seek(0, 2)
else:
self._fh = FileHandle(file, mode='wb', size=0)
self._fh.write({'<': b'II', '>': b'MM'}[byteorder])
if bigtiff:
self._fh.write(struct.pack(byteorder + 'HHH', 43, 8, 0))
else:
self._fh.write(struct.pack(byteorder + 'H', 42))
# first IFD
self._ifdoffset = self._fh.tell()
self._fh.write(struct.pack(byteorder + self._offsetformat, 0))
def save(self, data=None, shape=None, dtype=None, returnoffset=False,
photometric=None, planarconfig=None, extrasamples=None, tile=None,
contiguous=True, align=16, truncate=False, compress=None,
rowsperstrip=None, predictor=False, subsampling=None,
colormap=None, description=None, datetime=None, resolution=None,
subfiletype=0, software='tifffile.py', metadata={},
ijmetadata=None, extratags=()):
"""Write numpy array and tags to TIFF file.
The data shape's last dimensions are assumed to be image depth,
height (length), width, and samples.
If a colormap is provided, the data's dtype must be uint8 or uint16
and the data values are indices into the last dimension of the
colormap.
If 'shape' and 'dtype' are specified instead of 'data', an empty array
is saved. This option cannot be used with compression or multiple
tiles.
If 'shape', 'dtype', and 'tile' are specified, 'data' must be a
sequence or iterator over all individual tiles in image.
Image data are written uncompressed in one strip per plane by default.
Dimensions larger than 2 to 4 (depending on photometric mode, planar
configuration, and SGI mode) are flattened and saved as separate pages.
If the data size is zero, a single page with shape (0, 0) is saved.
The SampleFormat and BitsPerSample tags are derived from the data type.
Parameters
----------
data : numpy.ndarray, sequence of numpy.ndarray, or None
Input image or tiles.
shape : tuple or None
Shape of the empty or tiled array to save.
Used only if 'data' is None or a sequence of tiles.
dtype : numpy.dtype or None
Datatype of the empty or tiled array to save.
Used only if 'data' is None or a sequence of tiles.
returnoffset : bool
If True and the image data in the file is memory-mappable, return
the offset and number of bytes of the image data in the file.
photometric : {'MINISBLACK', 'MINISWHITE', 'RGB', 'PALETTE', 'CFA'}
The color space of the image data according to TIFF.PHOTOMETRIC.
By default, this setting is inferred from the data shape and the
value of colormap.
For CFA images, DNG tags must be specified in 'extratags'.
planarconfig : {'CONTIG', 'SEPARATE'}
Specifies if samples are stored interleaved or in separate planes.
By default, this setting is inferred from the data shape.
If this parameter is set, extra samples are used to store grayscale
images.
'CONTIG': last dimension contains samples.
'SEPARATE': third last dimension contains samples.
extrasamples : tuple of {'UNSPECIFIED', 'ASSOCALPHA', 'UNASSALPHA'}
Defines the interpretation of extra components in pixels.
'UNSPECIFIED': no transparency information (default).
'ASSOCALPHA': single, true transparency with pre-multiplied color.
'UNASSALPHA': independent transparency masks.
tile : tuple of int
The shape ([depth,] length, width) of image tiles to write.
If None (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 save volume data.
Tiles cannot be used to write contiguous files, except if tile
matches the data shape.
Few software can read the SGI format, e.g. MeVisLab.
contiguous : bool
If True (default) and the data and parameters are compatible with
previous ones, if any, the image data are stored contiguously after
the previous one. In that case, 'photometric', 'planarconfig',
'rowsperstrip', are ignored. Metadata such as 'description',
'metadata', 'datetime', and 'extratags' are written to the first
page of a contiguous series only.
align : int
Byte boundary on which to align the image data in the file.
Default 16. Use mmap.ALLOCATIONGRANULARITY for memory-mapped data.
Following contiguous writes are not aligned.
truncate : bool
If True, only write the first page including shape metadata if
possible (uncompressed, contiguous, not tiled).
Other TIFF readers will only be able to read part of the data.
compress : int, str, or (str, int)
If 0 or None (default), data are written uncompressed.
If 0-9, the level of ADOBE_DEFLATE compression.
If a str, one of TIFF.COMPESSORS, e.g. 'LZMA' or 'ZSTD'.
If a tuple, the first item is one of TIFF.COMPESSORS and the
second item is the compression level.
Compression cannot be used to write contiguous files.
Compressors may require certain data shapes, types or value ranges.
For example, JPEG requires grayscale or RGB(A), uint8 or 12-bit
uint16. JPEG compression is experimental. JPEG markers and TIFF
tags may not match.
rowsperstrip : int
The number of rows per strip. By default, strips will be ~64 KB
if compression is enabled, else rowsperstrip is set to the image
length. Bilevel images are always stored in one strip per plane.
predictor : bool