-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtiffparser.py
8552 lines (7581 loc) · 281 KB
/
tiffparser.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
# tiffparser.py
# All modifications: Copyright (c) 2020, Thomas Pearce
# All rights reserved
# Modified from, with copyright info and license intact:
# 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 TIFF(r) file (meta)data.
Data 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.
:Author:
`Christoph Gohlke <https://www.lfd.uci.edu/~gohlke/>`_
:Organization:
Laboratory for Fluorescence Dynamics, University of California, Irvine
:License: BSD 3-Clause
:Version: 2020.2.16
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
"""
__version__ = '0.1'
import os
import sys
import pathlib
import struct
import enum
import datetime
# use tinynumpy instead to minimize build size
import tinynumpy as numpy
# import numpy
itemsizes={'<B': 1,
'>B': 1,
'<b1': 1,
'>b1': 1,
'B': 1,
'b1': 1,
'bool': 1,
'<b': 1,
'>b': 1,
'<i1': 1,
'>i1': 1,
'b': 1,
'i1': 1,
'int8': 1,
'<u1': 1,
'>u1': 1,
'u1': 1,
'uint8': 1,
'<h': 2,
'>h': 2,
'<i2': 2,
'>i2': 2,
'h': 2,
'i2': 2,
'int16': 2,
'<H': 2,
'>H': 2,
'<u2': 2,
'>u2': 2,
'H': 2,
'u2': 2,
'uint16': 2,
'<i': 4,
'>i': 4,
'<i4': 4,
'>i4': 4,
'i': 4,
'i4': 4,
'int32': 4,
'<I': 4,
'>I': 4,
'<u4': 4,
'>u4': 4,
'I': 4,
'u4': 4,
'uint32': 4,
'<q': 8,
'>q': 8,
'<i8': 8,
'>i8': 8,
'q': 8,
'i8': 8,
'int64': 8,
'<Q': 8,
'>Q': 8,
'<u8': 8,
'>u8': 8,
'Q': 8,
'u8': 8,
'uint64': 8,
'<f': 4,
'>f': 4,
'<f4': 4,
'>f4': 4,
'f': 4,
'f4': 4,
'float32': 4,
'<d': 8,
'>d': 8,
'<f8': 8,
'>f8': 8,
'd': 8,
'f8': 8,
'float64': 8}
class dtype(object):
def __init__(self,s):
self.itemsize=itemsizes[s];
def getdtype(d):
return dtype(d)
# Hack: replace minimum functionality of numpy.dtype, which is only used for looking up bytes per object
numpy.dtype = getdtype
numpy.integer = False
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 TiffParserError(Exception):
"""Exception to indicate parser functionality exceeded"""
class TiffFile:
"""Read image and metadata from TIFF file.
TiffFile instances must be closed using the 'close' method, which is
automatically called when using the 'with' context manager.
TiffFile instances are not thread-safe.
Attributes
----------
pages : TiffPages
Sequence of TIFF pages in file.
series : list of TiffPageSeries
Sequences of closely related TIFF pages. These are computed
from OME, LSM, ImageJ, etc. metadata or based on similarity
of page properties such as shape, dtype, and compression.
is_flag : bool
If True, file is of a certain format.
Flags are: bigtiff, uniform, shaped, ome, imagej, stk, lsm, fluoview,
nih, vista, micromanager, metaseries, mdgel, mediacy, tvips, fei,
sem, scn, svs, scanimage, andor, epics, ndpi, pilatus, qpi.
All attributes are read-only.
"""
def __init__(self, arg, name=None, offset=None, size=None, multifile=True,
_useframes=None, **kwargs):
"""Initialize instance from file.
Parameters
----------
arg : str or open file
Name of file or open file object.
The file objects are closed in TiffFile.close().
name : str
Optional name of file in case 'arg' is a file handle.
offset : int
Optional start position of embedded file. By default, this is
the current file position.
size : int
Optional size of embedded file. By default, this is the number
of bytes from the 'offset' to the end of the file.
multifile : bool
If True (default), series may include pages from multiple files.
Currently applies to OME-TIFF only.
kwargs : bool
'is_ome': If False, disable processing of OME-XML metadata.
"""
if kwargs:
for key in ('movie', 'fastij', 'multifile_close'):
if key in kwargs:
del kwargs[key]
log_warning(f'TiffFile: the {key!r} argument is ignored')
if 'pages' in kwargs:
raise TypeError(
"the TiffFile 'pages' argument is no longer supported.\n\n"
"Use TiffFile.asarray(key=[...]) to read image data "
"from specific pages.\n")
for key, value in kwargs.items():
if key[:3] == 'is_' and key[3:] in TIFF.FILE_FLAGS:
if value is not None and not value:
setattr(self, key, bool(value))
else:
raise TypeError(f'unexpected keyword argument: {key}')
fh = FileHandle(arg, mode='rb', name=name, offset=offset, size=size)
self._fh = fh
self._multifile = bool(multifile)
self._files = {fh.name: self} # cache of TiffFiles
self._decoders = {} # cache of TiffPage.decode functions
try:
fh.seek(0)
header = fh.read(4)
try:
byteorder = {b'II': '<', b'MM': '>', b'EP': '<'}[header[:2]]
except KeyError:
raise TiffFileError('not a TIFF file')
version = struct.unpack(byteorder + 'H', header[2:4])[0]
if version == 43:
# BigTiff
offsetsize, zero = struct.unpack(byteorder + 'HH', fh.read(4))
if zero != 0 or offsetsize != 8:
raise TiffFileError('invalid BigTIFF file')
if byteorder == '>':
self.tiff = TIFF.BIG_BE
else:
self.tiff = TIFF.BIG_LE
elif version == 42:
# Classic TIFF
if byteorder == '>':
self.tiff = TIFF.CLASSIC_BE
elif kwargs.get('is_ndpi', False):
# NDPI uses 64 bit IFD offsets
# TODO: fix offsets in NDPI tags if file size > 4 GB
self.tiff = TIFF.NDPI_LE
else:
self.tiff = TIFF.CLASSIC_LE
else:
raise TiffFileError('invalid TIFF file')
# file handle is at offset to offset to first page
self.pages = TiffPages(self)
if self.is_lsm and (
self.filehandle.size >= 2**32
or self.pages[0].compression != 1
or self.pages[1].compression != 1
):
self._lsm_load_pages()
elif self.is_scanimage and (
not self.is_bigtiff and self.filehandle.size >= 2**31
):
self.pages._load_virtual_frames()
elif _useframes:
self.pages.useframes = True
except Exception:
fh.close()
raise
@property
def byteorder(self):
return self.tiff.byteorder
@property
def is_bigtiff(self):
return self.tiff.version == 43
@property
def filehandle(self):
"""Return file handle."""
return self._fh
@property
def filename(self):
"""Return name of file handle."""
return self._fh.name
@lazyattr
def fstat(self):
"""Return status of file handle as stat_result object."""
try:
return os.fstat(self._fh.fileno())
except Exception: # io.UnsupportedOperation
return None
def close(self):
"""Close open file handle(s)."""
for tif in self._files.values():
tif.filehandle.close()
self._files = {}
def asarray(self, key=None, series=None, out=None, maxworkers=None):
raise TiffParserError('TiffParser does not support reading image data')
@lazyattr
def series(self):
"""Return related pages as TiffPageSeries.
Side effect: after calling this function, TiffFile.pages might contain
TiffPage and TiffFrame instances.
"""
if not self.pages:
return []
useframes = self.pages.useframes
keyframe = self.pages.keyframe.index
series = []
for name in (
'lsm',
'ome',
'imagej',
'shaped',
'fluoview',
'sis',
'uniform',
'mdgel',
):
if getattr(self, 'is_' + name, False):
series = getattr(self, '_series_' + name)()
break
self.pages.useframes = useframes
self.pages.keyframe = keyframe
if not series:
series = self._series_generic()
# remove empty series, e.g. in MD Gel files
# series = [s for s in series if product(s.shape) > 0]
for i, s in enumerate(series):
s.index = i
return series
def _series_generic(self):
"""Return image series in file.
A series is a sequence of TiffPages with the same hash.
"""
pages = self.pages
pages._clear(False)
pages.useframes = False
if pages.cache:
pages._load()
result = []
keys = []
series = {}
for page in pages:
if not page.shape: # or product(page.shape) == 0:
continue
key = page.hash
if key in series:
series[key].append(page)
else:
keys.append(key)
series[key] = [page]
for key in keys:
pages = series[key]
page = pages[0]
shape = page.shape
axes = page.axes
if len(pages) > 1:
shape = (len(pages),) + shape
axes = 'I' + axes
result.append(
TiffPageSeries(pages, shape, page.dtype, axes, kind='Generic')
)
self.is_uniform = len(result) == 1
return result
def _series_uniform(self):
"""Return all images in file as single series."""
page = self.pages[0]
shape = page.shape
axes = page.axes
dtype = page.dtype
validate = not (page.is_scanimage or page.is_nih)
pages = self.pages._getlist(validate=validate)
lenpages = len(pages)
if lenpages > 1:
shape = (lenpages,) + shape
axes = 'I' + axes
if page.is_scanimage:
kind = 'ScanImage'
elif page.is_nih:
kind = 'NIHImage'
else:
kind = 'Uniform'
return [TiffPageSeries(pages, shape, dtype, axes, kind=kind)]
def _series_shaped(self):
"""Return image series in "shaped" file."""
pages = self.pages
pages.useframes = True
lenpages = len(pages)
def append(series, pages, axes, shape, reshape, name, truncated):
# append TiffPageSeries to series
page = pages[0]
if not axes:
shape = page.shape
axes = page.axes
if len(pages) > 1:
shape = (len(pages),) + shape
axes = 'Q' + axes
size = product(shape)
resize = product(reshape)
if page.is_contiguous and resize > size and resize % size == 0:
if truncated is None:
truncated = True
axes = 'Q' + axes
shape = (resize // size,) + shape
try:
axes = reshape_axes(axes, shape, reshape)
shape = reshape
except ValueError as exc:
log_warning(
f'Shaped series: {exc.__class__.__name__}: {exc}'
)
series.append(
TiffPageSeries(pages, shape, page.dtype, axes,
name=name, kind='Shaped', truncated=truncated)
)
keyframe = axes = shape = reshape = name = None
series = []
index = 0
while True:
if index >= lenpages:
break
# new keyframe; start of new series
pages.keyframe = index
keyframe = pages.keyframe
if not keyframe.is_shaped:
log_warning(
'Shaped series: invalid metadata or corrupted file')
return None
# read metadata
axes = None
shape = None
metadata = json_description_metadata(keyframe.is_shaped)
name = metadata.get('name', '')
reshape = metadata['shape']
truncated = metadata.get('truncated', None)
if 'axes' in metadata:
axes = metadata['axes']
if len(axes) == len(reshape):
shape = reshape
else:
axes = ''
log_warning('Shaped series: axes do not match shape')
# skip pages if possible
spages = [keyframe]
size = product(reshape)
if size > 0:
npages, mod = divmod(size, product(keyframe.shape))
else:
npages = 1
mod = 0
if mod:
log_warning(
'Shaped series: series shape does not match page shape')
return None
if 1 < npages <= lenpages - index:
size *= keyframe._dtype.itemsize
if truncated:
npages = 1
elif (
keyframe.is_final
and keyframe.offset + size < pages[index + 1].offset
):
truncated = False
else:
# need to read all pages for series
truncated = False
for j in range(index + 1, index + npages):
page = pages[j]
page.keyframe = keyframe
spages.append(page)
append(series, spages, axes, shape, reshape, name, truncated)
index += npages
self.is_uniform = len(series) == 1
return series
def _series_imagej(self):
"""Return image series in ImageJ file."""
# ImageJ's dimension order is always TZCYXS
# TODO: fix loading of color, composite, or palette images
pages = self.pages
pages.useframes = True
pages.keyframe = 0
page = pages[0]
ij = self.imagej_metadata
def is_virtual():
# ImageJ virtual hyperstacks store all image metadata in the first
# page and image data are stored contiguously before the second
# page, if any
if not page.is_final:
return False
images = ij.get('images', 0)
if images <= 1:
return False
offset, count = page.is_contiguous
if (
count != product(page.shape) * page.bitspersample // 8
or offset + count * images > self.filehandle.size
):
raise ValueError()
# check that next page is stored after data
if len(pages) > 1 and offset + count * images > pages[1].offset:
return False
return True
try:
isvirtual = is_virtual()
except ValueError:
log_warning('ImageJ series: invalid metadata or corrupted file')
return None
if isvirtual:
# no need to read other pages
pages = [page]
else:
pages = pages[:]
images = ij.get('images', len(pages))
frames = ij.get('frames', 1)
slices = ij.get('slices', 1)
channels = ij.get('channels', 1)
mode = ij.get('mode', None)
shape = []
axes = []
if frames > 1:
shape.append(frames)
axes.append('T')
if slices > 1:
shape.append(slices)
axes.append('Z')
if channels > 1 and (page.photometric != 2 or mode != 'composite'):
shape.append(channels)
axes.append('C')
remain = images // (product(shape) if shape else 1)
if remain > 1:
shape.append(remain)
axes.append('I')
if page.axes[0] == 'S' and 'C' in axes:
# planar storage, S == C, saved by Bio-Formats
shape.extend(page.shape[1:])
axes.extend(page.axes[1:])
elif page.axes[0] == 'I':
# contiguous multiple images
shape.extend(page.shape[1:])
axes.extend(page.axes[1:])
elif page.axes[:2] == 'SI':
# color-mapped contiguous multiple images
shape = page.shape[0:1] + tuple(shape) + page.shape[2:]
axes = list(page.axes[0]) + axes + list(page.axes[2:])
else:
shape.extend(page.shape)
axes.extend(page.axes)
truncated = (
isvirtual
and len(self.pages) == 1
and page.is_contiguous[1] != (
product(shape) * page.bitspersample // 8)
)
self.is_uniform = True
return [
TiffPageSeries(pages, shape, page.dtype, axes,
kind='ImageJ', truncated=truncated)
]
def _series_fluoview(self):
"""Return image series in FluoView file."""
pages = self.pages._getlist(validate=False)
mm = self.fluoview_metadata
mmhd = list(reversed(mm['Dimensions']))
axes = ''.join(TIFF.MM_DIMENSIONS.get(i[0].upper(), 'Q')
for i in mmhd if i[1] > 1)
shape = tuple(int(i[1]) for i in mmhd if i[1] > 1)
self.is_uniform = True
return [
TiffPageSeries(pages, shape, pages[0].dtype, axes,
name=mm['ImageName'], kind='FluoView')
]
def _series_mdgel(self):
"""Return image series in MD Gel file."""
# only a single page, scaled according to metadata in second page
self.pages.useframes = False
self.pages.keyframe = 0
md = self.mdgel_metadata
if md['FileTag'] in (2, 128):
dtype = numpy.dtype('float32')
scale = md['ScalePixel']
scale = scale[0] / scale[1] # rational
if md['FileTag'] == 2:
# squary root data format
def transform(a):
return a.astype('float32')**2 * scale
else:
def transform(a):
return a.astype('float32') * scale
else:
transform = None
page = self.pages[0]
self.is_uniform = False
return [
TiffPageSeries([page], page.shape, dtype, page.axes,
transform=transform, kind='MDGel')
]
def _series_sis(self):
"""Return image series in Olympus SIS file."""
pages = self.pages._getlist(validate=False)
page = pages[0]
lenpages = len(pages)
md = self.sis_metadata
if 'shape' in md and 'axes' in md:
shape = md['shape'] + page.shape
axes = md['axes'] + page.axes
elif lenpages == 1:
shape = page.shape
axes = page.axes
else:
shape = (lenpages,) + page.shape
axes = 'I' + page.axes
self.is_uniform = True
return [
TiffPageSeries(pages, shape, page.dtype, axes, kind='SIS')
]
def _series_ome(self):
"""Return image series in OME-TIFF file(s)."""
from xml.etree import cElementTree as etree # delayed import
omexml = self.pages[0].description
try:
root = etree.fromstring(omexml)
except etree.ParseError as exc:
# TODO: test badly encoded OME-XML
log_warning(f'OME series: {exc.__class__.__name__}: {exc}')
try:
omexml = omexml.decode(errors='ignore').encode()
root = etree.fromstring(omexml)
except Exception:
return None
self.pages.cache = True
self.pages.useframes = True
self.pages.keyframe = 0
self.pages._load(keyframe=None)
root_uuid = root.attrib.get('UUID', None)
self._files = {root_uuid: self}
dirname = self._fh.dirname
modulo = {}
series = []
for element in root:
if element.tag.endswith('BinaryOnly'):
# TODO: load OME-XML from master or companion file
log_warning('OME series: not an ome-tiff master file')
break
if element.tag.endswith('StructuredAnnotations'):
for annot in element:
if not annot.attrib.get('Namespace',
'').endswith('modulo'):
continue
for value in annot:
for modul in value:
for along in modul:
if not along.tag[:-1].endswith('Along'):
continue
axis = along.tag[-1]
newaxis = along.attrib.get('Type', 'other')
newaxis = TIFF.AXES_LABELS[newaxis]
if 'Start' in along.attrib:
step = float(along.attrib.get('Step', 1))
start = float(along.attrib['Start'])
stop = float(along.attrib['End']) + step
labels = numpy.arange(start, stop, step)
else:
labels = [
label.text
for label in along
if label.tag.endswith('Label')
]
modulo[axis] = (newaxis, labels)
if not element.tag.endswith('Image'):
continue
attr = element.attrib
name = attr.get('Name', None)
for pixels in element:
if not pixels.tag.endswith('Pixels'):
continue
attr = pixels.attrib
# dtype = attr.get('PixelType', None)
axes = ''.join(reversed(attr['DimensionOrder']))
shape = idxshape = [int(attr['Size' + ax]) for ax in axes]
size = product(shape[:-2])
ifds = None
spp = 1 # samples per pixel
for data in pixels:
if data.tag.endswith('Channel'):
attr = data.attrib
if ifds is None:
spp = int(attr.get('SamplesPerPixel', spp))
ifds = [None] * (size // spp)
if spp > 1:
# correct channel dimension for spp
idxshape = [
shape[i] // spp if ax == 'C' else shape[i]
for i, ax in enumerate(axes)]
elif int(attr.get('SamplesPerPixel', 1)) != spp:
raise ValueError('OME series: cannot handle '
'differing SamplesPerPixel')
continue
if ifds is None:
ifds = [None] * (size // spp)
if not data.tag.endswith('TiffData'):
continue
attr = data.attrib
ifd = int(attr.get('IFD', 0))
num = int(attr.get('NumPlanes', 1 if 'IFD' in attr else 0))
num = int(attr.get('PlaneCount', num))
idx = [int(attr.get('First' + ax, 0)) for ax in axes[:-2]]
try:
raise TiffParserError('series_ome is not supported by TiffParser')
# idx = numpy.ravel_multi_index(idx, idxshape[:-2])
except ValueError:
# ImageJ produces invalid ome-xml when cropping
log_warning('OME series: invalid TiffData index')
continue
for uuid in data:
if not uuid.tag.endswith('UUID'):
continue
if root_uuid is None and uuid.text is not None:
# no global UUID, use this file
root_uuid = uuid.text
self._files[root_uuid] = self._files[None]
elif uuid.text not in self._files:
if not self._multifile:
# abort reading multifile OME series
# and fall back to generic series
return []
fname = uuid.attrib['FileName']
try:
tif = TiffFile(os.path.join(dirname, fname))
tif.pages.cache = True
tif.pages.useframes = True
tif.pages.keyframe = 0
tif.pages._load(keyframe=None)
except (OSError, FileNotFoundError, ValueError):
log_warning(
f'OME series: failed to read {fname!r}')
break
self._files[uuid.text] = tif
tif.close()
pages = self._files[uuid.text].pages
try:
for i in range(num if num else len(pages)):
ifds[idx + i] = pages[ifd + i]
except IndexError:
log_warning('OME series: index out of range')
# only process first UUID
break
else:
pages = self.pages
try:
for i in range(num if num else
min(len(pages), len(ifds))):
ifds[idx + i] = pages[ifd + i]
except IndexError:
log_warning('OME series: index out of range')
if all(i is None for i in ifds):
# skip images without data
continue
# find a keyframe
keyframe = None
for i in ifds:
# try find a TiffPage
if i and i == i.keyframe:
keyframe = i
break
if keyframe is None:
# reload a TiffPage from file
for i, keyframe in enumerate(ifds):
if keyframe:
keyframe.parent.pages.keyframe = keyframe.index
keyframe = keyframe.parent.pages[keyframe.index]
ifds[i] = keyframe
break
# move channel axis to match PlanarConfiguration storage
# TODO: is this a bug or a inconsistency in the OME spec?
if spp > 1:
if keyframe.planarconfig == 1 and axes[-1] != 'C':
i = axes.index('C')
axes = axes[:i] + axes[i + 1:] + axes[i: i + 1]
shape = shape[:i] + shape[i + 1:] + shape[i: i + 1]
# FIXME: this implementation assumes the last dimensions are
# stored in TIFF pages. Apparently that is not always the case.
# For now, verify that shapes of keyframe and series match
# If not, skip series.
if keyframe.shape != tuple(shape[-len(keyframe.shape):]):
log_warning(
'OME series: incompatible page shape %s; expected %s',
keyframe.shape,
tuple(shape[-len(keyframe.shape):])
)
del ifds
continue
# set a keyframe on all IFDs
for i in ifds:
if i is not None:
try:
i.keyframe = keyframe
except RuntimeError as exc:
log_warning(f'OME series: {exc}')
series.append(
TiffPageSeries(ifds, shape, keyframe.dtype, axes,
parent=self, name=name, kind='OME')
)
del ifds
for serie in series:
shape = list(serie.shape)
for axis, (newaxis, labels) in modulo.items():
i = serie.axes.index(axis)
size = len(labels)
if shape[i] == size:
serie.axes = serie.axes.replace(axis, newaxis, 1)
else:
shape[i] //= size
shape.insert(i + 1, size)
serie.axes = serie.axes.replace(axis, axis + newaxis, 1)
serie.shape = tuple(shape)
# squeeze dimensions
for serie in series:
serie.shape, serie.axes = squeeze_axes(serie.shape, serie.axes)
self.is_uniform = len(series) == 1
return series
def _series_lsm(self):
"""Return main and thumbnail series in LSM file."""
lsmi = self.lsm_metadata
axes = TIFF.CZ_LSMINFO_SCANTYPE[lsmi['ScanType']]
if self.pages[0].photometric == 2: # RGB; more than one channel
axes = axes.replace('C', '').replace('XY', 'XYC')
if lsmi.get('DimensionP', 0) > 1:
axes += 'P'
if lsmi.get('DimensionM', 0) > 1:
axes += 'M'
axes = axes[::-1]
shape = tuple(int(lsmi[TIFF.CZ_LSMINFO_DIMENSIONS[i]]) for i in axes)
name = lsmi.get('Name', '')
pages = self.pages._getlist(slice(0, None, 2), validate=False)
dtype = pages[0].dtype
series = [
TiffPageSeries(pages, shape, dtype, axes, name=name, kind='LSM')
]
if self.pages[1].is_reduced:
pages = self.pages._getlist(slice(1, None, 2), validate=False)
dtype = pages[0].dtype
cp = 1
i = 0
while cp < len(pages) and i < len(shape) - 2:
cp *= shape[i]
i += 1
shape = shape[:i] + pages[0].shape
axes = axes[:i] + 'CYX'
series.append(
TiffPageSeries(pages, shape, dtype, axes, name=name,
kind='LSMreduced')
)
self.is_uniform = False
return series
def _lsm_load_pages(self):
"""Load and fix all pages from LSM file."""
# cache all pages to preserve corrected values
pages = self.pages
pages.cache = True
pages.useframes = True
# use first and second page as keyframes
pages.keyframe = 1
pages.keyframe = 0
# load remaining pages as frames
pages._load(keyframe=None)
# fix offsets and bytecounts first
# TODO: fix multiple conversions between lists and tuples
self._lsm_fix_strip_offsets()
self._lsm_fix_strip_bytecounts()
# assign keyframes for data and thumbnail series
keyframe = pages[0]
for page in pages[::2]:
page.keyframe = keyframe