-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimgfileutils.py
1567 lines (1230 loc) · 54.8 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 : 0.3
# Author : czsrh
# Date : 20.04.2020
# Institution : Carl Zeiss Microscopy GmbH
#
# Copyright (c) 2020 Carl Zeiss AG, Germany. All Rights Reserved.
#################################################################
# this can be used to switch on/off warnings
# import warnings
# warnings.filterwarnings('ignore')
# warnings.simplefilter('ignore')
import czifile as zis
from apeer_ometiff_library import io, processing, omexmlClass
import os
from skimage.external import tifffile
import ipywidgets as widgets
from matplotlib import pyplot as plt, cm
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
from aicsimageio import AICSImage, imread, imread_dask
import dask.array as da
import napari
import pandas as pd
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'
elif imagefile.lower().endswith('.gif') or imagefile.lower().endswith('.jpeg'):
imgtype = 'gif'
elif imagefile.lower().endswith('.jpeg') or imagefile.lower().endswith('.jpeg'):
imgtype = 'jpeg'
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,
'Name': None,
'AcqDate': None,
'TotalSeries': None,
'SizeX': None,
'SizeY': None,
'SizeZ': None,
'SizeC': None,
'SizeT': None,
'Sizes BF': None,
# 'DimOrder BF': None,
# 'DimOrder BF Array': None,
'Axes': None,
'Shape': None,
'isRGB': None,
'ObjNA': None,
'ObjMag': None,
'ObjID': None,
'ObjName': None,
'ObjImmersion': None,
'XScale': None,
'YScale': None,
'ZScale': None,
'XScaleUnit': None,
'YScaleUnit': None,
'ZScaleUnit': None,
'DetectorModel': [],
'DetectorName': [],
'DetectorID': None,
'InstrumentID': None,
'Channels': [],
'ImageIDs': [],
'NumPy.dtype': None
}
return metadata
def get_metadata(imagefile, series=0):
"""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 series: series of OME-TIFF file, , defaults to 0
:type series: int, 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('Image Type: ', imgtype)
md = None
additional_mdczi = None
if imgtype == 'ometiff':
with tifffile.TiffFile(imagefile) as tif:
# get OME-XML metadata as string
omexml = tif[0].image_description.decode('utf-8')
# get the OME-XML using the apeer-ometiff-library
omemd = omexmlClass.OMEXML(omexml)
# parse the OME-XML and return the metadata dictionary and additional information
md = get_metadata_ometiff(imagefile, omemd, series=series)
if imgtype == 'czi':
# parse the CZI metadata return the metadata dictionary and additional information
md = get_metadata_czi(imagefile, dim2none=False)
additional_mdczi = get_additional_metadata_czi(imagefile)
return md, additional_mdczi
def get_metadata_ometiff(filename, omemd, series=0):
"""Returns a dictionary with OME-TIFF metadata.
x
:param filename: filename of the OME-TIFF image
:type filename: str
:param omemd: OME-XML information
:type omemd: OME-XML
:param series: Image Series, defaults to 0
:type series: int, optional
:return: dictionary with the relevant OME-TIFF metainformation
:rtype: dict
"""
# 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
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 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['XScaleUnit'] = 'µm'
metadata['YScale'] = omemd.image(series).Pixels.PhysicalSizeY
#metadata['YScaleUnit'] = omemd.image(series).Pixels.PhysicalSizeYUnit
metadata['ZScale'] = omemd.image(series).Pixels.PhysicalSizeZ
#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:
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:
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:
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)
return metadata
def get_metadata_czi(filename, dim2none=False):
"""
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
:return: metadata - dictionary with the relevant CZI metainformation
:rtype: dict
"""
# get CZI object and read array
czi = zis.CziFile(filename)
# parse the XML into a dictionary
metadatadict_czi = czi.metadata(raw=False)
# parse the XML into a dictionary
# mdczi = czi.metadata()
# metadatadict_czi = xmltodict.parse(czi.metadata())
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.py
metadata['Axes'] = czi.axes
metadata['Shape'] = czi.shape
# add axes and shape information using czifile.py
czi_aics = AICSImage(filename)
metadata['Axes_aics'] = czi_aics.dims
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
# 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.axes[-1] == 3:
metadata['isRGB'] = True
try:
metadata['PixelType'] = metadatadict_czi['ImageDocument']['Metadata']['Information']['Image']['PixelType']
except KeyError as e:
print('Key not found:', e)
metadata['PixelType'] = None
metadata['SizeX'] = np.int(metadatadict_czi['ImageDocument']['Metadata']['Information']['Image']['SizeX'])
metadata['SizeY'] = np.int(metadatadict_czi['ImageDocument']['Metadata']['Information']['Image']['SizeY'])
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
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
channels = []
if metadata['SizeC'] == 1:
try:
channels.append(metadatadict_czi['ImageDocument']['Metadata']['DisplaySetting']
['Channels']['Channel']['ShortName'])
except Exception as e:
channels.append(None)
if metadata['SizeC'] > 1:
for ch in range(metadata['SizeC']):
try:
channels.append(metadatadict_czi['ImageDocument']['Metadata']['DisplaySetting']
['Channels']['Channel'][ch]['ShortName'])
except Exception as e:
print('Exception:', e)
try:
channels.append(metadatadict_czi['ImageDocument']['Metadata']['DisplaySetting']
['Channels']['Channel']['ShortName'])
except Exception as e:
print('Exception:', e)
channels.append(str(ch))
metadata['Channels'] = channels
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:
metadatada['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:
metadatada['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:
metadatada['SizeS'] = None
if not dim2none:
metadata['SizeS'] = 1
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)
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 as e:
print('Key not found:', e)
metadata['SW-Name'] = None
metadata['SW-Version'] = None
try:
metadata['AcqDate'] = metadatadict_czi['ImageDocument']['Metadata']['Information']['Image']['AcquisitionDateAndTime']
except KeyError as e:
print('Key not found:', e)
metadata['AcqDate'] = None
# get objective data
try:
metadata['ObjName'] = metadatadict_czi['ImageDocument']['Metadata']['Information']['Instrument']['Objectives']['Objective']['Name']
except KeyError as e:
print('Key not found:', e)
metadata['ObjName'] = None
try:
metadata['ObjImmersion'] = metadatadict_czi['ImageDocument']['Metadata']['Information']['Instrument']['Objectives']['Objective']['Immersion']
except KeyError as e:
print('Key not found:', e)
metadata['ObjImmersion'] = None
try:
metadata['ObjNA'] = np.float(metadatadict_czi['ImageDocument']['Metadata']['Information']
['Instrument']['Objectives']['Objective']['LensNA'])
except KeyError as e:
print('Key not found:', e)
metadata['ObjNA'] = None
try:
metadata['ObjID'] = metadatadict_czi['ImageDocument']['Metadata']['Information']['Instrument']['Objectives']['Objective']['Id']
except KeyError as e:
print('Key not found:', e)
metadata['ObjID'] = None
try:
metadata['TubelensMag'] = np.float(metadatadict_czi['ImageDocument']['Metadata']['Information']
['Instrument']['TubeLenses']['TubeLens']['Magnification'])
except KeyError as e:
print('Key not found:', e)
metadata['TubelensMag'] = None
try:
metadata['ObjNominalMag'] = np.float(metadatadict_czi['ImageDocument']['Metadata']['Information']
['Instrument']['Objectives']['Objective']['NominalMagnification'])
except KeyError as e:
metadata['ObjNominalMag'] = None
try:
metadata['ObjMag'] = metadata['ObjNominalMag'] * metadata['TubelensMag']
except KeyError as e:
print('Key not found:', e)
metadata['ObjMag'] = None
# get detector information
try:
metadata['DetectorID'] = metadatadict_czi['ImageDocument']['Metadata']['Information']['Instrument']['Detectors']['Detector']['Id']
except KeyError as e:
print('Key not found:', e)
metadata['DetectorID'] = None
try:
metadata['DetectorModel'] = metadatadict_czi['ImageDocument']['Metadata']['Information']['Instrument']['Detectors']['Detector']['Name']
except KeyError as e:
print('Key not found:', e)
metadata['DetectorModel'] = None
try:
metadata['DetectorName'] = metadatadict_czi['ImageDocument']['Metadata']['Information']['Instrument']['Detectors']['Detector']['Manufacturer']['Model']
except KeyError as e:
print('Key not found:', e)
metadata['DetectorName'] = None
# delete some key from dict
# del metadata['Instrument']
# check for well information
metadata['Well_ArrayNames'] = []
metadata['Well_Indices'] = []
metadata['Well_PositionNames'] = []
metadata['Well_ColId'] = []
metadata['Well_RowId'] = []
metadata['WellCounter'] = None
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']):
# more than one scene detected
if metadata['SizeS'] > 1:
# get the current well and add the array name to the metadata
well = allscenes[s]
metadata['Well_ArrayNames'].append(well['ArrayName'])
# exactly one scene detected (e.g. after split scenes etc.)
elif metadata['SizeS'] == 1:
# only get the current well - nor arraynames exist !
well = allscenes
# 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)
# metadata['Well_ColId'].append(well['Shape']['ColumnIndex'])
# metadata['Well_RowId'].append(well['Shape']['RowIndex'])
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)
# more than one scene detected
if metadata['SizeS'] > 1:
# count the content of the list, e.g. how many time a certain well was detected
metadata['WellCounter'] = Counter(metadata['Well_ArrayNames'])
# exactly one scene detected (e.g. after split scenes etc.)
elif metadata['SizeS'] == 1:
# set ArrayNames equal to PositionNames for convenience
metadata['Well_ArrayNames'] = metadata['Well_PositionNames']
# count the content of the list, e.g. how many time a certain well was detected
metadata['WellCounter'] = Counter(metadata['Well_PositionNames'])
# count the number of different wells
metadata['NumWells'] = len(metadata['WellCounter'].keys())
except KeyError as e:
print('No valid Scene or Well information found:', e)
# del metadata['Information']
# del metadata['Scaling']
# close CZI file
czi.close()
# close AICSImage object
czi_aics.close()
return metadata
def get_additional_metadata_czi(filename):
"""
Returns a dictionary with additional CZI metadata.
:param filename: filename of the CZI image
:type filename: str
:return: additional_czimd - dictionary with additional CZI metainformation
:rtype: dict
"""
# get CZI object and read array
czi = zis.CziFile(filename)
# parse the XML into a dictionary
metadatadict_czi = xmltodict.parse(czi.metadata())
additional_czimd = {}
try:
additional_czimd['Experiment'] = metadatadict_czi['ImageDocument']['Metadata']['Experiment']
except:
additional_czimd['Experiment'] = None
try:
additional_czimd['HardwareSetting'] = metadatadict_czi['ImageDocument']['Metadata']['HardwareSetting']
except:
additional_czimd['HardwareSetting'] = None
try:
additional_czimd['CustomAttributes'] = metadatadict_czi['ImageDocument']['Metadata']['CustomAttributes']
except:
additional_czimd['CustomAttributes'] = None
try:
additional_czimd['DisplaySetting'] = metadatadict_czi['ImageDocument']['Metadata']['DisplaySetting']
except KeyError as e:
print('Key not found:', e)
additional_czimd['DisplaySetting'] = None
try:
additional_czimd['Layers'] = metadatadict_czi['ImageDocument']['Metadata']['Layers']
except KeyError as e:
print('Key not found:', e)
additional_czimd['Layers'] = None
# close CZI file
czi.close()
return additional_czimd
def md2dataframe(metadata, paramcol='Parameter', keycol='Value'):
"""Convert the metadata dictionary to a Pandas DataFrame.
:param metadata: MeteData dictionary
:type metadata: dict
:param paramcol: Name of Columns for the MetaData Parameters, defaults to 'Parameter'
:type paramcol: str, optional
:param keycol: Name of Columns for the MetaData Values, defaults to 'Value'
:type keycol: str, optional
:return: Pandas DataFrame containing all the metadata
:rtype: Pandas.DataFrame
"""
mdframe = pd.DataFrame(columns=[paramcol, keycol])
for k in metadata.keys():
d = {'Parameter': k, 'Value': metadata[k]}
df = pd.DataFrame([d], index=[0])
mdframe = pd.concat([mdframe, df], ignore_index=True)
return mdframe
def create_ipyviewer_ome_tiff(array, metadata):
"""
Creates a simple interactive viewer inside a Jupyter Notebook.
Works with OME-TIFF files and the respective metadata
:param array: multidimensional array containing the pixel data
:type array: NumPy.Array
:param metadata: dictionary with the metainformation
:return: out - interactive widgetsfor jupyter notebook
:rtype: IPyWidgets Output
:return: ui - ui for interactive widgets
:rtype: IPyWidgets UI
"""
# time slider
t = widgets.IntSlider(description='Time:',
min=1,
max=metadata['SizeT'],
step=1,
value=1,
continuous_update=False)
# zplane lsider
z = widgets.IntSlider(description='Z-Plane:',
min=1,
max=metadata['SizeZ'],
step=1,
value=1,
continuous_update=False)
# channel slider
c = widgets.IntSlider(description='Channel:',
min=1,
max=metadata['SizeC'],
step=1,
value=1)
# slider for contrast
r = widgets.IntRangeSlider(description='Display Range:',
min=array.min(),
max=array.max(),
step=1,
value=[array.min(), array.max()],
continuous_update=False)
# disable slider that are not needed
if metadata['SizeT'] == 1:
t.disabled = True
if metadata['SizeZ'] == 1:
z.disabled = True
if metadata['SizeC'] == 1:
c.disabled = True
sliders = metadata['DimOrder BF Array'][:-2] + 'R'
# TODO: this section is not complete, because it does not contain all possible cases
# TODO: it is still under constrcution and can be done probably in a much smarter way
if sliders == 'CTZR':
ui = widgets.VBox([c, t, z, r])
def get_TZC_czi(c_ind, t_ind, z_ind, r):
display_image(array, metadata, sliders, c=c_ind, t=t_ind, z=z_ind, vmin=r[0], vmax=r[1])
out = widgets.interactive_output(get_TZC_czi, {'c_ind': c, 't_ind': t, 'z_ind': z, 'r': r})
if sliders == 'TZCR':
ui = widgets.VBox([t, z, c, r])
def get_TZC_czi(t_ind, z_ind, c_ind, r):
display_image(array, metadata, sliders, t=t_ind, z=z_ind, c=c_ind, vmin=r[0], vmax=r[1])
out = widgets.interactive_output(get_TZC_czi, {'t_ind': t, 'z_ind': z, 'c_ind': c, 'r': r})
if sliders == 'TCZR':
ui = widgets.VBox([t, c, z, r])
def get_TZC_czi(t_ind, c_ind, z_ind, r):
display_image(array, metadata, sliders, t=t_ind, c=t_ind, z=z_ind, vmin=r[0], vmax=r[1])
out = widgets.interactive_output(get_TZC_czi, {'t_ind': t, 'c_ind': c, 'z_ind': z, 'r': r})
if sliders == 'CZTR':
ui = widgets.VBox([c, z, t, r])
def get_TZC_czi(c_ind, z_ind, t_ind, r):
display_image(array, metadata, sliders, c=c_ind, z=z_ind, t=t_ind, vmin=r[0], vmax=r[1])
out = widgets.interactive_output(get_TZC_czi, {'c_ind': c, 'z_ind': z, 't_ind': t, 'r': r})
if sliders == 'ZTCR':
ui = widgets.VBox([z, t, c, r])
def get_TZC_czi(z_ind, t_ind, c_ind, r):
display_image(array, metadata, sliders, z=z_ind, t=t_ind, c=c_ind, vmin=r[0], vmax=r[1])
out = widgets.interactive_output(get_TZC_czi, {'z_ind': z, 't_ind': t, 'c_ind': c, 'r': r})
if sliders == 'ZCTR':
ui = widgets.VBox([z, c, t, r])
def get_TZC_czi(z_ind, c_ind, t_ind, r):
display_image(array, metadata, sliders, z=z_ind, c=c_ind, t=t_ind, vmin=r[0], vmax=r[1])
out = widgets.interactive_output(get_TZC_czi, {'z_ind': z, 'c_ind': c, 't_ind': t, 'r': r})
"""
ui = widgets.VBox([t, z, c, r])
def get_TZC_ometiff(t, z, c, r):
display_image(array, metadata, 'TZCR', t=t, z=z, c=c, vmin=r[0], vmax=r[1])
out = widgets.interactive_output(get_TZC_ometiff, {'t': t, 'z': z, 'c': c, 'r': r})
"""
return out, ui # , t, z, c, r
def create_ipyviewer_czi(cziarray, metadata):
"""
Creates a simple interactive viewer inside a Jupyter Notebook.
Works with CZI files and the respective metadata
:param array: multidimensional array containing the pixel data
:type array: NumPy.Array
:param metadata: dictionary with the metainformation
:return: out - interactive widgetsfor jupyter notebook
:rtype: IPyWidgets Output
:return: ui - ui for interactive widgets
:rtype: IPyWidgets UI
"""
dim_dict = metadata['DimOrder CZI']
useB = False
useS = False
if 'B' in dim_dict and dim_dict['B'] >= 0:
useB = True
b = widgets.IntSlider(description='Blocks:',
min=1,
max=metadata['SizeB'],
step=1,
value=1,
continuous_update=False)
if 'S' in dim_dict and dim_dict['S'] >= 0:
useS = True
s = widgets.IntSlider(description='Scenes:',
min=1,
max=metadata['SizeS'],
step=1,
value=1,
continuous_update=False)
t = widgets.IntSlider(description='Time:',
min=1,
max=metadata['SizeT'],
step=1,
value=1,
continuous_update=False)
z = widgets.IntSlider(description='Z-Plane:',
min=1,
max=metadata['SizeZ'],
step=1,
value=1,
continuous_update=False)
c = widgets.IntSlider(description='Channel:',
min=1,
max=metadata['SizeC'],
step=1,
value=1)
print(cziarray.min(), cziarray.max())
r = widgets.IntRangeSlider(description='Display Range:',
min=cziarray.min(),
max=cziarray.max(),
step=1,
value=[cziarray.min(), cziarray.max()],
continuous_update=False)
# disable slider that are not needed
if metadata['SizeB'] == 1 and useB:
b.disabled = True
if metadata['SizeS'] == 1 and useS:
s.disabled = True
if metadata['SizeT'] == 1:
t.disabled = True
if metadata['SizeZ'] == 1:
z.disabled = True
if metadata['SizeC'] == 1:
c.disabled = True
sliders = metadata['Axes'][:-3] + 'R'
# TODO: this section is not complete, because it does not contain all possible cases
# TODO: it is still under constrcution and can be done probably in a much smarter way
if sliders == 'BTZCR':
ui = widgets.VBox([b, t, z, c, r])
def get_TZC_czi(b_ind, t_ind, z_ind, c_ind, r):
display_image(cziarray, metadata, sliders, b=b_ind, t=t_ind, z=z_ind, c=c_ind, vmin=r[0], vmax=r[1])
out = widgets.interactive_output(get_TZC_czi, {'b_ind': b, 't_ind': t, 'z_ind': z, 'c_ind': c, 'r': r})
if sliders == 'BTCZR':
ui = widgets.VBox([b, t, c, z, r])
def get_TZC_czi(b_ind, t_ind, c_ind, z_ind, r):
display_image(cziarray, metadata, sliders, b=b_ind, t=t_ind, c=c_ind, z=z_ind, vmin=r[0], vmax=r[1])
out = widgets.interactive_output(get_TZC_czi, {'b_ind': b, 't_ind': t, 'c_ind': c, 'z_ind': z, 'r': r})
if sliders == 'BSTZCR':
ui = widgets.VBox([b, s, t, z, c, r])
def get_TZC_czi(b_ind, s_ind, t_ind, z_ind, c_ind, r):
display_image(cziarray, metadata, sliders, b=b_ind, s=s_ind, t=t_ind, z=z_ind, c=c_ind, vmin=r[0], vmax=r[1])
out = widgets.interactive_output(get_TZC_czi, {'b_ind': b, 's_ind': s, 't_ind': t, 'z_ind': z, 'c_ind': c, 'r': r})
if sliders == 'BSCR':
ui = widgets.VBox([b, s, c, r])
def get_TZC_czi(b_ind, s_ind, c_ind, r):
display_image(cziarray, metadata, sliders, b=b_ind, s=s_ind, c=c_ind, vmin=r[0], vmax=r[1])
out = widgets.interactive_output(get_TZC_czi, {'b_ind': b, 's_ind': s, 'c_ind': c, 'r': r})
if sliders == 'BSTCZR':
ui = widgets.VBox([b, s, t, c, z, r])
def get_TZC_czi(b_ind, s_ind, t_ind, c_ind, z_ind, r):
display_image(cziarray, metadata, sliders, b=b_ind, s=s_ind, t=t_ind, c=c_ind, z=z_ind, vmin=r[0], vmax=r[1])
out = widgets.interactive_output(get_TZC_czi, {'b_ind': b, 's_ind': s, 't_ind': t, 'c_ind': c, 'z_ind': z, 'r': r})
if sliders == 'STZCR':
ui = widgets.VBox([s, t, z, c, r])
def get_TZC_czi(s_ind, t_ind, z_ind, c_ind, r):
display_image(cziarray, metadata, sliders, s=s_ind, t=t_ind, z=z_ind, c=c_ind, vmin=r[0], vmax=r[1])
out = widgets.interactive_output(get_TZC_czi, {'s_ind': s, 't_ind': t, 'z_ind': z, 'c_ind': c, 'r': r})
if sliders == 'STCZR':
ui = widgets.VBox([s, t, c, z, r])
def get_TZC_czi(s_ind, t_ind, c_ind, z_ind, r):
display_image(cziarray, metadata, sliders, s=s_ind, t=t_ind, c=c_ind, z=z_ind, vmin=r[0], vmax=r[1])
out = widgets.interactive_output(get_TZC_czi, {'s_ind': s, 't_ind': t, 'c_ind': c, 'z_ind': z, 'r': r})
if sliders == 'TZCR':
ui = widgets.VBox([t, z, c, r])
def get_TZC_czi(t_ind, z_ind, c_ind, r):
display_image(cziarray, metadata, sliders, t=t_ind, z=z_ind, c=c_ind, vmin=r[0], vmax=r[1])
out = widgets.interactive_output(get_TZC_czi, {'t_ind': t, 'z_ind': z, 'c_ind': c, 'r': r})
if sliders == 'TCZR':
ui = widgets.VBox([t, c, z, r])
def get_TZC_czi(t_ind, c_ind, z_ind, r):
display_image(cziarray, metadata, sliders, t=t_ind, c=c_ind, z=z_ind, vmin=r[0], vmax=r[1])
out = widgets.interactive_output(get_TZC_czi, {'t_ind': t, 'c_ind': c, 'z_ind': z, 'r': r})
if sliders == 'SCR':
ui = widgets.VBox([s, c, r])
def get_TZC_czi(s_ind, c_ind, r):
display_image(cziarray, metadata, sliders, s=s_ind, c=c_ind, vmin=r[0], vmax=r[1])
out = widgets.interactive_output(get_TZC_czi, {'s_ind': s, 'c_ind': c, 'r': r})
if sliders == 'ZR':
ui = widgets.VBox([z, r])
def get_TZC_czi(z_ind, r):
display_image(cziarray, metadata, sliders, z=z_ind, vmin=r[0], vmax=r[1])
out = widgets.interactive_output(get_TZC_czi, {'z_ind': z, 'r': r})
if sliders == 'TR':
ui = widgets.VBox([t, r])
def get_TZC_czi(t_ind, r):
display_image(cziarray, metadata, sliders, t=t_ind, vmin=r[0], vmax=r[1])
out = widgets.interactive_output(get_TZC_czi, {'t_ind': t, 'r': r})
if sliders == 'CR':
ui = widgets.VBox([c, r])
def get_TZC_czi(c_ind, r):
display_image(cziarray, metadata, sliders, c=c_ind, vmin=r[0], vmax=r[1])
out = widgets.interactive_output(get_TZC_czi, {'c_ind': c, 'r': r})
if sliders == 'BTCR':
ui = widgets.VBox([b, t, c, r])
def get_TZC_czi(b_ind, t_ind, c_ind, r):
display_image(cziarray, metadata, sliders, b=b_ind, t=t_ind, c=c_ind, vmin=r[0], vmax=r[1])
out = widgets.interactive_output(get_TZC_czi, {'b_ind': b, 't_ind': t, 'c_ind': c, 'r': r})
############### Lightsheet data #################
if sliders == 'VIHRSCTZR':
ui = widgets.VBox([c, t, z, r])
def get_TZC_czi(c_ind, t_ind, z_ind, r):
display_image(cziarray, metadata, sliders, c=c_ind, t=t_ind, z=z_ind, vmin=r[0], vmax=r[1])