def __post_init__(self): # get directory and filename etc. self.dirname = os.path.dirname(self.filepath) self.filename = os.path.basename(self.filepath) # get metadata dictionary using pylibCZIrw with pyczi.open_czi(self.filepath) as czidoc: md_dict = czidoc.metadata # get acquisition data and SW version try: self.software_name = md_dict["ImageDocument"]["Metadata"][ "Information"]["Application"]["Name"] self.software_version = md_dict["ImageDocument"]["Metadata"][ "Information"]["Application"]["Version"] except (KeyError, TypeError) as e: print("Key not found:", e) self.software_name = None self.software_version = None try: self.acquisition_date = md_dict["ImageDocument"]["Metadata"][ "Information"]["Image"]["AcquisitionDateAndTime"] except (KeyError, TypeError) as e: print("Key not found:", e) self.acquisition_date = None
def writexml(filename: str, xmlsuffix: str = '_CZI_MetaData.xml') -> str: """Write XML information of CZI to disk :param filename: CZI image filename :type filename: str :param xmlsuffix: suffix for the XML file that will be created, defaults to '_CZI_MetaData.xml' :type xmlsuffix: str, optional :return: filename of the XML file :rtype: str """ # get the raw metadata as a XML or dictionary with pyczi.open_czi(filename) as czidoc: metadata_xmlstr = czidoc.raw_metadata # change file name xmlfile = filename.replace('.czi', xmlsuffix) # get tree from string tree = ET.ElementTree(ET.fromstring(metadata_xmlstr)) # write XML file to same folder tree.write(xmlfile, encoding='utf-8', method='xml') return xmlfile
def __init__(self, filename: str): # get metadata dictionary using pylibCZIrw with pyczi.open_czi(filename) as czidoc: md_dict = czidoc.metadata self.md = DictObj(md_dict)
def __init__(self, filename: str, dim2none: bool = True) -> None: # get metadata dictionary using pylibCZIrw self.scalefactorXY = None self.ratio_sf = None self.Y_sf = None self.X_sf = None with pyczi.open_czi(filename) as czidoc: md_dict = czidoc.metadata def _safe_get_scale(distances_: List[Dict[Any, Any]], idx: int) -> Optional[float]: try: return np.round( float(distances_[idx]["Value"]) * 1000000, 3) if distances_[idx]["Value"] is not None else None except IndexError: if dim2none: return None if not dim2none: # use scaling = 1.0 micron as fallback return 1.0 try: distances = md_dict["ImageDocument"]["Metadata"]["Scaling"][ "Items"]["Distance"] except KeyError: if dim2none: self.X = None self.Y = None self.Z = None if not dim2none: self.X = 1.0 self.Y = 1.0 self.Z = 1.0 # get the scaling in [micron] - inside CZI the default is [m] self.X = _safe_get_scale(distances, 0) self.Y = _safe_get_scale(distances, 1) self.Z = _safe_get_scale(distances, 2) # safety check in case a scale = 0 if self.X == 0.0: self.X = 1.0 if self.Y == 0.0: self.Y = 1.0 if self.Z == 0.0: self.Z = 1.0 # set the scaling unit to [micron] self.Unit = "micron" # get scaling ratio self.ratio = self.get_scale_ratio(scalex=self.X, scaley=self.Y, scalez=self.Z)
def read_mdarray(filename: str, remove_Adim: bool = True) -> Tuple[np.ndarray, str]: # get the complete metadata at once as one big class mdata = czimd.CziMetadata(filename) # open the CZI document to read the with pyczi.open_czi(filename) as czidoc: if mdata.image.SizeS is not None: # get size for a single scene using the 1st # works only if scene shape is consistent size_x = mdata.bbox.all_scenes[0].w size_y = mdata.bbox.all_scenes[0].h if mdata.image.SizeS is None: size_x = mdata.image.SizeX size_y = mdata.image.SizeY # check if dimensions are None (because they do not exist for that image) size_c = misc.check_dimsize(mdata.image.SizeC, set2value=1) size_z = misc.check_dimsize(mdata.image.SizeZ, set2value=1) size_t = misc.check_dimsize(mdata.image.SizeT, set2value=1) size_s = misc.check_dimsize(mdata.image.SizeS, set2value=1) # define the dimension order to be STZCYXA dimstring = "STZCYXA" array_md = np.empty([ size_s, size_t, size_z, size_c, size_y, size_x, 3 if mdata.isRGB else 1 ], dtype=mdata.npdtype) # read array for the scene for s, t, z, c in product(range(size_s), range(size_t), range(size_z), range(size_c)): if mdata.image.SizeS is None: image2d = czidoc.read(plane={'T': t, 'Z': z, 'C': c}) else: image2d = czidoc.read(plane={'T': t, 'Z': z, 'C': c}, scene=s) # check if the image2d is really not too big if (mdata.bbox.total_bounding_box["X"][1] > mdata.image.SizeX or mdata.bbox.total_bounding_box["Y"][1] > mdata.image.SizeY): image2d = image2d[..., 0:mdata.image.SizeY, 0:mdata.image.SizeX, :] array_md[s, t, z, c, ...] = image2d if remove_Adim: dimstring.replace("A", "") array_md = np.squeeze(array_md, axis=-1) return array_md, dimstring
def __init__(self, filename: str, sceneindex: int) -> None: # get metadata dictionary using pylibCZIrw with pyczi.open_czi(filename) as czidoc: md_dict = czidoc.metadata self.bbox = czidoc.scenes_bounding_rectangle[sceneindex] self.xstart = self.bbox.x self.ystart = self.bbox.y self.width = self.bbox.w self.height = self.bbox.h self.index = sceneindex
def read_5d(filename: str, sizes: Tuple[int, int, int, int, int], s: int, mdata: czimd.CziMetadata, remove_Adim: bool = True) -> np.ndarray: array_md = da.empty([ sizes[0], sizes[1], sizes[2], sizes[3], sizes[4], 3 if mdata.isRGB else 1 ], dtype=mdata.npdtype) # open the CZI document to read the with pyczi.open_czi(filename) as czidoc: # read array for the scene for t, z, c in product(range(sizes[0]), range(sizes[1]), range(sizes[2])): if mdata.image.SizeS is None: image2d = czidoc.read() else: image2d = czidoc.read(plane={ 'T': t, 'Z': z, 'C': c }, scene=s) # check if the image2d is really not too big if mdata.pyczi_dims["X"][ 1] > mdata.image.SizeX or mdata.pyczi_dims["Y"][ 1] > mdata.image.SizeY: image2d = image2d[..., 0:mdata.image.SizeY, 0:mdata.image.SizeX, :] array_md[t, z, c, ...] = image2d if remove_Adim: array_md = np.squeeze(array_md, axis=-1) return array_md
def __post_init__(self): with pyczi.open_czi(self.filename) as czidoc: try: self.all_scenes = czidoc.scenes_bounding_rectangle except Exception as e: self.all_scenes = None print("Scenes Bounding rectangle not found.", e) try: self.total_rect = czidoc.total_bounding_rectangle except Exception as e: self.total_rect = None print("Total Bounding rectangle not found.", e) try: self.total_bounding_box = czidoc.total_bounding_box except Exception as e: self.total_bounding_box = None print("Total Bounding Box not found.", e)
def __init__(self, filename: str) -> None: # get metadata dictionary using pylibCZIrw with pyczi.open_czi(filename) as czidoc: md_dict = czidoc.metadata try: self.experiment = md_dict["ImageDocument"]["Metadata"][ "Experiment"] except (KeyError, TypeError) as e: print("Key not found :", e) self.experiment = None try: self.hardwaresetting = md_dict["ImageDocument"]["Metadata"][ "HardwareSetting"] except (KeyError, TypeError) as e: print("Key not found :", e) self.hardwaresetting = None try: self.customattributes = md_dict["ImageDocument"]["Metadata"][ "CustomAttributes"] except (KeyError, TypeError) as e: print("Key not found :", e) self.customattributes = None try: self.displaysetting = md_dict["ImageDocument"]["Metadata"][ "DisplaySetting"] except (KeyError, TypeError) as e: print("Key not found :", e) self.displaysetting = None try: self.layers = md_dict["ImageDocument"]["Metadata"]["Layers"] except (KeyError, TypeError) as e: print("Key not found :", e) self.layers = None
def __init__(self, filename: str) -> None: self.SizeX = None self.SizeY = None self.SizeS = None self.SizeT = None self.SizeZ = None self.SizeC = None self.SizeM = None self.SizeR = None self.SizeH = None self.SizeI = None self.SizeV = None self.SizeB = None self.SizeX_sf = None self.SizeY_sf = None with pyczi.open_czi(filename) as czidoc_r: dim_dict = self.get_image_dimensions(czidoc_r.metadata) for key in dim_dict: setattr(self, key, dim_dict[key])
def __init__(self, filename: str) -> None: # get metadata dictionary using pylibCZIrw with pyczi.open_czi(filename) as czidoc: md_dict = czidoc.metadata self.ID = None self.Name = None # check if there are any microscope entry inside the dictionary if pydash.objects.has(md_dict, [ "ImageDocument", "Metadata", "Information", "Instrument", "Microscopes" ]): # check for detector ID try: self.ID = md_dict["ImageDocument"]["Metadata"]["Information"][ "Instrument"]["Microscopes"]["Microscope"]["Id"] except (KeyError, TypeError) as e: try: self.ID = md_dict["ImageDocument"]["Metadata"][ "Information"]["Instrument"]["Microscopes"][ "Microscope"]["@Id"] except (KeyError, TypeError) as e: print("Microscope ID not found :", e) self.ID = None # check for microscope system name try: self.Name = md_dict["ImageDocument"]["Metadata"][ "Information"]["Instrument"]["Microscopes"]["Microscope"][ "System"] except (KeyError, TypeError) as e: print("Microscope System Name not found :", e) self.Name = None
if file.endswith(ext): print("Processing CZI file:", file) cziname = file cziname_NUC = file[:-4] + "_onlyFL" cziname_TL = file[:-4] + "_onlyTL" # get the scaling from the CZI cziscale = czimd.CziScaling(os.path.join(basefolder, cziname)) pixels_physical_sizes = [1, cziscale.X, cziscale.Y] scale_forward = target_scaleXY / cziscale.X new_shapeXY = int(np.round(tilesize * scale_forward, 0)) # open a CZI instance to read and in parallel one to write with pyczi.open_czi(os.path.join(basefolder, file)) as czidoc_r: if use_tiles: tilecounter = 0 # create a "tile" by specifying the desired tile dimension and minimum required overlap tiler = AlmostEqualBorderFixedTotalAreaStrategy2D( total_tile_width=tilesize, total_tile_height=tilesize, min_border_width=8) # get the size of the bounding rectangle for the scene tiles = tiler.tile_rectangle( czidoc_r.scenes_bounding_rectangle[0])
#filename = r'/datadisk1/tuxedo/testpictures/Testdata_Zeiss/CZI_Testfiles/S=2_3x3_T=3_Z=4_CH=2.czi' #filename = r'/datadisk1/tuxedo/testpictures/Testdata_Zeiss/CZI_Testfiles/S=2_3x3_T=1_Z=4_CH=2.czi' #filename = r'/datadisk1/tuxedo/testpictures/Testdata_Zeiss/CZI_Testfiles/S=2_3x3_T=3_Z=1_CH=2.czi' #filename = r'/datadisk1/tuxedo/testpictures/Testdata_Zeiss/CZI_Testfiles/S=2_3x3_T=3_Z=4_CH=2.czi' #filename = r'/datadisk1/tuxedo/testpictures/Testdata_Zeiss/CZI_Testfiles/S=1_HE_Slide_RGB.czi' #filename = r'/datadisk1/tuxedo/testpictures/Testdata_Zeiss/CZI_Testfiles/Multiscene_CZI_3Scenes.czi' #filename = r'c:\Users\m1srh\Downloads\Overview.czi' #filename = r'd:\Testdata_Zeiss\LatticeLightSheet\LS_Mitosis_T=150-300.czi' #filename = r"D:\Testdata_Zeiss\CZI_Testfiles\strange_no_SizeC.czi" #filename = r"D:\Testdata_Zeiss\CZI_Testfiles\ab0451_CH1_scale_libCZI_issue.czi" # get the complete metadata at once as one big class mdata = czimd.CziMetadata(filename) # open the CZI document to read the czidoc = pyczi.open_czi(filename) # show all dimensions total_bbox = czidoc.total_bounding_box for k, v in total_bbox.items(): print(k, v) # get information about the scenes etc. sc_bbox = czidoc.scenes_bounding_rectangle total_rect = czidoc.total_bounding_rectangle pixeltype_ch = czidoc.get_channel_pixel_type(0) pixeltypes = czidoc.pixel_types print('Real Pixeltypes in CZI file : ', pixeltypes) # read a simple 2d image plane roi = (300, 300, 300, 600)
def __init__(self, filename: str) -> None: # get metadata dictionary using pylibCZIrw with pyczi.open_czi(filename) as czidoc: md_dict = czidoc.metadata # check for well information self.well_array_names = [] self.well_indices = [] self.well_position_names = [] self.well_colID = [] self.well_rowID = [] self.well_counter = [] self.scene_stageX = [] self.scene_stageY = [] try: # get S-Dimension SizeS = np.int(md_dict["ImageDocument"]["Metadata"]["Information"] ["Image"]["SizeS"]) print( "Trying to extract Scene and Well information if existing ...") # extract well information from the dictionary allscenes = md_dict["ImageDocument"]["Metadata"]["Information"][ "Image"]["Dimensions"]["S"]["Scenes"]["Scene"] # loop over all detected scenes for s in range(sizeS): if SizeS == 1: well = allscenes try: self.well_array_names.append(allscenes["ArrayName"]) except (KeyError, TypeError) as e: try: self.well_array_names.append(well["Name"]) except (KeyError, TypeError) as e: # print("Well Name not found :", e) try: self.well_array_names.append(well["@Name"]) except (KeyError, TypeError) as e: # print("Well @Name not found :", e) print("Well Name not found :", e, "Using A1 instead") self.well_array_names.append("A1") try: self.well_indices.append(allscenes["Index"]) except (KeyError, TypeError) as e: try: self.well_indices.append(allscenes["@Index"]) except (KeyError, TypeError) as e: print("Well Index not found :", e) self.well_indices.append(1) try: self.well_position_names.append(allscenes["Name"]) except (KeyError, TypeError) as e: try: self.well_position_names.append(allscenes["@Name"]) except (KeyError, TypeError) as e: print("Well Position Names not found :", e) self.well_position_names.append("P1") try: self.well_colID.append( np.int(allscenes["Shape"]["ColumnIndex"])) except (KeyError, TypeError) as e: print("Well ColumnIDs not found :", e) self.well_colID.append(0) try: self.well_rowID.append( np.int(allscenes["Shape"]["RowIndex"])) except (KeyError, TypeError) as e: print("Well RowIDs not found :", e) self.well_rowID.append(0) try: # count the content of the list, e.g. how many time a certain well was detected self.well_counter = Counter(self.well_array_names) except (KeyError, TypeError): self.well_counter.append(Counter({"A1": 1})) try: # get the SceneCenter Position sx = allscenes["CenterPosition"].split(",")[0] sy = allscenes["CenterPosition"].split(",")[1] self.scene_stageX.append(np.double(sx)) self.scene_stageY.append(np.double(sy)) except (TypeError, (KeyError, TypeError)) as e: print("Stage Positions XY not found :", e) self.scene_stageX.append(0.0) self.scene_stageY.append(0.0) if SizeS > 1: try: well = allscenes[s] self.well_array_names.append(well["ArrayName"]) except (KeyError, TypeError) as e: try: self.well_array_names.append(well["Name"]) except (KeyError, TypeError) as e: # print("Well Name not found :", e) try: self.well_array_names.append(well["@Name"]) except (KeyError, TypeError) as e: # print("Well @Name not found :", e) print("Well Name not found. Using A1 instead") self.well_array_names.append("A1") # get the well information try: self.well_indices.append(well["Index"]) except (KeyError, TypeError) as e: try: self.well_indices.append(well["@Index"]) except (KeyError, TypeError) as e: print("Well Index not found :", e) self.well_indices.append(None) try: self.well_position_names.append(well["Name"]) except (KeyError, TypeError) as e: try: self.well_position_names.append(well["@Name"]) except (KeyError, TypeError) as e: print("Well Position Names not found :", e) self.well_position_names.append(None) try: self.well_colID.append( np.int(well["Shape"]["ColumnIndex"])) except (KeyError, TypeError) as e: print("Well ColumnIDs not found :", e) self.well_colID.append(None) try: self.well_rowID.append( np.int(well["Shape"]["RowIndex"])) except (KeyError, TypeError) as e: print("Well RowIDs not found :", e) self.well_rowID.append(None) # count the content of the list, e.g. how many time a certain well was detected self.well_counter = Counter(self.well_array_names) # try: if isinstance(allscenes, list): try: # get the SceneCenter Position sx = allscenes[s]["CenterPosition"].split(",")[0] sy = allscenes[s]["CenterPosition"].split(",")[1] self.scene_stageX.append(np.double(sx)) self.scene_stageY.append(np.double(sy)) except (KeyError, TypeError) as e: print("Stage Positions XY not found :", e) self.scene_stageX.append(0.0) self.scene_stageY.append(0.0) if not isinstance(allscenes, list): self.scene_stageX.append(0.0) self.scene_stageY.append(0.0) # count the number of different wells self.number_wells = len(self.well_counter.keys()) except (KeyError, TypeError) as e: print("No valid Scene or Well information found:", e)
def __init__(self, filename: str) -> None: # get metadata dictionary using pylibCZIrw with pyczi.open_czi(filename) as czidoc: md_dict = czidoc.metadata # get detector information self.model = [] self.name = [] self.ID = [] self.modeltype = [] self.instrumentID = [] # check if there are any detector entries inside the dictionary if pydash.objects.has(md_dict, [ "ImageDocument", "Metadata", "Information", "Instrument", "Detectors" ]): if isinstance( md_dict["ImageDocument"]["Metadata"]["Information"] ["Instrument"]["Detectors"]["Detector"], list): num_detectors = len( md_dict["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: self.ID.append( md_dict["ImageDocument"]["Metadata"]["Information"] ["Instrument"]["Detectors"]["Detector"]["Id"]) except (KeyError, TypeError) as e: print("DetectorID not found :", e) self.ID.append(None) # check for detector Name try: self.name.append( md_dict["ImageDocument"]["Metadata"]["Information"] ["Instrument"]["Detectors"]["Detector"]["Name"]) except (KeyError, TypeError) as e: print("DetectorName not found :", e) self.name.append(None) # check for detector model try: self.model.append( md_dict["ImageDocument"]["Metadata"]["Information"] ["Instrument"]["Detectors"]["Detector"]["Manufacturer"] ["Model"]) except (KeyError, TypeError) as e: print("DetectorModel not found :", e) self.model.append(None) # check for detector modeltype try: self.modeltype.append( md_dict["ImageDocument"]["Metadata"]["Information"] ["Instrument"]["Detectors"]["Detector"]["Type"]) except (KeyError, TypeError) as e: print("DetectorType not found :", e) self.modeltype.append(None) if num_detectors > 1: for d in range(num_detectors): # check for detector ID try: self.ID.append( md_dict["ImageDocument"]["Metadata"]["Information"] ["Instrument"]["Detectors"]["Detector"][d]["Id"]) except (KeyError, TypeError) as e: print("DetectorID not found :", e) self.ID.append(None) # check for detector Name try: self.name.append( md_dict["ImageDocument"]["Metadata"]["Information"] ["Instrument"]["Detectors"]["Detector"][d]["Name"]) except (KeyError, TypeError) as e: print("DetectorName not found :", e) self.name.append(None) # check for detector model try: self.model.append( md_dict["ImageDocument"]["Metadata"]["Information"] ["Instrument"]["Detectors"]["Detector"][d] ["Manufacturer"]["Model"]) except (KeyError, TypeError) as e: print("DetectorModel not found :", e) self.model.append(None) # check for detector modeltype try: self.modeltype.append( md_dict["ImageDocument"]["Metadata"]["Information"] ["Instrument"]["Detectors"]["Detector"][d]["Type"]) except (KeyError, TypeError) as e: print("DetectorType not found :", e) self.modeltype.append(None)
def __init__(self, filename: str, dim2none: bool = False) -> None: # get metadata dictionary using pylibCZIrw with pyczi.open_czi(filename) as czidoc: md_dict = czidoc.metadata # get directory, filename, SW version and acquisition data self.info = CziInfo(filename) # get dimensions self.pyczi_dims = czidoc.total_bounding_box # get some additional metadata using aicspylibczi try: from aicspylibczi import CziFile # get the general CZI object using aicspylibczi aicsczi = CziFile(filename) self.aics_dimstring = aicsczi.dims self.aics_dims_shape = aicsczi.get_dims_shape() self.aics_size = aicsczi.size self.aics_ismosaic = aicsczi.is_mosaic() self.aics_dim_order, self.aics_dim_index, self.aics_dim_valid = self.get_dimorder( aicsczi.dims) self.aics_posC = self.aics_dim_order["C"] except ImportError as e: print("Use Fallback values because:", e) self.aics_dimstring = None self.aics_dims_shape = None self.aics_size = None self.aics_ismosaic = None self.aics_dim_order = None self.aics_dim_index = None self.aics_dim_valid = None self.aics_posC = None # get the pixel typed for all channels self.pixeltypes = czidoc.pixel_types self.isRGB = False # determine pixel type for CZI array by reading XML metadata self.pixeltype = md_dict["ImageDocument"]["Metadata"][ "Information"]["Image"]["PixelType"] # check if CZI is a RGB file if self.pixeltype in ["Bgr24", "Bgr48", "Bgr96Float"]: self.isRGB = True # determine pixel type for CZI array self.npdtype, self.maxvalue = self.get_dtype_fromstring( self.pixeltype) # get the dimensions and order self.image = CziDimensions(filename) # try to guess if the CZI is a mosaic file if self.image.SizeM is None or self.image.SizeM == 1: self.ismosaic = False else: self.ismosaic = True # get the bounding boxes self.bbox = CziBoundingBox(filename) # get information about channels self.channelinfo = CziChannelInfo(filename) # get scaling info self.scale = CziScaling(filename, dim2none=dim2none) # get objetive information self.objective = CziObjectives(filename) # get detector information self.detector = CziDetector(filename) # get detector information self.microscope = CziMicroscope(filename) # get information about sample carrier and wells etc. self.sample = CziSampleInfo(filename) # get additional metainformation self.add_metadata = CziAddMetaData(filename)
def __init__(self, filename: str) -> None: # get metadata dictionary using pylibCZIrw with pyczi.open_czi(filename) as czidoc: md_dict = czidoc.metadata self.NA = [] self.mag = [] self.ID = [] self.name = [] self.immersion = [] self.tubelensmag = [] self.nominalmag = [] # check if Instrument metadata actually exist if pydash.objects.has(md_dict, [ "ImageDocument", "Metadata", "Information", "Instrument", "Objectives" ]): # get objective data try: if isinstance( md_dict["ImageDocument"]["Metadata"]["Information"] ["Instrument"]["Objectives"]["Objective"], list): num_obj = len( md_dict["ImageDocument"]["Metadata"]["Information"] ["Instrument"]["Objectives"]["Objective"]) else: num_obj = 1 except (KeyError, TypeError) as e: num_obj = 0 # no objective found # if there is only one objective found if num_obj == 1: try: self.name.append( md_dict["ImageDocument"]["Metadata"]["Information"] ["Instrument"]["Objectives"]["Objective"]["Name"]) except (KeyError, TypeError) as e: print("No Objective Name :", e) self.name.append(None) try: self.immersion = md_dict["ImageDocument"]["Metadata"][ "Information"]["Instrument"]["Objectives"][ "Objective"]["Immersion"] except (KeyError, TypeError) as e: print("No Objective Immersion :", e) self.immersion = None try: self.NA = np.float( md_dict["ImageDocument"]["Metadata"]["Information"] ["Instrument"]["Objectives"]["Objective"]["LensNA"]) except (KeyError, TypeError) as e: print("No Objective NA :", e) self.NA = None try: self.ID = md_dict["ImageDocument"]["Metadata"][ "Information"]["Instrument"]["Objectives"][ "Objective"]["Id"] except (KeyError, TypeError) as e: print("No Objective ID :", e) self.ID = None try: self.tubelensmag = np.float( md_dict["ImageDocument"]["Metadata"]["Information"] ["Instrument"]["TubeLenses"]["TubeLens"] ["Magnification"]) except (KeyError, TypeError) as e: print("No Tubelens Mag. :", e, "Using Default Value = 1.0.") self.tubelensmag = 1.0 try: self.nominalmag = np.float( md_dict["ImageDocument"]["Metadata"]["Information"] ["Instrument"]["Objectives"]["Objective"] ["NominalMagnification"]) except (KeyError, TypeError) as e: print("No Nominal Mag.:", e, "Using Default Value = 1.0.") self.nominalmag = 1.0 try: if self.tubelensmag is not None: self.mag = self.nominalmag * self.tubelensmag if self.tubelensmag is None: print( "Using Tublens Mag = 1.0 for calculating Objective Magnification." ) self.mag = self.nominalmag * 1.0 except (KeyError, TypeError) as e: print("No Objective Magnification :", e) self.mag = None if num_obj > 1: for o in range(num_obj): try: self.name.append( md_dict["ImageDocument"]["Metadata"]["Information"] ["Instrument"]["Objectives"]["Objective"][o] ["Name"]) except (KeyError, TypeError) as e: print("No Objective Name :", e) self.name.append(None) try: self.immersion.append( md_dict["ImageDocument"]["Metadata"]["Information"] ["Instrument"]["Objectives"]["Objective"][o] ["Immersion"]) except (KeyError, TypeError) as e: print("No Objective Immersion :", e) self.immersion.append(None) try: self.NA.append( np.float(md_dict["ImageDocument"]["Metadata"] ["Information"]["Instrument"] ["Objectives"]["Objective"][o]["LensNA"])) except (KeyError, TypeError) as e: print("No Objective NA :", e) self.NA.append(None) try: self.ID.append( md_dict["ImageDocument"]["Metadata"]["Information"] ["Instrument"]["Objectives"]["Objective"][o]["Id"]) except (KeyError, TypeError) as e: print("No Objective ID :", e) self.ID.append(None) try: self.tubelensmag.append( np.float( md_dict["ImageDocument"]["Metadata"] ["Information"]["Instrument"]["TubeLenses"] ["TubeLens"][o]["Magnification"])) except (KeyError, TypeError) as e: print("No Tubelens Mag. :", e, "Using Default Value = 1.0.") self.tubelensmag.append(1.0) try: self.nominalmag.append( np.float( md_dict["ImageDocument"]["Metadata"] ["Information"]["Instrument"]["Objectives"] ["Objective"][o]["NominalMagnification"])) except (KeyError, TypeError) as e: print("No Nominal Mag. :", e, "Using Default Value = 1.0.") self.nominalmag.append(1.0) try: if self.tubelensmag is not None: self.mag.append(self.nominalmag[o] * self.tubelensmag[o]) if self.tubelensmag is None: print( "Using Tublens Mag = 1.0 for calculating Objective Magnification." ) self.mag.append(self.nominalmag[o] * 1.0) except (KeyError, TypeError) as e: print("No Objective Magnification :", e) self.mag.append(None)
def get_metadata_czi(filename, dim2none=False, 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 convert_scunit: convert scale unit string from 'µm' to 'micron', defaults to False :type convert_scunit: bool, optional :return: metadata, metadata_add - dictionaries with the relevant CZI metainformation :rtype: dict """ # get metadata dictionary using pylibCZIrw czidoc = pyczi.open_czi(filename) metadatadict_czi = xmltodict.parse(czidoc.raw_metadata) # get czi object aicspylibczi aicsczi = CziFile(filename) # 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' # get additional data by using aicspylibczi directly metadata['aicsczi_dims'] = aicsczi.dims metadata['aicsczi_dims_shape'] = aicsczi.get_dims_shape() metadata['aicsczi_size'] = aicsczi.size metadata['isMosaic'] = aicsczi.is_mosaic() print('CZI is Mosaic :', metadata['isMosaic']) # get the dimensions of the bounding boxes for the scenes # metadata['BBoxes_Scenes'] = getbboxes_allscenes(czi, metadata, numscenes=metadata['SizeS']) metadata['bbox_all_scenes'] = aicsczi.get_all_scene_bounding_boxes() if aicsczi.is_mosaic(): metadata[ 'bbox_all_mosaic_scenes'] = aicsczi.get_all_mosaic_scene_bounding_boxes( ) metadata[ 'bbox_all_mosaic_tiles'] = aicsczi.get_all_mosaic_tile_bounding_boxes( ) metadata['bbox_all_tiles'] = aicsczi.get_all_tile_bounding_boxes() # get additional data by using pylibczirw directly metadata['pyczi_dims'] = czidoc.total_bounding_box metadata['pyczi_bbox_scenes'] = czidoc.scenes_bounding_rectangle metadata['pyczi_total_rect'] = czidoc.total_bounding_rectangle # check which dimension exist inside this CZI file metadata = checkdims_czi(czidoc, metadata) # determine pixel type for CZI array metadata['NumPy.dtype'] = {} for ch, px in czidoc.pixel_types.items(): metadata['NumPy.dtype'][ch] = get_dtype_fromstring(px) if czidoc._is_rgb(czidoc.get_channel_pixel_type(0)): metadata['isRGB'] = True #if 'A' in aicsczi.dims: # metadata['isRGB'] = True print('CZI is RGB :', metadata['isRGB']) # determine pixel type for CZI array by reading XML metadata try: metadata['PixelType'] = metadatadict_czi['ImageDocument']['Metadata'][ 'Information']['Image']['PixelType'] except KeyError as e: print('No PixelType :', e) metadata['PixelType'] = None try: metadata['SizeX'] = np.int( metadatadict_czi['ImageDocument']['Metadata']['Information'] ['Image']['SizeX']) except KeyError as e: print('No X Dimension :', e) metadata['SizeX'] = None try: metadata['SizeY'] = np.int( metadatadict_czi['ImageDocument']['Metadata']['Information'] ['Image']['SizeY']) except KeyError as e: print('No Y Dimension :', e) metadata['SizeY'] = None try: metadata['SizeZ'] = np.int( metadatadict_czi['ImageDocument']['Metadata']['Information'] ['Image']['SizeZ']) except KeyError as e: print('No Z Dimension :', 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 KeyError as e: print('No C Dimension :', e) if dim2none: metadata['SizeC'] = None if not dim2none: metadata['SizeC'] = 1 # get dimension of consitent 5D stack using AICSImageio #aics_img = AICSImage(filename) #metadata['czi_dims5D_aics'] = aics_img.dims.order #metadata['czi_shape5D_aics'] = aics_img.dims.shape #metadata['czi_dict5D_aics'] = aics_img.dims.__dict__ # 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('Channel shortname not found :', e) try: channels.append( metadatadict_czi['ImageDocument']['Metadata'] ['DisplaySetting']['Channels']['Channel']['DyeName']) except KeyError as e: print('Channel dye not found :', e) channels.append('Dye-CH1') # get channel name try: channels_names.append( metadatadict_czi['ImageDocument']['Metadata']['DisplaySetting'] ['Channels']['Channel']['Name']) except KeyError as e: try: channels_names.append( metadatadict_czi['ImageDocument']['Metadata'] ['DisplaySetting']['Channels']['Channel']['@Name']) except KeyError as e: print('Channel name found :', 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('Channel color not found :', 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('Channel shortname not found :', e) try: channels.append(metadatadict_czi['ImageDocument'] ['Metadata']['DisplaySetting']['Channels'] ['Channel'][ch]['DyeName']) except KeyError as e: print('Channel dye not found :', 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: try: channels_names.append( metadatadict_czi['ImageDocument']['Metadata'] ['DisplaySetting']['Channels']['Channel'][ch]['@Name']) except KeyError as e: print('Channel name not found :', 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('Channel color not found :', 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 KeyError as e: print('No T Dimension :', 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 KeyError as e: print('No M Dimension :', 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 KeyError as e: print('No B Dimension :', 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 KeyError as e: print('No S Dimension :', 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 KeyError as e: print('No H Dimension :', 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 KeyError as e: print('No I Dimension :', 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 KeyError as e: print('No V Dimension :', e) if dim2none: metadata['SizeV'] = None if not dim2none: metadata['SizeV'] = 1 # get the XY scaling information try: 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, TypeError) as e: print('Error extracting XY ScaleUnit :', e) metadata['XScaleUnit'] = None metadata['YScaleUnit'] = None except (KeyError, TypeError) as e: print('Error extracting XY Scale :', e) # get the Z scaling information 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 (IndexError, KeyError, TypeError) as e: print('Error extracting Z ScaleUnit :', e) metadata['ZScaleUnit'] = metadata['XScaleUnit'] except (IndexError, KeyError, TypeError) as e: print('Error extracting Z Scale :', 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'] # convert scale unit to avoid encoding problems if convert_scunit: if metadata['XScaleUnit'] == 'µm': metadata['XScaleUnit'] = 'micron' if metadata['YScaleUnit'] == 'µm': metadata['YScaleUnit'] = 'micron' if metadata['ZScaleUnit'] == 'µm': metadata['ZScaleUnit'] = 'micron' # 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 # check if Instrument metadata actually exist if pydash.objects.has( metadatadict_czi, ['ImageDocument', 'Metadata', 'Information', 'Instrument']): if metadatadict_czi['ImageDocument']['Metadata']['Information'][ 'Instrument'] is not None: # get objective data 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 # 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('No Objective Name :', e) metadata['ObjName'].append(None) try: metadata['ObjImmersion'] = \ metadatadict_czi['ImageDocument']['Metadata']['Information']['Instrument']['Objectives'][ 'Objective']['Immersion'] except (KeyError, TypeError) as e: print('No Objective Immersion :', e) metadata['ObjImmersion'] = None try: metadata['ObjNA'] = np.float( metadatadict_czi['ImageDocument']['Metadata'] ['Information']['Instrument']['Objectives'] ['Objective']['LensNA']) except (KeyError, TypeError) as e: print('No Objective NA :', e) metadata['ObjNA'] = None try: metadata['ObjID'] = \ metadatadict_czi['ImageDocument']['Metadata']['Information']['Instrument']['Objectives'][ 'Objective']['Id'] except (KeyError, TypeError) as e: print('No Objective ID :', e) metadata['ObjID'] = None try: metadata['TubelensMag'] = np.float( metadatadict_czi['ImageDocument']['Metadata'] ['Information']['Instrument']['TubeLenses']['TubeLens'] ['Magnification']) except (KeyError, TypeError) as e: print('No Tubelens Mag. :', e, 'Using Default Value = 1.0.') metadata['TubelensMag'] = 1.0 try: metadata['ObjNominalMag'] = np.float( metadatadict_czi['ImageDocument']['Metadata'] ['Information']['Instrument']['Objectives'] ['Objective']['NominalMagnification']) except (KeyError, TypeError) as e: print('No Nominal Mag.:', e, 'Using Default Value = 1.0.') metadata['ObjNominalMag'] = 1.0 try: if metadata['TubelensMag'] is not None: metadata['ObjMag'] = metadata[ 'ObjNominalMag'] * metadata['TubelensMag'] if metadata['TubelensMag'] is None: print( 'Using Tublens Mag = 1.0 for calculating Objective Magnification.' ) metadata['ObjMag'] = metadata['ObjNominalMag'] * 1.0 except (KeyError, TypeError) as e: print('No Objective Magnification :', 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('No Objective Name :', e) metadata['ObjName'].append(None) try: metadata['ObjImmersion'].append( metadatadict_czi['ImageDocument']['Metadata'] ['Information']['Instrument']['Objectives'] ['Objective'][o]['Immersion']) except KeyError as e: print('No Objective Immersion :', 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('No Objective NA :', e) metadata['ObjNA'].append(None) try: metadata['ObjID'].append( metadatadict_czi['ImageDocument']['Metadata'] ['Information']['Instrument']['Objectives'] ['Objective'][o]['Id']) except KeyError as e: print('No Objective ID :', 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('No Tubelens Mag. :', e, 'Using Default Value = 1.0.') 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('No Nominal Mag. :', e, 'Using Default Value = 1.0.') 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( 'Using Tublens Mag = 1.0 for calculating Objective Magnification.' ) metadata['ObjMag'].append( metadata['ObjNominalMag'][o] * 1.0) except KeyError as e: print('No Objective Magnification :', 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: print('DetectorID not found :', 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: print('DetectorName not found :', 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: print('DetectorModel not found :', 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: print('DetectorType not found :', 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: print('DetectorID not found :', 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: print('DetectorName not found :', 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: print('DetectorModel not found :', 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: print('DetectorType not found :', 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: try: metadata['Well_ArrayNames'].append(well['Name']) except KeyError as e: # print('Well Name not found :', e) try: metadata['Well_ArrayNames'].append(well['@Name']) except KeyError as e: # print('Well @Name not found :', e) print('Well Name not found :', e, 'Using A1 instead') metadata['Well_ArrayNames'].append('A1') try: metadata['Well_Indices'].append(allscenes['Index']) except KeyError as e: try: metadata['Well_Indices'].append(allscenes['@Index']) except KeyError as e: print('Well Index not found :', e) metadata['Well_Indices'].append(1) try: metadata['Well_PositionNames'].append(allscenes['Name']) except KeyError as e: try: metadata['Well_PositionNames'].append( allscenes['@Name']) except KeyError as e: print('Well Position Names not found :', e) metadata['Well_PositionNames'].append('P1') try: metadata['Well_ColId'].append( np.int(allscenes['Shape']['ColumnIndex'])) except KeyError as e: print('Well ColumnIDs not found :', e) metadata['Well_ColId'].append(0) try: metadata['Well_RowId'].append( np.int(allscenes['Shape']['RowIndex'])) except KeyError as e: print('Well RowIDs not found :', 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: 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 (TypeError, KeyError) as e: print('Stage Positions XY not found :', 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: try: metadata['Well_ArrayNames'].append(well['Name']) except KeyError as e: # print('Well Name not found :', e) try: metadata['Well_ArrayNames'].append(well['@Name']) except KeyError as e: # print('Well @Name not found :', e) print('Well Name not found. Using A1 instead') metadata['Well_ArrayNames'].append('A1') # get the well information try: metadata['Well_Indices'].append(well['Index']) except KeyError as e: try: metadata['Well_Indices'].append(well['@Index']) except KeyError as e: print('Well Index not found :', e) metadata['Well_Indices'].append(None) try: metadata['Well_PositionNames'].append(well['Name']) except KeyError as e: try: metadata['Well_PositionNames'].append(well['@Name']) except KeyError as e: print('Well Position Names not found :', e) metadata['Well_PositionNames'].append(None) try: metadata['Well_ColId'].append( np.int(well['Shape']['ColumnIndex'])) except KeyError as e: print('Well ColumnIDs not found :', e) metadata['Well_ColId'].append(None) try: metadata['Well_RowId'].append( np.int(well['Shape']['RowIndex'])) except KeyError as e: print('Well RowIDs not found :', 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('Stage Positions XY not found :', 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) # get additional meta data about the experiment etc. metadata_add = get_additional_metadata_czi(metadatadict_czi) return metadata, metadata_add
def __init__(self, filename: str) -> None: # get metadata dictionary using pylibCZIrw with pyczi.open_czi(filename) as czidoc: md_dict = czidoc.metadata # create empty lists for channel related information channels = [] channels_names = [] channels_colors = [] channels_contrast = [] channels_gamma = [] try: sizeC = np.int(md_dict["ImageDocument"]["Metadata"]["Information"] ["Image"]["SizeC"]) except (KeyError, TypeError) as e: sizeC = 1 # in case of only one channel if sizeC == 1: # get name for dye try: channels.append( md_dict["ImageDocument"]["Metadata"]["DisplaySetting"] ["Channels"]["Channel"]["ShortName"]) except (KeyError, TypeError) as e: print("Channel shortname not found :", e) try: channels.append( md_dict["ImageDocument"]["Metadata"]["DisplaySetting"] ["Channels"]["Channel"]["DyeName"]) except (KeyError, TypeError) as e: print("Channel dye not found :", e) channels.append("Dye-CH1") # get channel name try: channels_names.append( md_dict["ImageDocument"]["Metadata"]["DisplaySetting"] ["Channels"]["Channel"]["Name"]) except (KeyError, TypeError) as e: try: channels_names.append( md_dict["ImageDocument"]["Metadata"]["DisplaySetting"] ["Channels"]["Channel"]["@Name"]) except (KeyError, TypeError) as e: print("Channel name found :", e) channels_names.append("CH1") # get channel color try: channels_colors.append( md_dict["ImageDocument"]["Metadata"]["DisplaySetting"] ["Channels"]["Channel"]["Color"]) except (KeyError, TypeError) as e: print("Channel color not found :", e) channels_colors.append("#80808000") # get contrast setting fro DisplaySetting try: low = np.float( md_dict["ImageDocument"]["Metadata"]["DisplaySetting"] ["Channels"]["Channel"]["Low"]) except (KeyError, TypeError) as e: low = 0.1 try: high = np.float( md_dict["ImageDocument"]["Metadata"]["DisplaySetting"] ["Channels"]["Channel"]["High"]) except (KeyError, TypeError) as e: high = 0.5 channels_contrast.append([low, high]) # get the gamma values try: channels_gamma.append( np.float( md_dict["ImageDocument"]["Metadata"]["DisplaySetting"] ["Channels"]["Channel"]["Gamma"])) except (KeyError, TypeError) as e: channels_gamma.append(0.85) # in case of two or more channels if sizeC > 1: # loop over all channels for ch in range(sizeC): # get name for dyes try: channels.append( md_dict["ImageDocument"]["Metadata"]["DisplaySetting"] ["Channels"]["Channel"][ch]["ShortName"]) except (KeyError, TypeError) as e: print("Channel shortname not found :", e) try: channels.append(md_dict["ImageDocument"]["Metadata"] ["DisplaySetting"]["Channels"] ["Channel"][ch]["DyeName"]) except (KeyError, TypeError) as e: print("Channel dye not found :", e) channels.append("Dye-CH" + str(ch)) # get channel names try: channels_names.append( md_dict["ImageDocument"]["Metadata"]["DisplaySetting"] ["Channels"]["Channel"][ch]["Name"]) except (KeyError, TypeError) as e: try: channels_names.append( md_dict["ImageDocument"]["Metadata"] ["DisplaySetting"]["Channels"]["Channel"][ch] ["@Name"]) except (KeyError, TypeError) as e: print("Channel name not found :", e) channels_names.append("CH" + str(ch)) # get channel colors try: channels_colors.append( md_dict["ImageDocument"]["Metadata"]["DisplaySetting"] ["Channels"]["Channel"][ch]["Color"]) except (KeyError, TypeError) as e: print("Channel color not found :", e) # use grayscale instead channels_colors.append("80808000") # get contrast setting fro DisplaySetting try: low = np.float( md_dict["ImageDocument"]["Metadata"]["DisplaySetting"] ["Channels"]["Channel"][ch]["Low"]) except (KeyError, TypeError) as e: low = 0.0 try: high = np.float( md_dict["ImageDocument"]["Metadata"]["DisplaySetting"] ["Channels"]["Channel"][ch]["High"]) except (KeyError, TypeError) as e: high = 0.5 channels_contrast.append([low, high]) # get the gamma values try: channels_gamma.append( np.float(md_dict["ImageDocument"]["Metadata"] ["DisplaySetting"]["Channels"]["Channel"][ch] ["Gamma"])) except (KeyError, TypeError) as e: channels_gamma.append(0.85) # write channels information (as lists) into metadata dictionary self.shortnames = channels self.names = channels_names self.colors = channels_colors self.clims = channels_contrast self.gamma = channels_gamma