Example #1
0
    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('&#181', '\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()))
Example #2
0
def read_image(filelike):
    """Read an image volume from a file.

    Parameters
    ----------
    filelike : string or bf.ImageReader
        Either a filename containing a BioFormats image, or a
        `bioformats.ImageReader`.

    Returns
    -------
    image : numpy ndarray, 5 dimensions
        The read image.
    """
    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.")
    if isinstance(filelike, bf.ImageReader):
        rdr = filelike
    else:
        rdr = bf.ImageReader(filelike)
    image = rdr.read(rescale=False)
    return image
Example #3
0
def read_images(image_ids, max_zs, lif_file):
    """
    Read rgb images from lif file

    :param image_ids: List of image ids (series #), to extract
    :param max_zs: List of max z-depths for each image
    :param lif_file: Path to lif file to extract images from
    :return: List of images containing image data
    """
    images = []
    with bf.ImageReader(path=lif_file) as reader:
        for i, s in enumerate(image_ids):
            for z in range(0, max_zs[i]):
                try:
                    image_data = reader.read(c=None,
                                             z=z,
                                             t=0,
                                             series=s,
                                             index=None,
                                             rescale=False,
                                             wants_max_intensity=False,
                                             channel_names=None,
                                             XYWH=None)
                except:
                    print('Error reading image data')
                    continue
                # Need to add blue channel, as microscope only saves red and green
                rgb_image = add_blue_channel(image_data)
                images.append(rgb_image)
    return images
Example #4
0
def merge_image_channel_files(data_path, dataset, i):
    """
  Given the path to the folder containing all of the image files, look up the
  channel files corresponding to cell i of the dataset and merge its channel
  files into a plane generator.

  The plane generator should return an x-y plane of values for each z, channel,
  and time combination (in that order). In this case, we have a variable number
  of z planes, 3 channels, and 1 time.
  """
    cell_name = 'cell{}'.format(i)
    prefix = dataset['file_prefix']
    first_channel_file = '_'.join([prefix, cell_name, 'ch0', 't1.tif'])
    first_channel_path = os.path.join(data_path, first_channel_file)
    with bioformats.ImageReader(first_channel_path) as reader:
        z_count = reader.rdr.getImageCount()

    def plane_generator():
        for z_i in xrange(z_count):
            for i in xrange(len(CHANNELS)):
                channel_infix = CHANNELS[i]['file_infix']
                channel_file = '_'.join(
                    [prefix, cell_name, channel_infix, 't1.tif'])
                channel_path = os.path.join(data_path, channel_file)
                with bioformats.ImageReader(channel_path) as reader:
                    yield reader.read(index=z_i)

    return plane_generator, z_count
Example #5
0
    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')
Example #6
0
    def load_imgs_generator(self):
        axes = self.check_dims_equal()

        for fn in self.img_fns:
            dims = get_pixel_dimensions(fn)
            #print("  -- ", fn, dims)

            ir = bf.ImageReader(str(fn))

            img = numpy.zeros((dims.t, dims.z, dims.y, dims.x, dims.c),
                              numpy.float32)
            for t in range(dims.t):
                for z in range(dims.z):
                    for c in range(dims.c):
                        img[t, z, :, :, c] = ir.read(series=0,
                                                     z=z,
                                                     c=c,
                                                     t=t,
                                                     rescale=False)

            if "Z" not in axes:
                img = img[:, 0, ...]
            yield img

            ir.close()
def align(im, warp_matrix):

    dic = oib.image_info(im)

    x = int(dic['frame_size_x'])
    y = int(dic['frame_size_y'])
    c = int(dic['channels'])
    z = int(dic['z_steps'])
    t = int(dic['time_frames'])

    with bioformats.ImageReader(im, perform_init=True) as rdr:
        image = np.empty([t, z, y, x, c], np.uint16)
        for c in range(c):
            image[:, :, :, :, c] = rdr.read(c=1, rescale=False)
            image[:, :, :, :, c] = cv2.warpAffine(
                (rdr.read(c=0, rescale=False)),
                warp_matrix, (y, x),
                flags=cv2.INTER_LINEAR + cv2.WARP_INVERSE_MAP)
            for t in range(t):
                image[t, :, :, :, c] = cv2.warpAffine(
                    (rdr.read(t=t, z=0, c=0, rescale=False)),
                    warp_matrix, (y, x),
                    flags=cv2.INTER_LINEAR + cv2.WARP_INVERSE_MAP)
                for z in range(z):
                    image[:, z, :, :, c] = cv2.warpAffine(
                        (rdr.read(z=z, c=0, rescale=False)),
                        warp_matrix, (y, x),
                        flags=cv2.INTER_LINEAR + cv2.WARP_INVERSE_MAP)

    return image
Example #8
0
 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 __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 read_bioformat(image, resize=False):
    '''Read Images in almost any format.

    Parameters
    ----------
    resize : bool, optional
        If "true", will resize image to 1024, while keeping the ratio.

    Returns
    -------
    image : numpy ndarray, 5 dimensions
        The read image.
    '''

    if JVM_BEGIN == False:
        begin_javabridge()
    if JVM_END == True:
        raise RuntimeError("The java virtual Machine has already ended "
                           "you should restart the program")

    else:
        with bioformats.ImageReader(image) as rdr:
            image = rdr.read(rescale=False)

    if resize == True:
        size = np.max(image.shape)
        if size > 1024:
            image = imresize(image, 1024. / size)

    return image
def test_read_subimage_tif():
    path = os.path.join(os.path.dirname(__file__), 'resources', 'Channel1-01-A-01.tif')
    with bioformats.ImageReader(path) as f:
        data_0_10_0_10 = f.read(XYWH=(0, 0, 10, 10), rescale=False)

    #
    # Data as read by cellprofiler.modules.loadimages.load_using_PIL
    #
    expected_0_10_0_10 = numpy.array(
        [[ 0,  7,  7,  6,  5,  8,  4,  2,  1,  2],
         [ 0,  8,  8,  7,  6, 10,  4,  2,  2,  2],
         [ 0,  9,  9,  7,  8,  8,  2,  1,  3,  2],
         [ 0, 10,  9,  8, 10,  6,  2,  2,  3,  2],
         [ 0, 10, 10, 10,  9,  4,  2,  2,  2,  2],
         [ 0,  9,  9, 10,  8,  3,  2,  4,  2,  2],
         [ 0,  9,  9, 10,  8,  2,  2,  4,  3,  2],
         [ 0,  9,  8,  9,  7,  4,  2,  2,  2,  2],
         [ 0, 10, 11,  9,  9,  4,  2,  2,  2,  2],
         [ 0, 12, 13, 12,  9,  4,  2,  2,  2,  2]], dtype=numpy.uint8)
    expected_n10_n10 = numpy.array(
        [[2, 1, 1, 1, 2, 2, 1, 2, 1, 2],
         [1, 2, 2, 2, 2, 1, 1, 1, 2, 1],
         [1, 1, 1, 2, 1, 2, 2, 2, 2, 1],
         [2, 2, 2, 2, 3, 2, 2, 2, 2, 1],
         [1, 2, 2, 1, 1, 1, 1, 1, 2, 2],
         [2, 1, 2, 2, 2, 1, 1, 2, 2, 2],
         [2, 2, 3, 2, 2, 1, 2, 2, 2, 1],
         [3, 3, 1, 2, 2, 2, 2, 3, 2, 2],
         [3, 2, 2, 2, 2, 2, 2, 2, 3, 3],
         [5, 2, 3, 3, 2, 2, 2, 3, 2, 2]], dtype=numpy.uint8)
    assert numpy.all(expected_0_10_0_10 == data_0_10_0_10)
Example #12
0
def imread_bioformats(path):
    """Thin wrapper around bioformats, slow and shitty,
    but works in a pinch, only reads z stack -- no time"""
    # import modules tp ise
    import javabridge
    import bioformats
    import gc
    import itertools
    # start the jave VM with the appropriate classes loaded
    javabridge.start_vm(class_path=bioformats.JARS)
    # init the reader
    with bioformats.ImageReader(path) as reader:
        # init container
        data = []
        for i in itertool.count():
            try:
                data.append(reader.read(z=i, rescale=False))
            except javabridge.JavaException:
                # reached end of file, break
                break
    # clean up a little
    javabridge.kill_vm()
    gc.collect()
    # return ndarray
    return np.asarray(data)
Example #13
0
def load_bioformats(path, serie=0):
    meta, _ = _metadata(path, serie=serie)
    image = np.empty((meta['SizeT'], meta['SizeZ'], meta['SizeX'],
                      meta['SizeY'], meta['SizeC']))

    with bioformats.ImageReader(path) as rdr:
        for t in range(0, meta['SizeT']):
            for z in range(0, meta['SizeZ']):
                for c in range(0, meta['SizeC']):
                    image[t, z, :, :, c] = rdr.read(c=c,
                                                    z=z,
                                                    t=t,
                                                    series=serie,
                                                    index=None,
                                                    rescale=False,
                                                    wants_max_intensity=False,
                                                    channel_names=None)
    img = np.squeeze(image)
    if img.ndim == 3:
        mip = np.amax(img, 0)
    elif img.ndim == 4:
        mip = np.amax(img[:, :, :, 1], 0)
    else:
        print("need to correct for ndim > 3")

    directory = _new_directory(path, meta)

    return (img, directory, mip, meta)
Example #14
0
def get_series_from_well(imagefile, sizes, seriesseq):
    """
    Reads all scenes from a single well and stores them in a array.
    """
    if not VM_STARTED:
        start_jvm()
    if VM_KILLED:
        jvm_error()

    rdr = bioformats.ImageReader(imagefile, perform_init=True)
    sizes[0] = len(seriesseq)

    #img6dwell = np.empty(sizes, dtype=BF2NP_DTYPE[rdr.rdr.getPixelType()])
    img6dwell = np.zeros(sizes, dtype=BF2NP_DTYPE[rdr.rdr.getPixelType()])

    for seriesID in range(0, len(seriesseq)):
        for timepoint in range(0, sizes[1]):
            for zplane in range(0, sizes[2]):
                for channel in range(0, sizes[3]):
                    img6dwell[seriesID, timepoint, zplane, channel, :, :] =\
                        rdr.read(series=seriesID, c=channel,z=zplane, t=timepoint, rescale=False)

    rdr.close()

    return img6dwell
Example #15
0
def merge_image_channel_files(tif_name, infix):
    """
  Given a path containing directories for each channel, grab the channel image
  for image_name in each of the channels, and merge them into a single plane
  generator which is returned.

  The plane generator should return an x-y plane of values for each z, channel,
  and time combination (in that order). In this case, we have a variable number
  of z planes, 3 channels, and 1 time.
  """
    with bioformats.ImageReader(tif_name) as reader:
        z_count = reader.rdr.getImageCount()
    prefix = tif_name[:tif_name.rindex(infix)]

    def plane_generator():
        for z_i in xrange(z_count):
            for channel in CHANNELS:
                if channel == "Cell membrane":
                    channel_path = prefix + "cell.tif"
                elif channel == "DNA":
                    channel_path = prefix + "nucleus.tif"
                elif channel == "protein":
                    channel_path = tif_name
                with bioformats.ImageReader(channel_path) as reader:
                    yield reader.read(index=z_i)

    return plane_generator, z_count
Example #16
0
def read_series(img_path, img_meta):
    with bioformats.ImageReader(img_path) as rdr:
        for i, m in enumerate(img_meta):
            img = np.array([
                rdr.read(c=c, series=i, rescale=False) for c in range(m.sizec)
            ])
            yield img, m
Example #17
0
def get_image6d(imagefile, sizes):
    """
    This function will read the image data and store them into a 6D numpy array.
    The 6D array has the following dimension order: [Series, T, Z, C, X, Y].
    """
    if not VM_STARTED:
        start_jvm()
    if VM_KILLED:
        jvm_error()

    rdr = bioformats.ImageReader(imagefile, perform_init=True)

    #img6d = np.empty(sizes, dtype=BF2NP_DTYPE[rdr.rdr.getPixelType()])
    img6d = np.zeros(sizes, dtype=BF2NP_DTYPE[rdr.rdr.getPixelType()])

    # main loop to read the images from the data file
    for seriesID in range(0, sizes[0]):
        for timepoint in range(0, sizes[1]):
            for zplane in range(0, sizes[2]):
                for channel in range(0, sizes[3]):
                    img6d[seriesID, timepoint, zplane, channel, :, :] =\
                        rdr.read(series=seriesID, c=channel, z=zplane, t=timepoint, rescale=False)

    rdr.close()

    return img6d
Example #18
0
    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()
Example #19
0
 def get_serie_stack(self, serie_ix: int):
     stack = []
     with bf.ImageReader(self.fullpath) as rdr:
         for z in range(self.md.SizeZ[serie_ix]):  # Loop through z slices
             im = rdr.read(z=z, series=serie_ix, rescale=False)
             stack.append(im)
         stack = np.array(stack)
     return stack
Example #20
0
def read_psf(path,output_type=np.float32):
    NX,NY,NZ,NC,NT=get_movie_shape(path)
    #assert(NC==1)
    #assert(NT==1)
    psf=np.zeros((NX,NY,NZ),dtype=output_type)
    with bf.ImageReader(path=path) as reader:
        for z in range(NZ):
            psf[:, :, z] = reader.read(c=z, rescale=False)
    return psf
Example #21
0
        def __init__(self, frontend):
            super().__init__(frontend)

            self._rdr = bioformats.ImageReader(str(self.frontend._file_path))

            # Test to see if the loci_tools.jar is present
            if bfio.JARS == None:
                raise FileNotFoundError(
                    "The loci_tools.jar could not be found.")
Example #22
0
 def plane_generator():
     for z_i in xrange(z_count):
         for i in xrange(len(CHANNELS)):
             channel_infix = CHANNELS[i]['file_infix']
             channel_file = '_'.join(
                 [prefix, cell_name, channel_infix, 't1.tif'])
             channel_path = os.path.join(data_path, channel_file)
             with bioformats.ImageReader(channel_path) as reader:
                 yield reader.read(index=z_i)
Example #23
0
    def __init__(self, file_path):
        ImagingExtractor.__init__(self)
        self.file_path = Path(file_path)
        self._start_javabridge_vm()
        self._reader = bioformats.ImageReader(str(self.file_path))

        # read metadata
        self._read_metadata()
        self._validate_metadata()
Example #24
0
def get_image6d_subset(imagefile,
                       sizes,
                       seriesstart=0,
                       seriesend=0,
                       tstart=0,
                       tend=0,
                       zstart=0,
                       zend=0,
                       chstart=0,
                       chend=0):
    """

    Attention: Still Experimental !!!

    This function will read a subset of the image file store them into a 6D numpy array.
    The 6D array has the following dimension order: [Series, T, Z, C, X, Y].
    """
    if not VM_STARTED:
        start_jvm()
    if VM_KILLED:
        jvm_error()

    rdr = bioformats.ImageReader(imagefile, perform_init=True)

    subsetSizeS = seriesend - seriesstart
    subsetSizeT = tend - tstart
    subsetSizeZ = zend - zstart
    subsetSizeC = chend - chstart

    subsetsizes = [
        subsetSizeS, subsetSizeT, subsetSizeZ, subsetSizeC, sizes[4], sizes[5]
    ]

    img6dsubset = np.zeros(subsetsizes,
                           dtype=BF2NP_DTYPE[rdr.rdr.getPixelType()])
    readstate = 'OK'
    readproblems = []

    # main loop to read the images from the data file
    for seriesID in range(seriesstart, seriesend):
        for timepoint in range(tstart, tend):
            for zplane in range(zstart, zend):
                for channel in range(chstart, chend):
                    try:
                        img6dsubset[seriesID, timepoint, zplane, channel, :, :] =\
                            rdr.read(series=seriesID, c=channel, z=zplane, t=timepoint, rescale=False)
                    except:
                        print(
                            'Problem reading data into Numpy Array for Series',
                            seriesID,
                            sys.exc_info()[1])
                        readstate = 'NOK'
                        readproblems = sys.exc_info()[1]

    rdr.close()

    return img6dsubset, readstate
Example #25
0
def get_image6d_multires(imagefile, MetaInfo):
    """
    This function will read the image data series by series.
    Every series will be stored inside a tuple as a 5D numpy array.
    The 5D array has the following dimension order: [T, Z, C, X, Y].
    """
    if not VM_STARTED:
        start_jvm()
    if VM_KILLED:
        jvm_error()

    rdr = bioformats.ImageReader(imagefile, perform_init=True)

    readstate = 'OK'
    readproblems = []

    # initialize the empty list that will hold all the 5D image arrays
    series_list = []

    numseries = MetaInfo['Sizes'][0]
    sizeT = MetaInfo['Sizes'][1]
    sizeZ = MetaInfo['Sizes'][2]
    sizeC = MetaInfo['Sizes'][3]

    for seriesID in range(0, numseries):
        # read the XY dimension of the first series
        current_sizeX = MetaInfo['SeriesDimensions'][seriesID][0]
        current_sizeY = MetaInfo['SeriesDimensions'][seriesID][1]

        newsize = [sizeT, sizeZ, sizeC, current_sizeX, current_sizeY]

        # create the 5D numpy array
        img5d = np.zeros(newsize, dtype=BF2NP_DTYPE[rdr.rdr.getPixelType()])

        # main loop to read the images from the data file
        for timepoint in range(0, sizeT):
            for zplane in range(0, sizeZ):
                for channel in range(0, sizeC):
                    try:
                        img5d[timepoint, zplane, channel, :, :] =\
                            rdr.read(series=seriesID, c=channel, z=zplane, t=timepoint, rescale=False)
                    except:
                        print(
                            'Problem reading data into Numpy Array for Series',
                            seriesID,
                            sys.exc_info()[1])
                        readstate = 'NOK'
                        readproblems = sys.exc_info()[1]

        # store the 5D array inside a tuple
        series_list.append(img5d)
        # clear the array from memory
        img5d = None

    rdr.close()

    return series_list, readstate
Example #26
0
def image_5d(file_name,
             series=0,
             rescale=False,
             frames=None,
             zslices=None,
             channels=None):
    """Read a single series as 5d numpy array

    Args:
        file_name (str): path to file
        series (int, optional): series to open. Defaults to 0.
        rescale (bool, optional): rescale each plane to min/max. Defaults to False.
        frames (list[int], optional): list of frame indices to read. Defaults to None.
        zslices (list[int], optional): list of zslice indices to read. Defaults to None.
        channels (list[int], optional): list of channel indices to read. Defaults to None.

    Returns:
        numpy.array: 5d numpy array (TZCYX)
    """

    JVM().start()

    with bf.ImageReader(file_name) as reader:
        reader.rdr.setSeries(series)

        dtype = get_numpy_pixel_type(reader.rdr.getPixelType())
        t_size, z_size, c_size, y_size, x_size = _get_TXCYX_shape(reader)

        t_list = range(t_size)
        if frames is not None:
            t_list = sorted(list(set(frames) & set(t_list)))
        assert len(t_list) > 0, "Please choose at least one valid frame"

        z_list = range(z_size)
        if zslices is not None:
            z_list = sorted(list(set(zslices) & set(z_list)))
        assert len(z_list) > 0, "Please choose at least one valid z-slice"

        c_list = range(c_size)
        if channels is not None:
            c_list = sorted(list(set(channels) & set(c_list)))
        assert len(c_list) > 0, "Please choose at least one valid channel"

        img_5d = np.zeros(
            (len(t_list), len(z_list), len(c_list), y_size, x_size),
            dtype=dtype)

        for ti, t in enumerate(t_list):
            for zi, z in enumerate(z_list):
                for ci, c in enumerate(c_list):
                    img_5d[ti, zi, ci, :, :] = reader.read(series=series,
                                                           z=z,
                                                           t=t,
                                                           c=c,
                                                           rescale=rescale)
    return img_5d
Example #27
0
def load_bioformats(path, folder_batch="", channel=None, no_meta_direct=False):
    meta = metadata(path)

    if channel:
        image = np.empty(
            (meta['SizeT'], meta['SizeZ'], meta['SizeX'], meta['SizeY'], 1))
        with bioformats.ImageReader(path) as rdr:
            for t in range(0, meta['SizeT']):
                for z in range(0, meta['SizeZ']):
                    image[t, z, :, :, 0] = rdr.read(c=channel,
                                                    z=z,
                                                    t=t,
                                                    series=None,
                                                    index=None,
                                                    rescale=False,
                                                    wants_max_intensity=False,
                                                    channel_names=None)
    else:
        image = np.empty((meta['SizeT'], meta['SizeZ'], meta['SizeX'],
                          meta['SizeY'], meta['SizeC']))
        with bioformats.ImageReader(path) as rdr:
            for t in range(0, meta['SizeT']):
                for z in range(0, meta['SizeZ']):
                    for c in range(0, meta['SizeC']):
                        image[t, z, :, :,
                              c] = rdr.read(c=c,
                                            z=z,
                                            t=t,
                                            series=None,
                                            index=None,
                                            rescale=False,
                                            wants_max_intensity=False,
                                            channel_names=None)

    if no_meta_direct == True:
        return (np.squeeze(image))
    else:
        if folder_batch:
            path = folder_batch
            return (np.squeeze(image), meta, _new_directory_batch(path, meta))
        else:
            return (np.squeeze(image), meta, _new_directory(path, meta))
Example #28
0
 def load_timelapse(self, name):
     "Loads a TXY record"
     numframes = self.get_size('T')
     axes = self.get_axes()
     reader = bioformats.ImageReader(name)
     kw = dict(series=self.index, rescale=False)
     images = np.array(
         [reader.read(t=i, **kw) for i in range(1, numframes)])
     out = fseq.from_array(images)
     out.meta['axes'] = axes
     return out
Example #29
0
 def plane_generator():
     for z_i in xrange(z_count):
         for channel in CHANNELS:
             if channel == "Cell membrane":
                 channel_path = prefix + "cell.tif"
             elif channel == "DNA":
                 channel_path = prefix + "nucleus.tif"
             elif channel == "protein":
                 channel_path = tif_name
             with bioformats.ImageReader(channel_path) as reader:
                 yield reader.read(index=z_i)
Example #30
0
def get_tiled_omexml_metadata(path=None, url=None, *, group_file=True):
    """
    Read tiled czi image and get ZeissCZIReader without stitching

    Parameters
    ---------
    path : str, default None
        path to the czi file
    url : str, default None
        url to the czi file (optional)
    groupfiles: bool, default True
        utilize the groupfiles option to take the directory structure into account.

    Returns
    -------
    xml : str
        the OME-XML string

    Notes
    -----
    Copied & modified from bioformats.get_omexml_metadata
    """

    with bioformats.ImageReader(path=path, url=url, perform_init=False) as rdr:
        #
        # Below, "in" is a keyword and Rhino's parser is just a little wonky I fear.
        #
        # It is critical that setGroupFiles be set to false, goodness knows
        # why, but if you don't the series count is wrong for flex files.
        #
        script = f"""
        importClass(Packages.loci.common.services.ServiceFactory,
                    Packages.loci.formats.services.OMEXMLService,
                    Packages.loci.formats['in'].ZeissCZIReader,
                    Packages.loci.formats['in'].DefaultMetadataOptions,
                    Packages.loci.formats['in'].DynamicMetadataOptions,
                    Packages.loci.formats['in'].MetadataLevel);
        reader.setGroupFiles({'true' if group_file else 'false'});
        reader.setOriginalMetadataPopulated(true);
        var service = new ServiceFactory().getInstance(OMEXMLService);
        var metadata = service.createOMEXMLMetadata();
        reader.setMetadataStore(metadata);
        reader.setMetadataOptions(new DefaultMetadataOptions(MetadataLevel.ALL));
        var dynop=DynamicMetadataOptions();
        dynop.set(ZeissCZIReader.ALLOW_AUTOSTITCHING_KEY,'false');
        dynop.set(ZeissCZIReader.INCLUDE_ATTACHMENTS_KEY,'false');
        reader.setMetadataOptions(dynop);
        reader.setId(path);
        var xml = service.getOMEXML(metadata);
        xml;
        """
        xml = jutil.run_script(script, dict(path=rdr.path, reader=rdr.rdr))
    return xml