Exemplo n.º 1
0
    def init_reader(self):
        mdoptions = metadatatools.get_metadata_options(metadatatools.ALL)
        self.rdr.setMetadataOptions(mdoptions)
        self.rdr.setGroupFiles(False)
        self.metadata = metadatatools.createOMEXMLMetadata()
        self.rdr.setMetadataStore(self.metadata)
        try:
            self.rdr.setId(self.path)
        except jutil.JavaException as e:
            # logger.warn(e.message)
            # for line in traceback.format_exc().split("\n"):
            #     logger.warn(line)
            je = e.throwable

            if has_omero_packages() and jutil.is_instance_of(
                    je, "Glacier2/PermissionDeniedException"):
                # Handle at a higher level
                raise
            if jutil.is_instance_of(je, "loci/formats/FormatException"):
                # je = jutil.call(je, "getCause",
                #                 "()Ljava/lang/Throwable;")
                # Handle at a higher level
                raise
            if jutil.is_instance_of(je, "java/io/FileNotFoundException"):
                raise IOError(errno.ENOENT,
                              "The file, \"%s\", does not exist." % self.path,
                              self.path)
            e2 = IOError(
                errno.EINVAL,
                "Could not load the file as an image (see log for details)",
                self.path.encode('utf-8'))
            raise e2
Exemplo n.º 2
0
def __load_using_bioformats(path, c, z, t, series, index, rescale,
                            wants_max_intensity, channel_names):
    FormatTools = make_format_tools_class()
    ImageReader = make_image_reader_class()
    ChannelSeparator = make_reader_wrapper_class(
        "loci/formats/ChannelSeparator")

    #
    # Bioformats is more picky about slashes than Python
    #
    if sys.platform.startswith("win"):
        path = path.replace("/", os.path.sep)
    #
    # Bypass the ImageReader and scroll through the class list. The
    # goal here is to ask the FormatHandler if it thinks it could
    # possibly parse the file, then only give the FormatReader access
    # to the open file stream so it can't damage the file server.
    #
    # Pass 0 - allow access to stream if reader believes it is the correct
    #          reader no matter what the file contents.
    # Pass 1 - allow access to stream if reader indicates that it supports
    #          files with this file's suffix.
    # Pass 2 - allow all readers access to the stream
    #

    env = jutil.get_env()
    with GetImageReader(path) as rdr:
        mdoptions = metadatatools.get_metadata_options(metadatatools.ALL)
        rdr.setMetadataOptions(mdoptions)
        rdr.setGroupFiles(False)
        metadata = metadatatools.createOMEXMLMetadata()
        rdr.setMetadataStore(metadata)
        rdr.setId(path)
        width = rdr.getSizeX()
        height = rdr.getSizeY()
        pixel_type = rdr.getPixelType()
        little_endian = rdr.isLittleEndian()
        if pixel_type == FormatTools.INT8:
            dtype = np.char
            scale = 255
        elif pixel_type == FormatTools.UINT8:
            dtype = np.uint8
            scale = 255
        elif pixel_type == FormatTools.UINT16:
            dtype = '<u2' if little_endian else '>u2'
            scale = 65535
        elif pixel_type == FormatTools.INT16:
            dtype = '<i2' if little_endian else '>i2'
            scale = 65535
        elif pixel_type == FormatTools.UINT32:
            dtype = '<u4' if little_endian else '>u4'
            scale = 2**32
        elif pixel_type == FormatTools.INT32:
            dtype = '<i4' if little_endian else '>i4'
            scale = 2**32 - 1
        elif pixel_type == FormatTools.FLOAT:
            dtype = '<f4' if little_endian else '>f4'
            scale = 1
        elif pixel_type == FormatTools.DOUBLE:
            dtype = '<f8' if little_endian else '>f8'
            scale = 1
        max_sample_value = rdr.getMetadataValue('MaxSampleValue')
        if max_sample_value is not None:
            try:
                scale = jutil.call(max_sample_value, 'intValue', '()I')
            except:
                bioformats.logger.warning(
                    "WARNING: failed to get MaxSampleValue for image. Intensities may be improperly scaled."
                )
        if series is not None:
            rdr.setSeries(series)
        if index is not None:
            image = np.frombuffer(rdr.openBytes(index), dtype)
            if len(image) / height / width in (3, 4):
                n_channels = int(len(image) / height / width)
                if rdr.isInterleaved():
                    image.shape = (height, width, n_channels)
                else:
                    image.shape = (n_channels, height, width)
                    image = image.transpose(1, 2, 0)
            else:
                image.shape = (height, width)
        elif rdr.isRGB() and rdr.isInterleaved():
            index = rdr.getIndex(z, 0, t)
            image = np.frombuffer(rdr.openBytes(index), dtype)
            image.shape = (height, width, 3)
        elif c is not None and rdr.getRGBChannelCount() == 1:
            index = rdr.getIndex(z, c, t)
            image = np.frombuffer(rdr.openBytes(index), dtype)
            image.shape = (height, width)
        elif rdr.getRGBChannelCount() > 1:
            n_planes = rdr.getRGBChannelCount()
            rdr = ChannelSeparator(rdr)
            planes = [
                np.frombuffer(rdr.openBytes(rdr.getIndex(z, i, t)), dtype)
                for i in range(n_planes)
            ]
            if len(planes) > 3:
                planes = planes[:3]
            elif len(planes) < 3:
                # > 1 and < 3 means must be 2
                # see issue #775
                planes.append(np.zeros(planes[0].shape, planes[0].dtype))
            image = np.dstack(planes)
            image.shape = (height, width, 3)
        elif rdr.getSizeC() > 1:
            images = [
                np.frombuffer(rdr.openBytes(rdr.getIndex(z, i, t)), dtype)
                for i in range(rdr.getSizeC())
            ]
            image = np.dstack(images)
            image.shape = (height, width, rdr.getSizeC())
            if not channel_names is None:
                metadata = metadatatools.MetadataRetrieve(metadata)
                for i in range(rdr.getSizeC()):
                    index = rdr.getIndex(z, 0, t)
                    channel_name = metadata.getChannelName(index, i)
                    if channel_name is None:
                        channel_name = metadata.getChannelID(index, i)
                    channel_names.append(channel_name)
        elif rdr.isIndexed():
            #
            # The image data is indexes into a color lookup-table
            # But sometimes the table is the identity table and just generates
            # a monochrome RGB image
            #
            index = rdr.getIndex(z, 0, t)
            image = np.frombuffer(rdr.openBytes(index), dtype)
            if pixel_type in (FormatTools.INT16, FormatTools.UINT16):
                lut = rdr.get16BitLookupTable()
                lut = np.array([
                    env.get_short_array_elements(d)
                    for d in env.get_object_array_elements(lut)
                ]).transpose()
            else:
                lut = rdr.get8BitLookupTable()
                lut = np.array([
                    env.get_byte_array_elements(d)
                    for d in env.get_object_array_elements(lut)
                ]).transpose()
            image.shape = (height, width)
            if not np.all(lut == np.arange(lut.shape[0])[:, np.newaxis]):
                image = lut[image, :]
        else:
            index = rdr.getIndex(z, 0, t)
            image = np.frombuffer(rdr.openBytes(index), dtype)
            image.shape = (height, width)

        rdr.close()
    if rescale:
        image = image.astype(np.float32) / float(scale)
    if wants_max_intensity:
        return image, scale
    return image
Exemplo n.º 3
0
 def fn(path=path, c=c, z=z, t=t, series=series, index=index,
        rescale=rescale, wants_max_intensity=wants_max_intensity,
        channel_names=channel_names):
     FormatTools = make_format_tools_class()
     ImageReader = make_image_reader_class()
     ChannelSeparator = make_reader_wrapper_class(
         "loci/formats/ChannelSeparator")
     
     #
     # Bioformats is more picky about slashes than Python
     #
     if sys.platform.startswith("win"):
         path = path.replace("/",os.path.sep)
     #
     # Bypass the ImageReader and scroll through the class list. The
     # goal here is to ask the FormatHandler if it thinks it could
     # possibly parse the file, then only give the FormatReader access
     # to the open file stream so it can't damage the file server.
     #
     
     env = jutil.get_env()
     class_list = get_class_list()
     stream = jutil.make_instance('loci/common/RandomAccessInputStream',
                                  '(Ljava/lang/String;)V', path)
     filename = os.path.split(path)[1]
     IFormatReader = make_iformat_reader_class()
     rdr = None
     for klass in env.get_object_array_elements(class_list.get_classes()):
         wclass = jutil.get_class_wrapper(klass, True)
         maybe_rdr = IFormatReader()
         maybe_rdr.o = wclass.newInstance()
         maybe_rdr.setGroupFiles(False)
         if maybe_rdr.suffixNecessary:
             if not maybe_rdr.isThisTypeSZ(filename, False):
                 continue
             if maybe_rdr.suffixSufficient:
                 rdr = maybe_rdr
                 break
         if (maybe_rdr.isThisTypeStream(stream)):
             rdr = maybe_rdr
             break
     if rdr is None:
         raise ValueError("Could not find a Bio-Formats reader for %s", path)
     mdoptions = metadatatools.get_metadata_options(metadatatools.ALL)
     rdr.setMetadataOptions(mdoptions)
     metadata = metadatatools.createOMEXMLMetadata()
     rdr.setMetadataStore(metadata)
     rdr.setId(path)
     width = rdr.getSizeX()
     height = rdr.getSizeY()
     pixel_type = rdr.getPixelType()
     little_endian = rdr.isLittleEndian()
     if pixel_type == FormatTools.INT8:
         dtype = np.char
         scale = 255
     elif pixel_type == FormatTools.UINT8:
         dtype = np.uint8
         scale = 255
     elif pixel_type == FormatTools.UINT16:
         dtype = '<u2' if little_endian else '>u2'
         scale = 65535
     elif pixel_type == FormatTools.INT16:
         dtype = '<i2' if little_endian else '>i2'
         scale = 65535
     elif pixel_type == FormatTools.UINT32:
         dtype = '<u4' if little_endian else '>u4'
         scale = 2**32
     elif pixel_type == FormatTools.INT32:
         dtype = '<i4' if little_endian else '>i4'
         scale = 2**32-1
     elif pixel_type == FormatTools.FLOAT:
         dtype = '<f4' if little_endian else '>f4'
         scale = 1
     elif pixel_type == FormatTools.DOUBLE:
         dtype = '<f8' if little_endian else '>f8'
         scale = 1
     max_sample_value = rdr.getMetadataValue('MaxSampleValue')
     if max_sample_value is not None:
         try:
             scale = jutil.call(max_sample_value, 'intValue', '()I')
         except:
             bioformats.logger.warning("WARNING: failed to get MaxSampleValue for image. Intensities may be improperly scaled.")
     if series is not None:
         rdr.setSeries(series)
     if index is not None:
         image = np.frombuffer(rdr.openBytes(index), dtype)
         if len(image) / height / width in (3,4):
             image.shape = (height, width, int(len(image) / height / width))
         else:
             image.shape = (height, width)
     elif rdr.isRGB() and rdr.isInterleaved():
         index = rdr.getIndex(z,0,t)
         image = np.frombuffer(rdr.openBytes(index), dtype)
         image.shape = (height, width, 3)
     elif c is not None and rdr.getRGBChannelCount() == 1:
         index = rdr.getIndex(z,c,t)
         image = np.frombuffer(rdr.openBytes(index), dtype)
         image.shape = (height, width)
     elif rdr.getRGBChannelCount() > 1:
         rdr.close()
         rdr = ImageReader()
         rdr.allowOpenToCheckType(False)
         rdr = ChannelSeparator(rdr)
         rdr.setGroupFiles(False)
         rdr.setId(path)
         red_image, green_image, blue_image = [
             np.frombuffer(rdr.openBytes(rdr.getIndex(z,i,t)),dtype)
             for i in range(3)]
         image = np.dstack((red_image, green_image, blue_image))
         image.shape=(height,width,3)
     elif rdr.getSizeC() > 1:
         images = [np.frombuffer(rdr.openBytes(rdr.getIndex(z,i,t)), dtype)
                   for i in range(rdr.getSizeC())]
         image = np.dstack(images)
         image.shape = (height, width, rdr.getSizeC())
         if not channel_names is None:
             metadata = metadatatools.MetadataRetrieve(metadata)
             for i in range(rdr.getSizeC()):
                 index = rdr.getIndex(z, 0, t)
                 channel_name = metadata.getChannelName(index, i)
                 if channel_name is None:
                     channel_name = metadata.getChannelID(index, i)
                 channel_names.append(channel_name)
     else:
         index = rdr.getIndex(z,0,t)
         image = np.frombuffer(rdr.openBytes(index),dtype)
         image.shape = (height,width)
         
     rdr.close()
     jutil.call(stream, 'close', '()V')
     del rdr
     #
     # Run the Java garbage collector here.
     #
     jutil.static_call("java/lang/System", "gc","()V")
     if rescale:
         image = image.astype(np.float32) / float(scale)
     if wants_max_intensity:
         return image, scale
     return image
Exemplo n.º 4
0
def __load_using_bioformats(path, c, z, t, series, index, rescale,
                            wants_max_intensity, channel_names):
    FormatTools = make_format_tools_class()
    ImageReader = make_image_reader_class()
    ChannelSeparator = make_reader_wrapper_class(
        "loci/formats/ChannelSeparator")
    
    #
    # Bioformats is more picky about slashes than Python
    #
    if sys.platform.startswith("win"):
        path = path.replace("/",os.path.sep)
    #
    # Bypass the ImageReader and scroll through the class list. The
    # goal here is to ask the FormatHandler if it thinks it could
    # possibly parse the file, then only give the FormatReader access
    # to the open file stream so it can't damage the file server.
    #
    # Pass 0 - allow access to stream if reader believes it is the correct
    #          reader no matter what the file contents.
    # Pass 1 - allow access to stream if reader indicates that it supports
    #          files with this file's suffix.
    # Pass 2 - allow all readers access to the stream
    #
    
    env = jutil.get_env()
    with GetImageReader(path) as rdr:
        mdoptions = metadatatools.get_metadata_options(metadatatools.ALL)
        rdr.setMetadataOptions(mdoptions)
        rdr.setGroupFiles(False)
        metadata = metadatatools.createOMEXMLMetadata()
        rdr.setMetadataStore(metadata)
        rdr.setId(path)
        if series is not None:
            rdr.setSeries(series)
        width = rdr.getSizeX()
        height = rdr.getSizeY()
        pixel_type = rdr.getPixelType()
        little_endian = rdr.isLittleEndian()
        if pixel_type == FormatTools.INT8:
            dtype = np.char
            scale = 255
        elif pixel_type == FormatTools.UINT8:
            dtype = np.uint8
            scale = 255
        elif pixel_type == FormatTools.UINT16:
            dtype = '<u2' if little_endian else '>u2'
            scale = 65535
        elif pixel_type == FormatTools.INT16:
            dtype = '<i2' if little_endian else '>i2'
            scale = 65535
        elif pixel_type == FormatTools.UINT32:
            dtype = '<u4' if little_endian else '>u4'
            scale = 2**32
        elif pixel_type == FormatTools.INT32:
            dtype = '<i4' if little_endian else '>i4'
            scale = 2**32-1
        elif pixel_type == FormatTools.FLOAT:
            dtype = '<f4' if little_endian else '>f4'
            scale = 1
        elif pixel_type == FormatTools.DOUBLE:
            dtype = '<f8' if little_endian else '>f8'
            scale = 1
        max_sample_value = rdr.getMetadataValue('MaxSampleValue')
        if max_sample_value is not None:
            try:
                scale = jutil.call(max_sample_value, 'intValue', '()I')
            except:
                bioformats.logger.warning("WARNING: failed to get MaxSampleValue for image. Intensities may be improperly scaled.")
        if index is not None:
            image = np.frombuffer(rdr.openBytes(index), dtype)
            if len(image) / height / width in (3,4):
                n_channels = int(len(image) / height / width)
                if rdr.isInterleaved():
                    image.shape = (height, width, n_channels)
                else:
                    image.shape = (n_channels, height, width)
                    image = image.transpose(1, 2, 0)
            else:
                image.shape = (height, width)
        elif rdr.isRGB() and rdr.isInterleaved():
            index = rdr.getIndex(z,0,t)
            image = np.frombuffer(rdr.openBytes(index), dtype)
            image.shape = (height, width, 3)
        elif c is not None and rdr.getRGBChannelCount() == 1:
            index = rdr.getIndex(z,c,t)
            image = np.frombuffer(rdr.openBytes(index), dtype)
            image.shape = (height, width)
        elif rdr.getRGBChannelCount() > 1:
            n_planes = rdr.getRGBChannelCount()
            rdr = ChannelSeparator(rdr)
            planes = [
                np.frombuffer(rdr.openBytes(rdr.getIndex(z,i,t)),dtype)
                for i in range(n_planes)]
            if len(planes) > 3:
                planes = planes[:3]
            elif len(planes) < 3:
                # > 1 and < 3 means must be 2
                # see issue #775
                planes.append(np.zeros(planes[0].shape, planes[0].dtype))
            image = np.dstack(planes)
            image.shape=(height,width,3)
        elif rdr.getSizeC() > 1:
            images = [np.frombuffer(rdr.openBytes(rdr.getIndex(z,i,t)), dtype)
                      for i in range(rdr.getSizeC())]
            image = np.dstack(images)
            image.shape = (height, width, rdr.getSizeC())
            if not channel_names is None:
                metadata = metadatatools.MetadataRetrieve(metadata)
                for i in range(rdr.getSizeC()):
                    index = rdr.getIndex(z, 0, t)
                    channel_name = metadata.getChannelName(index, i)
                    if channel_name is None:
                        channel_name = metadata.getChannelID(index, i)
                    channel_names.append(channel_name)
        elif rdr.isIndexed():
            #
            # The image data is indexes into a color lookup-table
            # But sometimes the table is the identity table and just generates
            # a monochrome RGB image
            #
            index = rdr.getIndex(z,0,t)
            image = np.frombuffer(rdr.openBytes(index),dtype)
            if pixel_type in (FormatTools.INT16, FormatTools.UINT16):
                lut = rdr.get16BitLookupTable()
                lut = np.array(
                    [env.get_short_array_elements(d)
                     for d in env.get_object_array_elements(lut)]).transpose()
            else:
                lut = rdr.get8BitLookupTable()
                lut = np.array(
                    [env.get_byte_array_elements(d)
                     for d in env.get_object_array_elements(lut)]).transpose()
            image.shape = (height, width)
            if not np.all(lut == np.arange(lut.shape[0])[:, np.newaxis]):
                image = lut[image, :]
        else:
            index = rdr.getIndex(z,0,t)
            image = np.frombuffer(rdr.openBytes(index),dtype)
            image.shape = (height,width)
            
        rdr.close()
    if rescale:
        image = image.astype(np.float32) / float(scale)
    if wants_max_intensity:
        return image, scale
    return image