def get_dimension_only(imagefile): # get OME-XML and change the encoding to UTF-8 omexml = bioformats.get_omexml_metadata(imagefile) new_omexml = omexml.encode('utf-8') rdr = bioformats.get_image_reader(None, path=imagefile) # read total number of image series totalseries = rdr.rdr.getSeriesCount() # get dimensions for CTZXY md = bioformats.OMEXML(new_omexml) pixels = md.image(IMAGEID).Pixels SizeC = pixels.SizeC SizeT = pixels.SizeT SizeZ = pixels.SizeZ SizeX = pixels.SizeX SizeY = pixels.SizeY print 'Series: ', totalseries, 'T: ', SizeT, 'Z: ', SizeZ, 'C: ', SizeC, 'X: ', SizeX, 'Y: ', SizeY # usually the x-axis of an image is from left --> right and y from top --> bottom # in order to be compatible with numpy arrays XY are switched # for numpy arrays the 2st axis are columns (top --> down) = Y-Axis for an image sizes = [totalseries, SizeT, SizeZ, SizeC, SizeY, SizeX] return sizes
def get_metadata_lif(filename): check_VM() xml_string = bf.get_omexml_metadata(filename).encode("utf-8") metadata = [] size_tags = ['Size' + c for c in 'XYZCT'] res_tags = ['PhysicalSize' + c for c in 'XYZ'] metadata_root = et.ElementTree.fromstring(xml_string) for child in metadata_root: if child.tag.endswith('Image'): aux_dict = {} aux_dict['Name'] = child.attrib['Name'] for grandchild in child: if grandchild.tag.endswith('AcquisitionDate'): aux_dict['AcquisitionDate'] = grandchild.text elif grandchild.tag.endswith('InstrumentRef'): instrumentID = grandchild.attrib['ID'] for aux_child in metadata_root: if aux_child.tag.endswith('Instrument'): if aux_child.attrib['ID'] == instrumentID: for aux_grandchild in aux_child: if aux_grandchild.tag.endswith('Microscope'): aux_dict['Instrument'] = aux_grandchild.attrib['Model'] if grandchild.tag.endswith('Pixels'): att = grandchild.attrib for tag in size_tags: aux_dict[tag] = int(att[tag]) for tag in res_tags: aux_dict[tag] = float(att[tag]) metadata.append(aux_dict) return json.dumps(metadata)
def __init__(self, imgfile, output_path): self.imgfile = imgfile try: self.image = I.ImarisImage(self.imgfile) if not os.path.isdir(output_path): raise IOError('Invalid output directory: ', output_path) else: # create unique output directory from image filename filename = basename(imgfile) new_folder = splitext(filename)[0] image_folder = join(output_path, new_folder) if not os.path.isdir(image_folder): os.makedirs(image_folder) self.output_folder = image_folder try: javabridge.start_vm(run_headless=True, class_path=bioformats.JARS) javabridge.attach() except Exception as e: raise (e) javabridge.attach() self.basicmeta = javabridge.jutil.to_string( bioformats.formatreader.make_iformat_reader_class().getMetadata(bioformats.ImageReader(imgfile).rdr)).split(',') self.basicmeta = sorted(self.basicmeta) self.omemeta = bioformats.get_omexml_metadata(imgfile).split("></") self.omemeta1 = self.omemeta[0].split(".xsd") self.omemeta2 = self.omemeta[1:] #javabridge.detach() except Exception as e: raise (e)
def readZPositions(stk_files): # the only entry parameter for this function is a list with # the stk files print('\n\t\treading z-values... ') javabridge.start_vm(class_path=bioformats.JARS) zs = [] # array with z-positions ts = [] # array with time point (got from data files) print('starting loop...') for file_path in stk_files: print('reading file: {}'.format(file_path)) md = bioformats.get_omexml_metadata(file_path) ome = bioformats.OMEXML(md) # create an instance of an image to read z-position zp = ome.image().Pixels.Plane().get_PositionZ() time = int(file_path[:-4].split('t')[-1]) zs.append(zp) ts.append(time) z_offsets = np.array([item - min(np.array(zs)) for item in zs]) javabridge.kill_vm() return np.array(zs), np.array(ts), z_offsets
def metadata(filename, array_order=DEFAULT_DIM_ORDER): """Get metadata from a BioFormats file. Parameters ---------- filename : string The path to a BioFormats File. array_order : string The order of the dimensions in the multidimensional array. Valid orders are a permutation of "tzyxc" for time, the three spatial dimensions, and channels. Returns ------- names : list of string The name of each image series. sizes : list of tuple of int The pixel size in the specified order of each series. resolutions : list of tuple of float The resolution of each series in the order given by `array_order`. Time and channel dimensions are ignored. """ if not VM_STARTED: start() if VM_KILLED: raise RuntimeError("The Java Virtual Machine has already been " "killed, and cannot be restarted. See the " "python-javabridge documentation for more " "information. You must restart your program " "and try again.") md_string = bf.get_omexml_metadata(filename) return parse_xml_metadata(md_string, array_order)
def _start_lif_reader(self): jv.start_vm(class_path=bf.JARS) log_level = 'ERROR' # reduce log level # currently does not work in new conda environment #rootLoggerName = jv.get_static_field("org/slf4j/Logger", "ROOT_LOGGER_NAME", "Ljava/lang/String;") #rootLogger = jv.static_call("org/slf4j/LoggerFactory", "getLogger", "(Ljava/lang/String;)Lorg/slf4j/Logger;", rootLoggerName) #logLevel = jv.get_static_field("ch/qos/logback/classic/Level", log_level, "Lch/qos/logback/classic/Level;") #jv.call(rootLogger, "setLevel", "(Lch/qos/logback/classic/Level;)V", logLevel) self.ir = bf.ImageReader(self.lif_file_path, perform_init=True) mdroot = et.ElementTree.fromstring(bf.get_omexml_metadata(self.lif_file_path)) mds = list(map(lambda e: e.attrib, mdroot.iter('{http://www.openmicroscopy.org/Schemas/OME/2016-06}Pixels'))) # lif can contain multiple images, select one that is likely to be the timeseries self.metadata = None self.lif_stack_idx = 0 for idx, md in enumerate(mds): if int(md['SizeT']) > 1: self.lif_stack_idx = idx self.metadata = md if not self.metadata: raise ValueError('lif does not contain an image with sizeT > 1')
def readBioFormatsMeta(fn): """Reads meta data out of bioformats format. .. note:: Changes system default encoding to UTF8. Args: fn (str): Path to file. Returns: OMEXML: meta data of all data. """ #Change system encoding to UTF 8 reload(sys) sys.setdefaultencoding('UTF8') #Load and convert to utf8 meta=bioformats.get_omexml_metadata(path=fn) meta=meta.decode().encode('utf-8') meta2 = bioformats.OMEXML(meta) return meta2
def __enter__(self): javabridge.start_vm(class_path=bioformats.JARS, run_headless=True) self.reader = bioformats.ImageReader(self.path) self.metadatastr = bioformats.get_omexml_metadata(self.path) self.metadata = ETree.fromstring(self.metadatastr.encode('utf-8')) self.initialize() return self
def ROI_crop(coordinates, diameter): # Call JavaBridge Bioformat Plugin VM_STARTED = False VM_KILLED = False DEFAULT_DIM_ORDER = 'XYZTC' BF2NP_DTYPE = { 0: np.int8, 1: np.uint8, 2: np.int16, 3: np.uint16, 4: np.int32, 5: np.uint32, 6: np.float32, 7: np.double } # Start Java virtual machine JVstart() for point in coordinates: filename = 'view'+str(point[0])+'ids' md = bf.get_omexml_metadata(filename) # Parse XML string into XML object xml = ET.ElementTree(ET.fromstring(md)) metadata=parse_xml_metadata_IDS(xml) rdr = bf.ImageReader(filename, perform_init=True) image=np.empty(metadata['format'][2]) z=100 a=rdr.read(z=z,c=1) plt.imshow(a,cmap=cm.gray) plt.show() # End Java virtual machine JVdone()
def __init__(self, dv_path, tag_path=None, cache_all=True, speak=True): self.dv_path = dv_path self.tag_path = tag_path self.cache_all = cache_all javabridge.start_vm(class_path=bioformats.JARS) if speak: print('Getting DV metadata....') self.meta_str = bioformats.get_omexml_metadata(path=self.dv_path) if speak: print('Solving metadata...') self.meta_xml = bioformats.omexml.OMEXML(self.meta_str) if cache_all: if speak: print('Caching all images') self.cache_image = self.__read_image() else: self.cache_image = np.empty(0) self.reader = bioformats.get_image_reader(None, self.dv_path) if tag_path is not None: tmp = sio.loadmat(tag_path)['tag'] if len(tmp.shape) < 3: tmp = np.reshape(tmp, newshape=(1, tmp.shape[0], tmp.shape[1])) self.tags = tmp.astype(np.int32) else: self.tags = np.empty(0)
def metadata(file_name): """Read the meta data and return the OME metadata object. """ JVM().start() meta = bf.get_omexml_metadata(file_name) return bf.omexml.OMEXML(meta)
def _loadBioformats(self, filename): #from PYME.IO.FileUtils import readTiff from PYME.IO.DataSources import BioformatsDataSource try: import bioformats except ImportError: logger.exception( 'Error importing bioformats - is the python-bioformats module installed?' ) raise #mdfn = self.FindAndParseMetadata(filename) print("Bioformats:loading data") self.dataSource = BioformatsDataSource.DataSource(filename, None) self.mdh = MetaDataHandler.NestedClassMDHandler(MetaData.BareBones) print("Bioformats:loading metadata") OMEXML = bioformats.get_omexml_metadata(filename).encode('utf8') print("Bioformats:parsing metadata") OMEmd = MetaDataHandler.OMEXMLMDHandler(OMEXML) self.mdh.copyEntriesFrom(OMEmd) print("Bioformats:done") print(self.dataSource.shape) self.dataSource = BufferedDataSource.DataSource( self.dataSource, min(self.dataSource.getNumSlices(), 50)) self.data = self.dataSource #this will get replaced with a wrapped version print(self.data.shape) #from PYME.ParallelTasks.relativeFiles import getRelFilename self.seriesName = getRelFilename(filename) self.mode = 'default'
def save_images(self): """Saves the individual images as a npy file 2D might have more acquisitions +/- focal plane, (usually 3 images). focal_plane_idx corresponds to the plane to consider. Mid-plane is the one in focus and the +/- on either side would be blurred. For 2D acquisitions, this is stored along the Z dimension. How is this handled for 3D acquisitions? """ if not os.path.exists(self.lif_fname): raise FileNotFoundError("LIF file doesn't exist at:", self.lif_fname) os.makedirs(self.split_dir, exist_ok=True) jv.start_vm(class_path=bf.JARS, max_heap_size='8G') metadata = bf.get_omexml_metadata(self.lif_fname) omexml_object = bf.OMEXML(metadata) num_channels = omexml_object.image().Pixels.channel_count num_samples = omexml_object.get_image_count() num_timepoints = omexml_object.image().Pixels.SizeT num_pix_z = omexml_object.image().Pixels.SizeZ size_x_um = omexml_object.image().Pixels.PhysicalSizeX size_y_um = omexml_object.image().Pixels.PhysicalSizeY size_z_um = omexml_object.image().Pixels.PhysicalSizeZ reader = bf.ImageReader(self.lif_fname, perform_init=True) records = [] for timepoint_idx in range(num_timepoints): timepoint_dir = os.path.join(self.split_dir, 'timepoint_{}'.format(timepoint_idx)) os.makedirs(timepoint_dir, exist_ok=True) for channel_idx in range(num_channels): channel_dir = os.path.join(timepoint_dir, 'channel_{}'.format(channel_idx)) os.makedirs(channel_dir, exist_ok=True) for sample_idx in range(15, 412): # num_samples cur_records = self.save_each_image(reader, num_pix_z, channel_dir, timepoint_idx, channel_idx, sample_idx, size_x_um, size_y_um, size_z_um) records.extend(cur_records) msg = 'Wrote files for tp:{}, channel:{}'.format( timepoint_idx, channel_idx) self._log_info(msg) df = pd.DataFrame.from_records(records, columns=[ 'timepoint', 'channel_num', 'sample_num', 'slice_num', 'fname', 'size_x_microns', 'size_y_microns', 'size_z_microns' ]) metadata_fname = os.path.join(self.split_dir, 'split_images_info.csv') df.to_csv(metadata_fname, sep=',') jv.kill_vm()
def extract_meta_bioformats(filepath, metadata=dict()): omexmlstr = bioformats.get_omexml_metadata(filepath) o = bioformats.OMEXML(omexmlstr) x = o.image().Pixels metadata['size_Z'] = x.SizeZ metadata['size_T'] = x.SizeT metadata['scale'] = x.PhysicalSizeX return metadata
def getImageInfo(filename): md = bf.get_omexml_metadata(filename) ome = bf.OMEXML(md) pixels = ome.image().Pixels pT = pixels.SizeT pX = pixels.SizeX pY = pixels.SizeY return pT, pX, pY
def get_meta(input_file_path, output_path, **kwargs): """ Extract specific metadata typically used in bio-image analysis. Also outputs a preview image to the output directory. Parameters ---------- input_file_path: str Input file path output_path: str Returns ------- meta: [dict] List of dicts containing with keys and values for specific metadata """ pix_exc = set(["id", "significantbits", "bigendian", "interleaved"]) channel_exc = set(["color", "id", "color", "contrastmethod", "fluor", "ndfilter", "illuminationtype", "name", "pockelcellsetting", "acquisitionmode"]) input_fname, ext = os.path.splitext(os.path.basename(input_file_path)) if ext[1:] not in bioformats.READABLE_FORMATS: logger.debug("Unsupported format: %s.%s" % (input_fname, ext)) return omexml = bioformats.get_omexml_metadata(input_file_path).encode('utf-8') meta_xml = et.fromstring(omexml) meta = list() for i, img_meta in enumerate(meta_xml.iter(IMAGE)): smeta = dict() output_file_path = os.path.join(output_path, input_fname+"_s%s.png" % i) logger.debug("Generating series %s preview from image: %s" % (i, input_fname+ext)) img = previewimage.get_preview_image(input_file_path, omexml, series=i) logger.debug("Saving series %s preview from image: %s" % (i, input_fname+ext)) previewimage.save_image(img, output_file_path, overwrite=True) logger.debug("Extracting metadata for series %s preview from image: %s" % (i, input_fname+ext)) smeta['id'] = img_meta.attrib['ID'] smeta['name'] = img_meta.attrib['Name'] smeta['previewImage'] = output_file_path for pix_meta in img_meta.iter(PIXEL): for k, v in pix_meta.attrib.iteritems(): if k.lower() not in pix_exc: smeta[k.lower()] = v for c, channel_meta in enumerate(pix_meta.iter(CHANNEL)): for kc, vc in channel_meta.attrib.iteritems(): if kc.lower() not in channel_exc: if kc.lower() not in smeta: smeta[kc.lower()] = ["Channel %s: %s" % (c, vc)] else: smeta[kc.lower()].append("Channel %s: %s" % (c, vc)) meta.append(smeta) return meta
def loadBioMetaFromFile(filepath) -> BioMeta: biometa = BioMeta() try: biometa.unparsed = bioformats.get_omexml_metadata(filepath) biometa.metadata = BeautifulSoup(biometa.unparsed, "xml") except Exception as e: raise e return biometa
def getImageShape(path): xmlimage=bf.get_omexml_metadata(path=path) metadata= bf.OMEXML(xmlimage) NX= metadata.image().Pixels.SizeX NY= metadata.image().Pixels.SizeY NZ= metadata.image().Pixels.SizeZ NC= metadata.image().Pixels.SizeC NT= metadata.image().Pixels.SizeT return (NX,NY,NZ,NC,NT)
def meta_bioformats(path, verbose=True): """ Function for reading io metadata. Reads a path for a Tiff io Allows to read the metadata from the Tiff io via the bioformats standard. It returns a python dictionary with all the information, and gives a warning in case a relevant one is missing (the dictionary is generated anyways) Default PhysicalSize for X and Y is 0.16125 """ # Imports for bioformats import javabridge import bioformats import xml.etree.ElementTree as ET # Start JVM for bioformats javabridge.start_vm(class_path=bioformats.JARS, run_headless=False, max_heap_size='2048M') # Read Metadata meta_xml = bioformats.get_omexml_metadata(path=path) # Creates the XML structure from the metadata string root = ET.fromstring(meta_xml.encode('utf-8')) # Get the dictionary with image metadata # meta = root[0][2].attrib # Original line, working on local meta = root[0][1].attrib # Working on remote (new version of something ?) # Convert some values to int meta['SizeT'] = int(meta['SizeT']) meta['SizeZ'] = int(meta['SizeZ']) meta['SizeY'] = int(meta['SizeY']) meta['SizeX'] = int(meta['SizeX']) meta['SizeC'] = int(meta['SizeC']) # Check metadata checklist = [ 'PhysicalSizeX', 'PhysicalSizeY', 'PhysicalSizeZ', 'SizeX', 'SizeY', 'SizeZ', 'SizeT', 'SizeC', 'Type' ] if verbose: for item in checklist: if item in meta: print(item + ': ' + str(meta[item])) else: print('*** Metadata problem, missing ' + item) # Kill java virtual machine # javabridge.detach() return meta
def readHeader(self): """ read metadata """ self.dataOffset = 0 self._secExtraByteSize = 0 # ========== obtain reader ============ # getting the right reader for tiff is not always done by bioformats... self.is_ometiff = False if self.fn.lower().endswith(OMETIFF) or \ not self.fn.lower().endswith(READABLE_FORMATS): self.fp = bioformats.ImageReader(self.fn, perform_init=False) self.handle = self.fp rdr = self.fp.rdr = self._readOMETiffHeader( self.fn.lower().endswith(OMETIFF)) else: # reading meta data of standard file formats self.xml = bioformats.get_omexml_metadata(self.fn) self.fp = bioformats.ImageReader(self.fn) self.handle = self.fp rdr = self.fp.rdr # http://stackoverflow.com/questions/2365411/python-convert-unicode-to-ascii-without-errors if sys.version_info.major == 2: self.xml = self.xml.replace(u'\xb5', u'u') # micro -> "u" self.xml = unicodedata.normalize('NFKD', self.xml).encode( 'ascii', 'ignore') else: self.xml = self.xml.replace('µ', '\xb5') #'u') # micro -> "u" self.omexml = ome.OMEXML(self.xml) # ========== setup attributes =========== self.ome = OME_XML_Editor(self.omexml) self.setUpDynamicList(self.ome) self.setDim() # ========== obtain other data =========== self.nseries = self.omexml.get_image_count() # obtain meta data other than Image # TODO: This must be done in a more structured way in the future if hasattr(self.omexml, 'root_node'): for node in self.omexml.root_node.getchildren(): name = repr(node).split()[1].split('}')[1].replace("'", '') if name not in ('Image', 'StructuredAnnotations'): self.metadata[name] = dict(list(node.items())) for cnode in node.getchildren(): cname = repr(cnode).split()[1].split('}')[1].replace( "'", '') self.metadata[name][cname] = dict(list(cnode.items()))
def readVWS(path): javabridge.start_vm(class_path=bf.JARS) try: logging.info('Data path: {}'.format(path)) md = bf.get_omexml_metadata(path) # img = bf.ImageReader(path, perform_init=True) finally: javabridge.kill_vm() return md
def createOMEXML(imagefile): if not VM_STARTED: start_jvm() if VM_KILLED: jvm_error() omexml = bioformats.get_omexml_metadata(imagefile) new_omexml = omexml.encode('utf-8') return new_omexml
def get_movie_shape(path): xml_image = bf.get_omexml_metadata(path=path) metadata = bf.OMEXML(xml_image) path = path NX = metadata.image().Pixels.SizeX NY = metadata.image().Pixels.SizeY NZ = metadata.image().Pixels.SizeZ NC = metadata.image().Pixels.SizeC NT = metadata.image().Pixels.SizeT return NX,NY,NZ,NC,NT
def lif_get_metas(fn): md = bioformats.get_omexml_metadata(fn) # Load meta data mdroot = ETree.fromstring(md) # Parse XML # meta = mdroot[1][3].attrib # Get relevant meta data metas = list( map( lambda e: e.attrib, mdroot.iter( '{http://www.openmicroscopy.org/Schemas/OME/2016-06}Pixels'))) return metas
def get_name_lif(filename): names = [] xml_string = bf.get_omexml_metadata(filename) xml_string = xml_string.encode('ascii', 'ignore') metadata_root = et.ElementTree.fromstring(xml_string) for child in metadata_root: if child.tag.endswith('Image'): names.append(child.attrib['Name']) return names
def get_editable_omexml(path): """ Parse OMEXML header data from a Bio-Formats-compatible file. Used to parse metadata from .nd2 file and pass on to .ome.tiff file. """ o = bioformats.get_omexml_metadata(path) new_omexml = bioformats.OMEXML(o) return new_omexml
def get_tif_res(tif_file): root = bioformats.get_omexml_metadata(tif_file) root = root.encode('ascii', 'replace') root = etree.fromstring(root) ns = root.nsmap[None] root = root.find('{{{ns}}}Image/{{{ns}}}Description'.format(ns=ns)) root = root.text root = etree.fromstring(root) ns = root.nsmap[None] return tuple( float(root.find('{{{ns}}}Image/{{{ns}}}Pixels'.format(ns=ns)).get('PhysicalSize{}'.format(dim))) for dim in ('Z', 'Y', 'X'))
def _get_schema(self) -> Schema: # Parse metadata, start a JVM if needed. # This JVM must continue to run until javabridge is no longer needed, # since javabridge does't support starting another one. Current # solution is to start a JVM upon first use of bioformats, and never # stop it. try: xml = bioformats.get_omexml_metadata(self.uri) except AttributeError: bioformats.javabridge.start_vm(class_path=bioformats.JARS, run_headless=True) xml = bioformats.get_omexml_metadata(self.uri) xml = _parse_ome_metadata(xml) shape = self._set_shape_metadata(xml["axes"], xml["shape"], xml["spacing"], xml["spacing_units"], xml["coords"]) self._set_fileheader(xml["fileheader"]) return Schema(dtype=xml["dtype"], shape=shape, npartitions=1, chunks=None)
def get_metadata_store(imagefile): if not VM_STARTED: start_jvm() if VM_KILLED: jvm_error() omexml = bioformats.get_omexml_metadata(imagefile) new_omexml = omexml.encode('utf-8') metadatastore = bioformats.OMEXML(new_omexml) return metadatastore
def provide_image(self, image_set): """Load an image from a pathname """ if self.__image is not None: return self.__image if self.volume: return self.get_image_volume() self.cache_file() filename = self.get_filename() channel_names = [] url = self.get_url() properties = {} if self.index is None: metadata = bioformats.get_omexml_metadata(self.get_full_name()) ometadata = bioformats.omexml.OMEXML(metadata) pixel_metadata = ometadata.image( 0 if self.series is None else self.series).Pixels nplanes = pixel_metadata.SizeC * pixel_metadata.SizeZ * pixel_metadata.SizeT indexes = list(range(nplanes)) elif numpy.isscalar(self.index): indexes = [self.index] else: indexes = self.index planes = [] offset = 0 for i, index in enumerate(indexes): properties["index"] = str(index) if self.series is not None: if numpy.isscalar(self.series): properties["series"] = self.series else: properties["series"] = self.series[i] img = bioformats.load_image(self.get_full_name(), rescale=False, **properties).astype(int) img = convert_image_to_objects(img).astype(numpy.int32) img[img != 0] += offset offset += numpy.max(img) planes.append(img) image = Image( numpy.dstack(planes), path_name=self.get_pathname(), file_name=self.get_filename(), convert=False, ) self.__image = image return image
def get_OMEXML(imagefile): if not VM_STARTED: start_jvm() if VM_KILLED: jvm_error() # get OME-XML and change the encoding to UTF-8 omexml = bioformats.get_omexml_metadata(imagefile) omexml = omexml.encode('utf-8') # omexml = unidecode(omexml) return omexml
def readfile(filename): # read metadata metadata = bioformats.get_omexml_metadata(filename) xml = bioformats.OMEXML(metadata) Pixels = xml.image().Pixels nx, ny, nz, nt = Pixels.SizeX, Pixels.SizeY, Pixels.SizeZ, Pixels.SizeT # read image data image4d = np.zeros(shape=(nx, ny, nz, nt)) reader = bioformats.ImageReader(filename) for t in range(nt): for z in range(nz): image4d[:, :, z, t] = reader.read(z=z, t=t, rescale=False) return image4d
def showGrahp(filename, num): md = bf.get_omexml_metadata(filename) #rdr = bf.ImageReader(filename, perform_init=True) ome = bf.OMEXML(md) pixels = ome.image().Pixels print('pixels in Z: ' + str(pixels.SizeZ)) print('pixels in C: ' + str(pixels.SizeC)) print('pixels in T: ' + str(pixels.SizeT)) print('pixels in X: ' + str(pixels.SizeX)) print('pixels in Y: ' + str(pixels.SizeY)) with bf.ImageReader(filename) as reader: img = reader.read(t=num) plt.imshow(img, cmap=plt.cm.binary) plt.show() reader.close()
def _metadata(path): xml = bioformats.get_omexml_metadata(path) md = bioformats.omexml.OMEXML(xml) meta = {'AcquisitionDate': md.image().AcquisitionDate} meta['Name'] = (md.image().Name).replace(" ", "") meta['SizeT'] = md.image().Pixels.SizeT meta['SizeX'] = md.image().Pixels.SizeX meta['SizeY'] = md.image().Pixels.SizeY meta['PhysicalSizeX'] = md.image().Pixels.PhysicalSizeX meta['PhysicalSizeY'] = md.image().Pixels.PhysicalSizeY timepoint = [] for planes in range(meta['SizeT']): timepoint.append(md.image().Pixels.Plane(planes).DeltaT) meta['Timepoint'] = np.asarray(timepoint) return (meta)
def read_metadata(self): omexmlstr = bioformats.get_omexml_metadata(self.path) omexml = bioformats.OMEXML(omexmlstr) # orgmetadata = bioformats.OMEXML.OriginalMetadata(omexml) root = ET.fromstring(omexmlstr) print(omexml) tree = ET.ElementTree(root) self.channel_count = omexml.image().Pixels.channel_count self.channel_names = [] # populate channel_names for i in np.arange(0, self.channel_count, 1): self.channel_names.append(omexml.image().Pixels.Channel(i).Name) # print('image_count:',omexml.get_image_count()) # print('image physical sizex unit',omexml.image().Pixels.get_PhysicalSizeXUnit()) # print('image physical sizex',omexml.image().Pixels.get_PhysicalSizeX()) # print('image sizex',omexml.image().Pixels.get_SizeX()) # print('image physical sizey unit',omexml.image().Pixels.get_PhysicalSizeYUnit()) # print('image physical sizey',omexml.image().Pixels.get_PhysicalSizeY()) # print('image sizey',omexml.image().Pixels.get_SizeY()) # print('image sizez',omexml.image().Pixels.get_SizeZ()) # print('image sixec',omexml.image().Pixels.get_SizeC()) # print('image sizet',omexml.image().Pixels.get_SizeT()) # print('image dimensions',omexml.image().Pixels.get_DimensionOrder()) tagprefix = '{http://www.openmicroscopy.org/Schemas/OME/2016-06}' for child1 in root: print('Child1: ', child1.tag, '\t', child1.attrib) for child2 in child1: print('Child2: ', child2.tag, '\t', child2.attrib) count = 0 for child3 in child2: print('Child3: ', child3.tag, child3.attrib) if (count >= 10): break if (child3.tag == tagprefix + 'Plane'): count = count + 1 for child4 in child3: print('Child4: ', child4.tag, child4.attrib) for child5 in child4: print('Child5: ', child5.tag, child5.attrib) for child6 in child5: print('Child6: ', child6.tag, child6.attrib) print('-----------------------------------') print('====================================')
def exposure_times_image( s_image, s_find="Information\|Image\|Channel\|ExposureTime\<\/Key\>\<Value\>" ): # ok ''' version: 2021-03-06 input: s_image: path and filename to image s_find: string to parse and extract the exposure time metadata output: li_exposure: list of each channels exposer time values in milisecond. s_meta: all bioformats metadata form this image stored as string. description: function to extract from a bioformat compatible image for each channel the exposter time in milliseconds. ''' print(f'process image: {s_image} ...') # get bioformats metadata #javabridge.start_vm(class_path=bioformats.JARS) s_meta = bioformats.get_omexml_metadata(path=s_image) #o = bioformats.OMEXML(s_meta) #javabridge.kill_vm() #print(o.image().Name) #print(o.image().AcquisitionDate) # sain check li_start = [m.start() for m in re.finditer(s_find, s_meta)] if len(li_start) != 1: print( 'Error @ metadata.exposure_times_image : found wrong number of exposure times' ) # extract exposure time ls_exposure = [] for i_start in li_start: ls_exposure.append(s_meta[i_start:i_start + 200]) s_exposure = ls_exposure[0].strip(s_find) s_exposure = s_exposure[1:s_exposure.find(']')] ls_exposure = s_exposure.split(',') li_exposure = [int(s_item) / 1000000 for s_item in ls_exposure] # output return (li_exposure, s_meta)
def metadata(path: str) -> Dict[str, Any]: xml = bioformats.get_omexml_metadata(path) md = bioformats.omexml.OMEXML(xml) meta = {'AcquisitionDate': md.image().AcquisitionDate} meta['Name'] = md.image().Name meta['SizeC'] = md.image().Pixels.SizeC meta['SizeT'] = md.image().Pixels.SizeT meta['SizeX'] = md.image().Pixels.SizeX meta['SizeY'] = md.image().Pixels.SizeY meta['SizeZ'] = md.image().Pixels.SizeZ meta['PhysicalSizeX'] = md.image().Pixels.PhysicalSizeX meta['PhysicalSizeY'] = md.image().Pixels.PhysicalSizeY meta['PhysicalSizeZ'] = md.image().Pixels.PhysicalSizeZ meta['PositionX'] = md.image().Pixels.Plane().PositionX meta['PositionY'] = md.image().Pixels.Plane().PositionY meta['Timepoint'] = md.image().Pixels.Plane().DeltaT return (meta)
def load_slide_scanner_image(self, z=0, serie=4): self.downfactor = 1 self._img_vsi = bf.load_image(self.path.as_posix(), t=0, series=serie, z=z) metadata = bf.get_omexml_metadata(self.path.as_posix()) o = bf.OMEXML(metadata) n_zslices = o.image_count self.n_slices_known.emit(n_zslices, self._img_vsi.shape[-1], 4, 1) self.slice_slide_scanner()
def get_ome_metadata(input_file_path, output_path, **kwargs): """ Extracts metadata from an input file and save it to a file at the specified output_path. Note: this is currently not used at this stage. Parameters ---------- input_file_path: str Path to the input file """ input_fname, ext = os.path.splitext(os.path.basename(input_file_path)) if ext[1:] not in bioformats.READABLE_FORMATS: raise Exception("Unsupported format: %s.%s" % (input_fname, ext)) meta_xml = bioformats.get_omexml_metadata(input_file_path) output_file_path = os.path.join(output_path, input_fname+".xml") with open(output_file_path, "w") as f: f.write(meta_xml.encode('utf-8')) return {"ome": output_file_path}
def on_calculate(self): # calculate force if len(self.markers) < 2: return x0 = min(self.markers[0].x(), self.markers[1].x()) x1 = max(self.markers[0].x(), self.markers[1].x()) y0 = min(self.markers[0].y(), self.markers[1].y()) y1 = max(self.markers[0].y(), self.markers[1].y()) md = bioformats.get_omexml_metadata(self.file_name) md = md.encode('utf-8') mdroot = ETree.fromstring(md) n = mdroot[1][3].attrib['SizeT'] n = int(float(n)) # number of frames scalebar = mdroot[1][3].attrib['PhysicalSizeX'] scalebar = float(scalebar) result = [] shift = numpy.zeros([n-10, 2]) image_np = self.reader.read(z=0, t=10) # discard the first 10 frames image_np = image_np[:,:,1] imWindow = image_np[y0:y1, x0:x1] for i in range(10, n): self.statusBar().showMessage('Processing %d of %d' % (i-9, n-10)) image_np = self.reader.read(z=0, t=i) image_np = image_np[:,:,1] image_np = image_np[y0:y1, x0:x1] result = feature.register_translation(imWindow, image_np, upsample_factor=100) shift[i-10] = result[0] time = numpy.arange(0, n-10) time = numpy.multiply(timeUnit, time) shift = -shift x_min = min(shift[:,1]) index = numpy.where(shift[:,1] == x_min) index = index[0][0] shift[:,1] = shift[:,1] - x_min shift[:,0] = shift[:,0] - shift[index,0] pixel_x = shift[:,1] pixel_y = shift[:,0] pixel = numpy.sqrt(pixel_x * pixel_x + pixel_y * pixel_y) displacement_x = shift[:,1] * scalebar displacement_y = shift[:,0] * scalebar displacement = numpy.sqrt(displacement_x * displacement_x + displacement_y * displacement_y) fig = plt.figure() ax = fig.gca() plt.plot(time, displacement_x, label = 'X') plt.plot(time, displacement_y, label = 'Y') plt.plot(time, displacement, label = 'Total') ax.yaxis.set_minor_locator(AutoMinorLocator(5)) plt.xlabel('Time (s)') plt.ylabel('Displacement (um)') plt.legend(loc='lower right') plt.grid(which='minor', alpha=0.35) plt.grid(which='major', alpha=1) plt.show() force_x = shift[:,1] * scalebar * springConstant force_y = shift[:,0] * scalebar * springConstant force = numpy.sqrt(force_x * force_x + force_y * force_y) plt.savefig(self.file_name[0:-4] + "_force.png", dpi=300) numpy.savetxt(self.file_name[0:-4] + "_force.csv", numpy.transpose([time, pixel_x, pixel_y, pixel, displacement_x, displacement_y, displacement, force_x, force_y, force]), fmt='%1.3f', delimiter='\t', header='t(s)\tpx\tpy\tp\tx(um)\ty(um)\ttotal(um)\tfx(uN)\tfy(uN)\tf(uN)', comments='')
def metadata(filename): array_order = 'XYZTC' md_string = bf.get_omexml_metadata(filename) return parse_xml_metadata(md_string, array_order)
def getWelllNamesfromCZI(filename): """ This function can be used to extract information about the well or image scence container a CZI image was acquired. Those information are "hidden" inside the XML meta-information. Attention: It works for CZI image data sets only! Example XML structure (shortend) ------------------------------------------------------------------------------------------------------------------------- <OME xmlns="http://www.openmicroscopy.org/Schemas/OME/2015-01" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.openmicroscopy.org/Schemas/OME/2015-01 http://www.openmicroscopy.org/Schemas/OME/2015-01/ome.xsd"> <Experimenter ID="Experimenter:0" UserName="******"/> <Image ID="Image:0" Name="B4_B5_S=8_4Pos_perWell_T=2_Z=1_CH=1.czi #1"> <AcquisitionDate>2016-07-20T11:44:16.161</AcquisitionDate> <ExperimenterRef ID="Experimenter:0"/> <InstrumentRef ID="Instrument:0"/> <ObjectiveSettings ID="Objective:1" Medium="Air" RefractiveIndex="1.000293"/> <Pixels BigEndian="false" DimensionOrder="XYCZT" ID="Pixels:0" Interleaved="false" PhysicalSizeX="0.39999999999999997" PhysicalSizeXUnit="µm" PhysicalSizeY="0.39999999999999997" PhysicalSizeYUnit="µm" SignificantBits="8" SizeC="1" SizeT="2" SizeX="640" SizeY="640" SizeZ="1" Type="uint8"> <Channel AcquisitionMode="WideField" EmissionWavelength="465.0" EmissionWavelengthUnit="nm" ExcitationWavelength="353.0" ExcitationWavelengthUnit="nm" ID="Channel:0:0" IlluminationType="Epifluorescence" Name="DAPI" SamplesPerPixel="1"> <DetectorSettings Binning="1x1" Gain="0.0" ID="Detector:Internal"/> <FilterSetRef ID="FilterSet:1"/> <LightPath/> </Channel> <MetadataOnly/> <Plane DeltaT="0.46000003814697266" DeltaTUnit="s" ExposureTime="20.0" ExposureTimeUnit="s" PositionX="30533.145" PositionXUnit="reference frame" PositionY="16533.145" PositionYUnit="reference frame" PositionZ="111.842" PositionZUnit="reference frame" TheC="0" TheT="0" TheZ="0"/> <Plane DeltaT="5.456000089645386" DeltaTUnit="s" ExposureTime="20.0" ExposureTimeUnit="s" PositionX="30533.145" PositionXUnit="reference frame" PositionY="16533.145" PositionYUnit="reference frame" PositionZ="111.842" PositionZUnit="reference frame" TheC="0" TheT="1" TheZ="0"/> </Pixels> </Image> <StructuredAnnotations xmlns="http://www.openmicroscopy.org/Schemas/SA/2015-01"> <XMLAnnotation ID="Annotation:2127" Namespace="openmicroscopy.org/OriginalMetadata"> <Value> <OriginalMetadata> <Key>Information|Image|S|Scene|Shape|Name</Key> <Value>[B4, B4, B4, B4, B5, B5, B5, B5]</Value> </OriginalMetadata> </Value> </XMLAnnotation> </StructuredAnnotations> </OME> :param filename: input CZI image file location :return: string wellstring containing the information """ if not VM_STARTED: start_jvm() if VM_KILLED: jvm_error() # Current key for wells inside the meta-information - 2016_07_21 wellkey = 'Information|Image|S|Scene|Shape|Name' # Create OME-XMF using BioFormats from CZI file and encode omexml = bioformats.get_omexml_metadata(filename) omexml_enc = omexml.encode('utf-8') # Get the tree and define namespace tree = etl.fromstring(omexml_enc) name_space = "{http://www.openmicroscopy.org/Schemas/SA/2015-01}" # find OriginalMetadata origin_meta_datas = tree.findall(".//{}OriginalMetadata".format(name_space)) # Iterate in founded origins for origin in origin_meta_datas: key = origin.find("{}Key".format(name_space)).text if key == wellkey: wellstring= origin.find("{}Value".format(name_space)).text print("Value: {}".format(wellstring)) return wellstring
def read(self): return bioformats.get_omexml_metadata(self.filename)
def main(args): javabridge.start_vm(class_path=bf.JARS) try: lifdir = sys.argv[1] except IndexError: print "Usage: %s lif_directory [sdx] [sdy] [sdz]" % os.path.basename(sys.argv[0]) sys.exit(1) try: sdx, sdy, sdz = int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4]) except IndexError: print "Using default values for standard deviation" sdx, sdy, sdz = 4, 4, 3 md = bf.get_omexml_metadata(lifdir) mdo = bf.OMEXML(md) rdr = bf.ImageReader(lifdir, perform_init=True) names, sizes, resolutions = parse_xml_metadata(md) print '%s contains:' % lifdir for i in range(mdo.image_count): print '%d, %s, %s' % (i,names[i],(sizes[i],)) for im_num in range(mdo.image_count): im_size = () im_size = [sizes[im_num][1],sizes[im_num][2],sizes[im_num][0],3] image3d = np.empty(im_size, np.uint8) print 'projecting: %d, %s, %s' % (im_num,names[im_num],(sizes[im_num],)) z_size = sizes[im_num][0] flush_message('Importing...') for z in range(z_size): image3d[:,:,z,:] = rdr.read(z=z, series=im_num, rescale=False) print 'done' #ma = greyScale(image3d) ma = np.amax(image3d, 3) #sdx, sdy, sdz = 4, 4, 3 sds = 4 output_dir = "./proj_%s_%s" % (lifdir, im_num) if not os.path.exists(output_dir): os.makedirs(output_dir) max_proj = np.amax(ma, axis=2) mpfilename = os.path.join(output_dir, "max-proj.png") scipy.misc.imsave(mpfilename, max_proj) bl = nd.gaussian_filter(ma, [sdx, sdy, sdz]) #ps = find_projection_surface(bl) ps = proj.max_indices_z(bl) sps = nd.gaussian_filter(ps, sds) vis_factor = 255 / z_size sfilename = os.path.join(output_dir, "surface-g3d-%d-%d-%d-%d.png" % (sdx, sdy, sdz, sds)) scipy.misc.imsave(sfilename, sps * vis_factor) res = proj.projection_from_surface(ma, sps, dm=3, dp=0) filename = os.path.join(output_dir, "proj-g3d-%d-%d-%d-%d.png" % (sdx, sdy, sdz, sds)) pmax = np.amax(res) vis_scale = 255 / pmax scipy.misc.imsave(filename, res * vis_scale) flush_message("Post processing...") pp = projpp.proj_filter(res * vis_scale, 3, 60, 15) print " done" filename = os.path.join(output_dir, 'proj-pp-%d-%d-%d-%d.png' % (sdx, sdy, sdz, sds)) scipy.misc.imsave(filename, pp) javabridge.kill_vm() return 0
viewer.addRGBALayer(va) viewer.addGrayscaleLayer(va[...,1]) viewer.show() viewer.addGrayscaleLayer(array1) ### examine lif files import javabridge import bioformats as bf javabridge.start_vm(class_path=bf.JARS) path = '/media/tmp/lif/fish test.lif' #### get the series count ox = bf.OMEXML(bf.get_omexml_metadata(path)) series_count = ox.image_count print series_count #### other version import javabridge ImageReader = javabridge.JClassWrapper("loci.formats.ImageReader") MetadataTools = javabridge.JClassWrapper("loci.formats.MetadataTools") reader = ImageReader() omeMeta = MetadataTools.createOMEXMLMetadata() reader.setMetadataStore(omeMeta) reader.setId(path) print reader.getSeriesCount()
def get_preview_image(fname, meta_xml=None, maxwh=256, series=0): """ Generate a thumbnail of an image at the specified path. Gets the middle Z plane of channel=0 and timepoint=0 of the specified series. Parameters ---------- fname: str Path to image file. meta_xml: str OME XML metadata. maxwh: int Maximum width or height of the output thumbnail. If the extracted image is larger in either x or y, the image will will be downsized to fit. series: int Series for multi-stack formats (default=0) Returns ------- img: numpy.ndarray N x M array of grayscale pixel intentsities. """ name, ext = os.path.splitext(os.path.basename(fname)) if ext[1:] not in bioformats.READABLE_FORMATS: raise Exception("Format not supported: %s" % ext[1:]) if not meta_xml: meta_xml = bioformats.get_omexml_metadata(fname) ome = bioformats.OMEXML(meta_xml) if series > ome.get_image_count(): raise Exception( "Specified series number %s exceeds number of series " "in the image file: %s" % (series, fname) ) # Get metadata for first series meta = ome.image(0).Pixels # Determine resize factor sizex = meta.SizeX sizey = meta.SizeY if sizex > maxwh or sizey > maxwh: f = min(float(maxwh) / float(sizex), float(maxwh) / float(sizey)) else: f = max(float(maxwh) / float(sizex), float(maxwh) / float(sizey)) # Determine which Z slice z = 0 # Determine middle Z plane # Note: SizeZ doesn't seem to be reliable. Might need to check BF. # Stick with first slice for now. # if meta.SizeZ > 1: # z = int(math.floor(float(meta.SizeZ)/2)) # Load image plane if meta.channel_count == 1 and meta.SizeC == 4: # RGB Image img = bioformats.load_image(fname, t=0, z=z, series=series, rescale=False) return zoom(img, (f, f, 1)) else: # Grayscale, grab channel 0 only img = bioformats.load_image(fname, c=0, t=0, z=z, series=series, rescale=False) # if img.dtype in (np.uint16, np.uint32, np.int16, np.int32): img = stretch_contrast(img) return zoom(img, f)
def metadata(filename, array_order=DEFAULT_DIM_ORDER): md_string = bf.get_omexml_metadata(filename) return parse_xml_metadata(md_string, array_order)
def on_calculate(self): # calculate force if len(self.markers) < 2: return x0 = min(self.markers[0].x(), self.markers[1].x()) + width_offset x1 = max(self.markers[0].x(), self.markers[1].x()) + width_offset y0 = min(self.markers[0].y(), self.markers[1].y()) + height_offset y1 = max(self.markers[0].y(), self.markers[1].y()) + height_offset md = bioformats.get_omexml_metadata(self.file_name) md = md.encode('utf-8') mdroot = ETree.fromstring(md) n = mdroot[0][1].attrib['SizeT'] n = int(float(n)) # number of frames # scalebar = mdroot[1][3].attrib['PhysicalSizeX'] # scalebar = float(scalebar) result = [] shift = numpy.zeros(n) image_np = self.reader.read(z=0, t=0) image_np = image_np[:,:,1] imWindow = image_np[y0:y1, x0:x1] for i in range(0, n): self.statusBar().showMessage('Processing %d of %d' % (i+1, n)) image_np = self.reader.read(z=0, t=i) image_np = image_np[:,:,1] image_np = image_np[y0:y1, x0:x1] # result = feature.register_translation(imWindow, # image_np, # upsample_factor=100) result = feature.canny(image_np, sigma = 3) # edge result = (result == True).nonzero()[1] result = numpy.mean(result) print result shift[i] = result time = numpy.arange(0, n) timeUnit = 30.0 / n; time = numpy.multiply(timeUnit, time) shift = shift - shift[0] pixel_x = shift displacement_x = shift * scalebar force_x = shift * scalebar * springConstant fig = plt.figure() ax = fig.gca() plt.plot(time, force_x, label = 'X') ax.yaxis.set_minor_locator(AutoMinorLocator(5)) plt.xlabel('Time (min)') plt.ylabel('Force (uN)') plt.legend(loc='lower right') plt.grid(which='minor', alpha=0.35) plt.grid(which='major', alpha=1) plt.show() plt.savefig(self.file_name[0:-4] + "_force.png", dpi=300) numpy.savetxt(self.file_name[0:-4] + "_force.csv", numpy.transpose([time, pixel_x, displacement_x, force_x]), fmt='%1.3f', delimiter='\t', header='t(s)\tpx\tx(um)\tfx(uN)', comments='')
Bckg_FN = FolderNames[len(FolderNames)-1]+ FilesOnFold +'Bckg' SuperPrev_fn = FolderNames[len(FolderNames)-1]+ FilesOnFold + "_Preview.tif" BckgSubs_fn = FolderOut+'/BckgSubs' Bckg_fn = Bckg_FN +'/Bckg' if os.path.isfile(SuperPrev_fn): os.remove(SuperPrev_fn) Char1 = 'bool' rdr = bf.ImageReader(FilesOnFold, perform_init=True) Meta = bf.get_omexml_metadata(FilesOnFold) md = bf.omexml.OMEXML(Meta) pixels = md.image().Pixels TempStack = False VolumeStack = False if (pixels.SizeT > 1): TempStack = True StackLength = pixels.SizeT elif (pixels.SizeZ > 1): VolumeStack = True StackLength = pixels.SizeZ else: print(FilesOnFold) sys.exit("\n\n Selected file is not a Stack \n\n") if TempStack:
def get_metadata_xml(self): # bioformats.get_omexml_metadata opens and closes a new reader return bioformats.get_omexml_metadata(self.filename)