-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimgfileutils.py
2075 lines (1682 loc) · 74.2 KB
/
imgfileutils.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
# -*- coding: utf-8 -*-
#################################################################
# File : imgfileutils.py
# Version : 1.4.5
# Author : czsrh
# Date : 10.12.2020
# Institution : Carl Zeiss Microscopy GmbH
#
# Copyright (c) 2020 Carl Zeiss AG, Germany. All Rights Reserved.
#################################################################
import czifile as zis
from apeer_ometiff_library import omexmlClass
import os
from pathlib import Path
from matplotlib import pyplot as plt, cm, use
from mpl_toolkits.axes_grid1 import make_axes_locatable
import xmltodict
import numpy as np
from collections import Counter
from lxml import etree as ET
import time
import re
import sys
from aicsimageio import AICSImage, imread, imread_dask
from aicsimageio.writers import ome_tiff_writer
from aicspylibczi import CziFile
import dask.array as da
import pandas as pd
import tifffile
import pydash
try:
import javabridge as jv
import bioformats
except (ImportError, ModuleNotFoundError) as error:
# Output expected ImportErrors.
print(error.__class__.__name__ + ": " + error.msg)
print('Python-BioFormats cannot be used')
try:
import napari
except ModuleNotFoundError as error:
print(error.__class__.__name__ + ": " + error.msg)
from PyQt5.QtWidgets import (
QHBoxLayout,
QVBoxLayout,
QFileSystemModel,
QFileDialog,
QTreeView,
QDialogButtonBox,
QWidget,
QTableWidget,
QTableWidgetItem,
QAbstractItemView
)
from PyQt5.QtCore import Qt, QDir, QSortFilterProxyModel
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QFont
def get_imgtype(imagefile):
"""Returns the type of the image based on the file extension - no magic
:param imagefile: filename of the image
:type imagefile: str
:return: string specifying the image type
:rtype: str
"""
imgtype = None
if imagefile.lower().endswith('.ome.tiff') or imagefile.lower().endswith('.ome.tif'):
# it is on OME-TIFF based on the file extension ... :-)
imgtype = 'ometiff'
elif imagefile.lower().endswith('.tiff') or imagefile.lower().endswith('.tif'):
# it is on OME-TIFF based on the file extension ... :-)
imgtype = 'tiff'
elif imagefile.lower().endswith('.czi'):
# it is on CZI based on the file extension ... :-)
imgtype = 'czi'
elif imagefile.lower().endswith('.png'):
# it is on CZI based on the file extension ... :-)
imgtype = 'png'
elif imagefile.lower().endswith('.jpg') or imagefile.lower().endswith('.jpeg'):
# it is on OME-TIFF based on the file extension ... :-)
imgtype = 'jpg'
return imgtype
def create_metadata_dict():
"""A Python dictionary will be created to hold the relevant metadata.
:return: dictionary with keys for the relevant metadata
:rtype: dict
"""
metadata = {'Directory': None,
'Filename': None,
'Extension': None,
'ImageType': None,
'AcqDate': None,
'TotalSeries': None,
'SizeX': None,
'SizeY': None,
'SizeZ': 1,
'SizeC': 1,
'SizeT': 1,
'SizeS': 1,
'SizeB': 1,
'SizeM': 1,
'Sizes BF': None,
'DimOrder BF': None,
'DimOrder BF Array': None,
'Axes_czifile': None,
'Shape_czifile': None,
'czi_isRGB': None,
'czi_isMosaic': None,
'ObjNA': [],
'ObjMag': [],
'ObjID': [],
'ObjName': [],
'ObjImmersion': [],
'TubelensMag': [],
'ObjNominalMag': [],
'XScale': None,
'YScale': None,
'ZScale': None,
'XScaleUnit': None,
'YScaleUnit': None,
'ZScaleUnit': None,
'DetectorModel': [],
'DetectorName': [],
'DetectorID': [],
'DetectorType': [],
'InstrumentID': [],
'Channels': [],
'ChannelNames': [],
'ChannelColors': [],
'ImageIDs': [],
'NumPy.dtype': None
}
return metadata
def get_metadata(imagefile,
omeseries=0,
round_values=False):
"""Returns a dictionary with metadata depending on the image type.
Only CZI and OME-TIFF are currently supported.
:param imagefile: filename of the image
:type imagefile: str
:param omeseries: series of OME-TIFF file, , defaults to 0
:type omeseries: int, optional
:param round_values: option to round some values, defaults to TrueFalse
:type round_values: bool, optional
:return: metadata - dict with the metainformation
:rtype: dict
:return: additional_mdczi - dict with additional the metainformation for CZI only
:rtype: dict
"""
# get the image type
imgtype = get_imgtype(imagefile)
print('Detected Image Type (based on extension): ', imgtype)
md = {}
additional_md = {}
if imgtype == 'ometiff':
# parse the OME-XML and return the metadata dictionary and additional info
md = get_metadata_ometiff(imagefile, series=omeseries)
elif imgtype == 'czi':
# parse the CZI metadata return the metadata dictionary and additional info
md = get_metadata_czi(imagefile, dim2none=False)
additional_md = get_additional_metadata_czi(imagefile)
# TODO - Remove this when issue is fixed
if round_values:
# temporary workaround for slider / floating point issue in Napari viewer
# https://forum.image.sc/t/problem-with-dimension-slider-when-adding-array-as-new-layer-for-ome-tiff/39092/2?u=sebi06
md['XScale'] = np.round(md['XScale'], 3)
md['YScale'] = np.round(md['YScale'], 3)
md['ZScale'] = np.round(md['ZScale'], 3)
else:
# no metadate will be returned
print('Scales will not be rounded.')
return md, additional_md
def get_metadata_ometiff(filename, series=0):
"""Returns a dictionary with OME-TIFF metadata.
:param filename: filename of the OME-TIFF image
:type filename: str
:param series: Image Series, defaults to 0
:type series: int, optional
:return: dictionary with the relevant OME-TIFF metainformation
:rtype: dict
"""
with tifffile.TiffFile(filename) as tif:
try:
# get OME-XML metadata as string the old way
omexml_string = tif[0].image_description.decode('utf-8')
except TypeError as e:
print(e)
omexml_string = tif.ome_metadata
# get the OME-XML using the apeer-ometiff-library
omemd = omexmlClass.OMEXML(omexml_string)
# create dictionary for metadata and get OME-XML data
metadata = create_metadata_dict()
# get directory and filename etc.
metadata['Directory'] = os.path.dirname(filename)
metadata['Filename'] = os.path.basename(filename)
metadata['Extension'] = 'ome.tiff'
metadata['ImageType'] = 'ometiff'
metadata['AcqDate'] = omemd.image(series).AcquisitionDate
metadata['Name'] = omemd.image(series).Name
# get image dimensions TZCXY
metadata['SizeT'] = omemd.image(series).Pixels.SizeT
metadata['SizeZ'] = omemd.image(series).Pixels.SizeZ
metadata['SizeC'] = omemd.image(series).Pixels.SizeC
metadata['SizeX'] = omemd.image(series).Pixels.SizeX
metadata['SizeY'] = omemd.image(series).Pixels.SizeY
# get number of image series
metadata['TotalSeries'] = omemd.get_image_count()
metadata['Sizes BF'] = [metadata['TotalSeries'],
metadata['SizeT'],
metadata['SizeZ'],
metadata['SizeC'],
metadata['SizeY'],
metadata['SizeX']]
# get dimension order
metadata['DimOrder BF'] = omemd.image(series).Pixels.DimensionOrder
# reverse the order to reflect later the array shape
metadata['DimOrder BF Array'] = metadata['DimOrder BF'][::-1]
# get the scaling
metadata['XScale'] = omemd.image(series).Pixels.PhysicalSizeX
metadata['XScale'] = np.round(metadata['XScale'], 3)
# metadata['XScaleUnit'] = omemd.image(series).Pixels.PhysicalSizeXUnit
metadata['YScale'] = omemd.image(series).Pixels.PhysicalSizeY
metadata['YScale'] = np.round(metadata['YScale'], 3)
# metadata['YScaleUnit'] = omemd.image(series).Pixels.PhysicalSizeYUnit
metadata['ZScale'] = omemd.image(series).Pixels.PhysicalSizeZ
metadata['ZScale'] = np.round(metadata['ZScale'], 3)
# metadata['ZScaleUnit'] = omemd.image(series).Pixels.PhysicalSizeZUnit
# get all image IDs
for i in range(omemd.get_image_count()):
metadata['ImageIDs'].append(i)
# get information about the instrument and objective
try:
metadata['InstrumentID'] = omemd.instrument(series).get_ID()
except (KeyError, AttributeError) as e:
print('Key not found:', e)
metadata['InstrumentID'] = None
try:
metadata['DetectorModel'] = omemd.instrument(series).Detector.get_Model()
metadata['DetectorID'] = omemd.instrument(series).Detector.get_ID()
metadata['DetectorModel'] = omemd.instrument(series).Detector.get_Type()
except (KeyError, AttributeError) as e:
print('Key not found:', e)
metadata['DetectorModel'] = None
metadata['DetectorID'] = None
metadata['DetectorModel'] = None
try:
metadata['ObjNA'] = omemd.instrument(series).Objective.get_LensNA()
metadata['ObjID'] = omemd.instrument(series).Objective.get_ID()
metadata['ObjMag'] = omemd.instrument(series).Objective.get_NominalMagnification()
except (KeyError, AttributeError) as e:
print('Key not found:', e)
metadata['ObjNA'] = None
metadata['ObjID'] = None
metadata['ObjMag'] = None
# get channel names
for c in range(metadata['SizeC']):
metadata['Channels'].append(omemd.image(series).Pixels.Channel(c).Name)
# add axes and shape information using aicsimageio package
ometiff_aics = AICSImage(filename)
metadata['Axes_aics'] = ometiff_aics.dims
metadata['Shape_aics'] = ometiff_aics.shape
metadata['SizeX_aics'] = ometiff_aics.size_x
metadata['SizeY_aics'] = ometiff_aics.size_y
metadata['SizeC_aics'] = ometiff_aics.size_c
metadata['SizeZ_aics'] = ometiff_aics.size_t
metadata['SizeT_aics'] = ometiff_aics.size_t
metadata['SizeS_aics'] = ometiff_aics.size_s
# close AICSImage object
ometiff_aics.close()
# check for None inside Scaling to avoid issues later one ...
metadata = checkmdscale_none(metadata,
tocheck=['XScale', 'YScale', 'ZScale'],
replace=[1.0, 1.0, 1.0])
return metadata
def checkmdscale_none(md, tocheck=['ZScale'], replace=[1.0]):
"""Check scaling entries for None to avoid issues later on
:param md: original metadata
:type md: dict
:param tocheck: list with entries to check for None, defaults to ['ZScale']
:type tocheck: list, optional
:param replace: list with values replacing the None, defaults to [1.0]
:type replace: list, optional
:return: modified metadata where None entries where replaces by
:rtype: [type]
"""
for tc, rv in zip(tocheck, replace):
if md[tc] is None:
md[tc] = rv
return md
def get_metadata_czi(filename, dim2none=False,
forceDim=False,
forceDimname='SizeC',
forceDimvalue=2,
convert_scunit=True):
"""
Returns a dictionary with CZI metadata.
Information CZI Dimension Characters:
- '0': 'Sample', # e.g. RGBA
- 'X': 'Width',
- 'Y': 'Height',
- 'C': 'Channel',
- 'Z': 'Slice', # depth
- 'T': 'Time',
- 'R': 'Rotation',
- 'S': 'Scene', # contiguous regions of interest in a mosaic image
- 'I': 'Illumination', # direction
- 'B': 'Block', # acquisition
- 'M': 'Mosaic', # index of tile for compositing a scene
- 'H': 'Phase', # e.g. Airy detector fibers
- 'V': 'View', # e.g. for SPIM
:param filename: filename of the CZI image
:type filename: str
:param dim2none: option to set non-existing dimension to None, defaults to False
:type dim2none: bool, optional
:param forceDim: option to force to not read certain dimensions, defaults to False
:type forceDim: bool, optional
:param forceDimname: name of the dimension not to read, defaults to SizeC
:type forceDimname: str, optional
:param forceDimvalue: index of the dimension not to read, defaults to 2
:type forceDimvalue: int, optional
:param convert_scunit: convert scale unit string from 'µm' to 'micron', defaults to False
:type convert_scunit: bool, optional
:return: metadata - dictionary with the relevant CZI metainformation
:rtype: dict
"""
# get CZI object
czi = zis.CziFile(filename)
# parse the XML into a dictionary
metadatadict_czi = czi.metadata(raw=False)
# initialize metadata dictionary
metadata = create_metadata_dict()
# get directory and filename etc.
metadata['Directory'] = os.path.dirname(filename)
metadata['Filename'] = os.path.basename(filename)
metadata['Extension'] = 'czi'
metadata['ImageType'] = 'czi'
# add axes and shape information using czifile package
metadata['Axes_czifile'] = czi.axes
metadata['Shape_czifile'] = czi.shape
# add axes and shape information using aicsimageio package
czi_aics = AICSImage(filename)
metadata['Axes_aics'] = czi_aics.dims
try:
metadata['Shape_aics'] = czi_aics.shape
metadata['SizeX_aics'] = czi_aics.size_x
metadata['SizeY_aics'] = czi_aics.size_y
metadata['SizeC_aics'] = czi_aics.size_c
metadata['SizeZ_aics'] = czi_aics.size_t
metadata['SizeT_aics'] = czi_aics.size_t
metadata['SizeS_aics'] = czi_aics.size_s
except KeyError as e:
metadata['Shape_aics'] = None
metadata['SizeX_aics'] = None
metadata['SizeY_aics'] = None
metadata['SizeC_aics'] = None
metadata['SizeZ_aics'] = None
metadata['SizeT_aics'] = None
metadata['SizeS_aics'] = None
# get additional data by using pylibczi directly
# Get the shape of the data, the coordinate pairs are (start index, size)
aics_czi = CziFile(filename)
metadata['dims_aicspylibczi'] = aics_czi.dims_shape()[0]
metadata['dimorder_aicspylibczi'] = aics_czi.dims
metadata['size_aicspylibczi'] = aics_czi.size
metadata['czi_isMosaic'] = aics_czi.is_mosaic()
# determine pixel type for CZI array
metadata['NumPy.dtype'] = czi.dtype
# check if the CZI image is an RGB image depending
# on the last dimension entry of axes
if czi.shape[-1] == 3:
metadata['czi_isRGB'] = True
try:
metadata['PixelType'] = metadatadict_czi['ImageDocument']['Metadata']['Information']['Image']['PixelType']
except KeyError as e:
print('Key not found:', e)
metadata['PixelType'] = None
try:
metadata['SizeX'] = np.int(metadatadict_czi['ImageDocument']['Metadata']['Information']['Image']['SizeX'])
except KeyError as e:
metadata['SizeX'] = None
try:
metadata['SizeY'] = np.int(metadatadict_czi['ImageDocument']['Metadata']['Information']['Image']['SizeY'])
except KeyError as e:
metadata['SizeY'] = None
try:
metadata['SizeZ'] = np.int(metadatadict_czi['ImageDocument']['Metadata']['Information']['Image']['SizeZ'])
except Exception as e:
# print('Exception:', e)
if dim2none:
metadata['SizeZ'] = None
if not dim2none:
metadata['SizeZ'] = 1
# for special cases do not read the SizeC from the metadata
if forceDim and forceDimname == 'SizeC':
metadata[forceDimname] = forceDimvalue
if not forceDim:
try:
metadata['SizeC'] = np.int(metadatadict_czi['ImageDocument']['Metadata']['Information']['Image']['SizeC'])
except Exception as e:
# print('Exception:', e)
if dim2none:
metadata['SizeC'] = None
if not dim2none:
metadata['SizeC'] = 1
# create empty lists for channel related information
channels = []
channels_names = []
channels_colors = []
# in case of only one channel
if metadata['SizeC'] == 1:
# get name for dye
try:
channels.append(metadatadict_czi['ImageDocument']['Metadata']['DisplaySetting']
['Channels']['Channel']['ShortName'])
except KeyError as e:
print('Exception:', e)
try:
channels.append(metadatadict_czi['ImageDocument']['Metadata']['DisplaySetting']
['Channels']['Channel']['DyeName'])
except KeyError as e:
print('Exception:', e)
channels.append('Dye-CH1')
# get channel name
try:
channels_names.append(metadatadict_czi['ImageDocument']['Metadata']['DisplaySetting']
['Channels']['Channel']['Name'])
except KeyError as e:
print('Exception:', e)
channels_names.append['CH1']
# get channel color
try:
channels_colors.append(metadatadict_czi['ImageDocument']['Metadata']['DisplaySetting']
['Channels']['Channel']['Color'])
except KeyError as e:
print('Exception:', e)
channels_colors.append('#80808000')
# in case of two or more channels
if metadata['SizeC'] > 1:
# loop over all channels
for ch in range(metadata['SizeC']):
# get name for dyes
try:
channels.append(metadatadict_czi['ImageDocument']['Metadata']['DisplaySetting']
['Channels']['Channel'][ch]['ShortName'])
except KeyError as e:
print('Exception:', e)
try:
channels.append(metadatadict_czi['ImageDocument']['Metadata']['DisplaySetting']
['Channels']['Channel'][ch]['DyeName'])
except KeyError as e:
print('Exception:', e)
channels.append('Dye-CH' + str(ch))
# get channel names
try:
channels_names.append(metadatadict_czi['ImageDocument']['Metadata']['DisplaySetting']
['Channels']['Channel'][ch]['Name'])
except KeyError as e:
print('Exception:', e)
channels_names.append('CH' + str(ch))
# get channel colors
try:
channels_colors.append(metadatadict_czi['ImageDocument']['Metadata']['DisplaySetting']
['Channels']['Channel'][ch]['Color'])
except KeyError as e:
print('Exception:', e)
# use grayscale instead
channels_colors.append('80808000')
# write channels information (as lists) into metadata dictionary
metadata['Channels'] = channels
metadata['ChannelNames'] = channels_names
metadata['ChannelColors'] = channels_colors
try:
metadata['SizeT'] = np.int(metadatadict_czi['ImageDocument']['Metadata']['Information']['Image']['SizeT'])
except Exception as e:
# print('Exception:', e)
if dim2none:
metadata['SizeT'] = None
if not dim2none:
metadata['SizeT'] = 1
try:
metadata['SizeM'] = np.int(metadatadict_czi['ImageDocument']['Metadata']['Information']['Image']['SizeM'])
except Exception as e:
# print('Exception:', e)
if dim2none:
metadata['SizeM'] = None
if not dim2none:
metadata['SizeM'] = 1
try:
metadata['SizeB'] = np.int(metadatadict_czi['ImageDocument']['Metadata']['Information']['Image']['SizeB'])
except Exception as e:
# print('Exception:', e)
if dim2none:
metadata['SizeB'] = None
if not dim2none:
metadata['SizeB'] = 1
try:
metadata['SizeS'] = np.int(metadatadict_czi['ImageDocument']['Metadata']['Information']['Image']['SizeS'])
except Exception as e:
# print('Exception:', e)
if dim2none:
metadata['SizeS'] = None
if not dim2none:
metadata['SizeS'] = 1
try:
metadata['SizeH'] = np.int(metadatadict_czi['ImageDocument']['Metadata']['Information']['Image']['SizeH'])
except Exception as e:
# print('Exception:', e)
if dim2none:
metadata['SizeH'] = None
if not dim2none:
metadata['SizeH'] = 1
try:
metadata['SizeI'] = np.int(metadatadict_czi['ImageDocument']['Metadata']['Information']['Image']['SizeI'])
except Exception as e:
# print('Exception:', e)
if dim2none:
metadata['SizeI'] = None
if not dim2none:
metadata['SizeI'] = 1
try:
metadata['SizeV'] = np.int(metadatadict_czi['ImageDocument']['Metadata']['Information']['Image']['SizeV'])
except Exception as e:
# print('Exception:', e)
if dim2none:
metadata['SizeV'] = None
if not dim2none:
metadata['SizeV'] = 1
# get the scaling information
try:
# metadata['Scaling'] = metadatadict_czi['ImageDocument']['Metadata']['Scaling']
metadata['XScale'] = float(metadatadict_czi['ImageDocument']['Metadata']['Scaling']['Items']['Distance'][0]['Value']) * 1000000
metadata['YScale'] = float(metadatadict_czi['ImageDocument']['Metadata']['Scaling']['Items']['Distance'][1]['Value']) * 1000000
metadata['XScale'] = np.round(metadata['XScale'], 3)
metadata['YScale'] = np.round(metadata['YScale'], 3)
try:
metadata['XScaleUnit'] = metadatadict_czi['ImageDocument']['Metadata']['Scaling']['Items']['Distance'][0]['DefaultUnitFormat']
metadata['YScaleUnit'] = metadatadict_czi['ImageDocument']['Metadata']['Scaling']['Items']['Distance'][1]['DefaultUnitFormat']
except KeyError as e:
print('Key not found:', e)
metadata['XScaleUnit'] = None
metadata['YScaleUnit'] = None
try:
metadata['ZScale'] = float(metadatadict_czi['ImageDocument']['Metadata']['Scaling']['Items']['Distance'][2]['Value']) * 1000000
metadata['ZScale'] = np.round(metadata['ZScale'], 3)
# additional check for faulty z-scaling
if metadata['ZScale'] == 0.0:
metadata['ZScale'] = 1.0
try:
metadata['ZScaleUnit'] = metadatadict_czi['ImageDocument']['Metadata']['Scaling']['Items']['Distance'][2]['DefaultUnitFormat']
except KeyError as e:
print('Key not found:', e)
metadata['ZScaleUnit'] = metadata['XScaleUnit']
except Exception as e:
# print('Exception:', e)
if dim2none:
metadata['ZScale'] = None
metadata['ZScaleUnit'] = None
if not dim2none:
# set to isotropic scaling if it was single plane only
metadata['ZScale'] = metadata['XScale']
metadata['ZScaleUnit'] = metadata['XScaleUnit']
except Exception as e:
print('Exception:', e)
print('Scaling Data could not be found.')
# try to get software version
try:
metadata['SW-Name'] = metadatadict_czi['ImageDocument']['Metadata']['Information']['Application']['Name']
metadata['SW-Version'] = metadatadict_czi['ImageDocument']['Metadata']['Information']['Application']['Version']
except (KeyError, TypeError) as e:
print(e)
metadata['SW-Name'] = None
metadata['SW-Version'] = None
try:
metadata['AcqDate'] = metadatadict_czi['ImageDocument']['Metadata']['Information']['Image']['AcquisitionDateAndTime']
except (KeyError, TypeError) as e:
print(e)
metadata['AcqDate'] = None
# get objective data
try:
if isinstance(metadatadict_czi['ImageDocument']['Metadata']['Information']['Instrument']['Objectives']['Objective'], list):
num_obj = len(metadatadict_czi['ImageDocument']['Metadata']['Information']['Instrument']['Objectives']['Objective'])
else:
num_obj = 1
except (KeyError, TypeError) as e:
print(e)
num_obj = 1
# if there is only one objective found
if num_obj == 1:
try:
metadata['ObjName'].append(metadatadict_czi['ImageDocument']['Metadata']['Information']
['Instrument']['Objectives']['Objective']['Name'])
except (KeyError, TypeError) as e:
print(e)
metadata['ObjName'].append(None)
try:
metadata['ObjImmersion'] = metadatadict_czi['ImageDocument']['Metadata']['Information']['Instrument']['Objectives']['Objective']['Immersion']
except (KeyError, TypeError) as e:
print(e)
metadata['ObjImmersion'] = None
try:
metadata['ObjNA'] = np.float(metadatadict_czi['ImageDocument']['Metadata']['Information']
['Instrument']['Objectives']['Objective']['LensNA'])
except (KeyError, TypeError) as e:
print(e)
metadata['ObjNA'] = None
try:
metadata['ObjID'] = metadatadict_czi['ImageDocument']['Metadata']['Information']['Instrument']['Objectives']['Objective']['Id']
except (KeyError, TypeError) as e:
print(e)
metadata['ObjID'] = None
try:
metadata['TubelensMag'] = np.float(metadatadict_czi['ImageDocument']['Metadata']['Information']
['Instrument']['TubeLenses']['TubeLens']['Magnification'])
except (KeyError, TypeError) as e:
print(e, 'Using Default Value = 1.0 for Tublens Magnification.')
metadata['TubelensMag'] = 1.0
try:
metadata['ObjNominalMag'] = np.float(metadatadict_czi['ImageDocument']['Metadata']['Information']
['Instrument']['Objectives']['Objective']['NominalMagnification'])
except (KeyError, TypeError) as e:
print(e, 'Using Default Value = 1.0 for Nominal Magnification.')
metadata['ObjNominalMag'] = 1.0
try:
if metadata['TubelensMag'] is not None:
metadata['ObjMag'] = metadata['ObjNominalMag'] * metadata['TubelensMag']
if metadata['TubelensMag'] is None:
print('No TublensMag found. Use 1 instead')
metadata['ObjMag'] = metadata['ObjNominalMag'] * 1.0
except (KeyError, TypeError) as e:
print(e)
metadata['ObjMag'] = None
if num_obj > 1:
for o in range(num_obj):
try:
metadata['ObjName'].append(metadatadict_czi['ImageDocument']['Metadata']['Information']
['Instrument']['Objectives']['Objective'][o]['Name'])
except KeyError as e:
print('Key not found:', e)
metadata['ObjName'].append(None)
try:
metadata['ObjImmersion'].append(metadatadict_czi['ImageDocument']['Metadata']['Information']
['Instrument']['Objectives']['Objective'][o]['Immersion'])
except KeyError as e:
print('Key not found:', e)
metadata['ObjImmersion'].append(None)
try:
metadata['ObjNA'].append(np.float(metadatadict_czi['ImageDocument']['Metadata']['Information']
['Instrument']['Objectives']['Objective'][o]['LensNA']))
except KeyError as e:
print('Key not found:', e)
metadata['ObjNA'].append(None)
try:
metadata['ObjID'].append(metadatadict_czi['ImageDocument']['Metadata']['Information']
['Instrument']['Objectives']['Objective'][o]['Id'])
except KeyError as e:
print('Key not found:', e)
metadata['ObjID'].append(None)
try:
metadata['TubelensMag'].append(np.float(metadatadict_czi['ImageDocument']['Metadata']['Information']
['Instrument']['TubeLenses']['TubeLens'][o]['Magnification']))
except KeyError as e:
print('Key not found:', e, 'Using Default Value = 1.0 for Tublens Magnification.')
metadata['TubelensMag'].append(1.0)
try:
metadata['ObjNominalMag'].append(np.float(metadatadict_czi['ImageDocument']['Metadata']['Information']
['Instrument']['Objectives']['Objective'][o]['NominalMagnification']))
except KeyError as e:
print('Key not found:', e, 'Using Default Value = 1.0 for Nominal Magnification.')
metadata['ObjNominalMag'].append(1.0)
try:
if metadata['TubelensMag'] is not None:
metadata['ObjMag'].append(metadata['ObjNominalMag'][o] * metadata['TubelensMag'][o])
if metadata['TubelensMag'] is None:
print('No TublensMag found. Use 1 instead')
metadata['ObjMag'].append(metadata['ObjNominalMag'][o] * 1.0)
except KeyError as e:
print('Key not found:', e)
metadata['ObjMag'].append(None)
# get detector information
# check if there are any detector entries inside the dictionary
if pydash.objects.has(metadatadict_czi, ['ImageDocument', 'Metadata', 'Information', 'Instrument', 'Detectors']):
if isinstance(metadatadict_czi['ImageDocument']['Metadata']['Information']['Instrument']['Detectors']['Detector'], list):
num_detectors = len(metadatadict_czi['ImageDocument']['Metadata']['Information']['Instrument']['Detectors']['Detector'])
else:
num_detectors = 1
# if there is only one detector found
if num_detectors == 1:
# check for detector ID
try:
metadata['DetectorID'].append(metadatadict_czi['ImageDocument']['Metadata']['Information']
['Instrument']['Detectors']['Detector']['Id'])
except KeyError as e:
metadata['DetectorID'].append(None)
# check for detector Name
try:
metadata['DetectorName'].append(metadatadict_czi['ImageDocument']['Metadata']['Information']
['Instrument']['Detectors']['Detector']['Name'])
except KeyError as e:
metadata['DetectorName'].append(None)
# check for detector model
try:
metadata['DetectorModel'].append(metadatadict_czi['ImageDocument']['Metadata']['Information']
['Instrument']['Detectors']['Detector']['Manufacturer']['Model'])
except KeyError as e:
metadata['DetectorModel'].append(None)
# check for detector type
try:
metadata['DetectorType'].append(metadatadict_czi['ImageDocument']['Metadata']['Information']
['Instrument']['Detectors']['Detector']['Type'])
except KeyError as e:
metadata['DetectorType'].append(None)
if num_detectors > 1:
for d in range(num_detectors):
# check for detector ID
try:
metadata['DetectorID'].append(metadatadict_czi['ImageDocument']['Metadata']['Information']
['Instrument']['Detectors']['Detector'][d]['Id'])
except KeyError as e:
metadata['DetectorID'].append(None)
# check for detector Name
try:
metadata['DetectorName'].append(metadatadict_czi['ImageDocument']['Metadata']['Information']
['Instrument']['Detectors']['Detector'][d]['Name'])
except KeyError as e:
metadata['DetectorName'].append(None)
# check for detector model
try:
metadata['DetectorModel'].append(metadatadict_czi['ImageDocument']['Metadata']['Information']
['Instrument']['Detectors']['Detector'][d]['Manufacturer']['Model'])
except KeyError as e:
metadata['DetectorModel'].append(None)
# check for detector type
try:
metadata['DetectorType'].append(metadatadict_czi['ImageDocument']['Metadata']['Information']
['Instrument']['Detectors']['Detector'][d]['Type'])
except KeyError as e:
metadata['DetectorType'].append(None)
# check for well information
metadata['Well_ArrayNames'] = []
metadata['Well_Indices'] = []
metadata['Well_PositionNames'] = []
metadata['Well_ColId'] = []
metadata['Well_RowId'] = []
metadata['WellCounter'] = None
metadata['SceneStageCenterX'] = []
metadata['SceneStageCenterY'] = []
try:
print('Trying to extract Scene and Well information if existing ...')
# extract well information from the dictionary
allscenes = metadatadict_czi['ImageDocument']['Metadata']['Information']['Image']['Dimensions']['S']['Scenes']['Scene']
# loop over all detected scenes
for s in range(metadata['SizeS']):
if metadata['SizeS'] == 1:
well = allscenes
try:
metadata['Well_ArrayNames'].append(allscenes['ArrayName'])
except KeyError as e:
# print('Key not found in Metadata Dictionary:', e)
try:
metadata['Well_ArrayNames'].append(well['Name'])
except KeyError as e:
print('Key not found in Metadata Dictionary:', e, 'Using A1 instead')
metadata['Well_ArrayNames'].append('A1')
try:
metadata['Well_Indices'].append(allscenes['Index'])
except KeyError as e:
print('Key not found in Metadata Dictionary:', e)
metadata['Well_Indices'].append(1)
try:
metadata['Well_PositionNames'].append(allscenes['Name'])
except KeyError as e:
print('Key not found in Metadata Dictionary:', e)
metadata['Well_PositionNames'].append('P1')
try:
metadata['Well_ColId'].append(np.int(allscenes['Shape']['ColumnIndex']))
except KeyError as e:
print('Key not found in Metadata Dictionary:', e)
metadata['Well_ColId'].append(0)
try:
metadata['Well_RowId'].append(np.int(allscenes['Shape']['RowIndex']))
except KeyError as e:
print('Key not found in Metadata Dictionary:', e)
metadata['Well_RowId'].append(0)
try:
# count the content of the list, e.g. how many time a certain well was detected
metadata['WellCounter'] = Counter(metadata['Well_ArrayNames'])
except KeyError as e:
print('Key not found in Metadata Dictionary:', e)
metadata['WellCounter'].append(Counter({'A1': 1}))
try:
# get the SceneCenter Position
sx = allscenes['CenterPosition'].split(',')[0]
sy = allscenes['CenterPosition'].split(',')[1]
metadata['SceneStageCenterX'].append(np.double(sx))
metadata['SceneStageCenterY'].append(np.double(sy))
except KeyError as e:
metadata['SceneStageCenterX'].append(0.0)
metadata['SceneStageCenterY'].append(0.0)
if metadata['SizeS'] > 1:
try:
well = allscenes[s]
metadata['Well_ArrayNames'].append(well['ArrayName'])
except KeyError as e:
# print('Key not found in Metadata Dictionary:', e)
try:
metadata['Well_ArrayNames'].append(well['Name'])
except KeyError as e:
print('Key not found in Metadata Dictionary:', e, 'Using A1 instead')
metadata['Well_ArrayNames'].append('A1')
# get the well information
try:
metadata['Well_Indices'].append(well['Index'])
except KeyError as e:
# print('Key not found in Metadata Dictionary:', e)
metadata['Well_Indices'].append(None)
try:
metadata['Well_PositionNames'].append(well['Name'])
except KeyError as e:
# print('Key not found in Metadata Dictionary:', e)
metadata['Well_PositionNames'].append(None)
try:
metadata['Well_ColId'].append(np.int(well['Shape']['ColumnIndex']))
except KeyError as e:
print('Key not found in Metadata Dictionary:', e)
metadata['Well_ColId'].append(None)
try:
metadata['Well_RowId'].append(np.int(well['Shape']['RowIndex']))
except KeyError as e:
print('Key not found in Metadata Dictionary:', e)
metadata['Well_RowId'].append(None)
# count the content of the list, e.g. how many time a certain well was detected
metadata['WellCounter'] = Counter(metadata['Well_ArrayNames'])
# try:
if isinstance(allscenes, list):
try:
# get the SceneCenter Position
sx = allscenes[s]['CenterPosition'].split(',')[0]
sy = allscenes[s]['CenterPosition'].split(',')[1]
metadata['SceneStageCenterX'].append(np.double(sx))
metadata['SceneStageCenterY'].append(np.double(sy))
except KeyError as e:
print('Key not found in Metadata Dictionary:', e)
metadata['SceneCenterX'].append(0.0)
metadata['SceneCenterY'].append(0.0)
if not isinstance(allscenes, list):
metadata['SceneStageCenterX'].append(0.0)
metadata['SceneStageCenterY'].append(0.0)
# count the number of different wells
metadata['NumWells'] = len(metadata['WellCounter'].keys())
except (KeyError, TypeError) as e:
print('No valid Scene or Well information found:', e)
# close CZI file
czi.close()
# close AICSImage object
czi_aics.close()