Search in sources :

Example 51 with ImageReader

use of loci.formats.ImageReader in project bioformats by openmicroscopy.

the class TrestleReader method parseROIs.

// -- Helper methods --
private void parseROIs(MetadataStore store) throws FormatException, IOException {
    String roiID = MetadataTools.createLSID("ROI", 0, 0);
    String maskID = MetadataTools.createLSID("Shape", 0, 0);
    store.setROIID(roiID, 0);
    store.setMaskID(maskID, 0, 0);
    String positionData = DataTools.readFile(roiDrawFile);
    String[] coordinates = positionData.split("[ ,]");
    double x1 = Double.parseDouble(coordinates[1]);
    double y1 = Double.parseDouble(coordinates[2]);
    double x2 = Double.parseDouble(coordinates[3]);
    double y2 = Double.parseDouble(coordinates[5]);
    store.setMaskX(x1, 0, 0);
    store.setMaskY(y1, 0, 0);
    store.setMaskWidth(x2 - x1, 0, 0);
    store.setMaskHeight(y2 - y1, 0, 0);
    store.setImageROIRef(roiID, 0, 0);
    ImageReader roiReader = new ImageReader();
    roiReader.setId(roiFile);
    byte[] roiPixels = roiReader.openBytes(0);
    roiReader.close();
    BitWriter bits = new BitWriter(roiPixels.length / 8);
    for (int i = 0; i < roiPixels.length; i++) {
        bits.write(roiPixels[i] == 0 ? 0 : 1, 1);
    }
    store.setMaskBinData(bits.toByteArray(), 0, 0);
}
Also used : BitWriter(loci.formats.codec.BitWriter) ImageReader(loci.formats.ImageReader)

Example 52 with ImageReader

use of loci.formats.ImageReader in project bioformats by openmicroscopy.

the class ConvertToOmeTiff method main.

public static void main(String[] args) throws Exception {
    if (args.length == 0) {
        System.out.println("Usage: java ConvertToOmeTiff file1 file2 ...");
        return;
    }
    ImageReader reader = new ImageReader();
    OMETiffWriter writer = new OMETiffWriter();
    for (int i = 0; i < args.length; i++) {
        String id = args[i];
        int dot = id.lastIndexOf(".");
        String outId = (dot >= 0 ? id.substring(0, dot) : id) + ".ome.tif";
        System.out.print("Converting " + id + " to " + outId + " ");
        // record metadata to OME-XML format
        ServiceFactory factory = new ServiceFactory();
        OMEXMLService service = factory.getInstance(OMEXMLService.class);
        IMetadata omexmlMeta = service.createOMEXMLMetadata();
        reader.setMetadataStore(omexmlMeta);
        reader.setId(id);
        // configure OME-TIFF writer
        writer.setMetadataRetrieve(omexmlMeta);
        writer.setId(outId);
        // writer.setCompression("J2K");
        // write out image planes
        int seriesCount = reader.getSeriesCount();
        for (int s = 0; s < seriesCount; s++) {
            reader.setSeries(s);
            writer.setSeries(s);
            int planeCount = reader.getImageCount();
            for (int p = 0; p < planeCount; p++) {
                byte[] plane = reader.openBytes(p);
                // write plane to output file
                writer.saveBytes(p, plane);
                System.out.print(".");
            }
        }
        writer.close();
        reader.close();
        System.out.println(" [done]");
    }
}
Also used : OMETiffWriter(loci.formats.out.OMETiffWriter) IMetadata(loci.formats.meta.IMetadata) ServiceFactory(loci.common.services.ServiceFactory) ImageReader(loci.formats.ImageReader) OMEXMLService(loci.formats.services.OMEXMLService)

Example 53 with ImageReader

use of loci.formats.ImageReader in project bioformats by openmicroscopy.

the class Colorizer method applyColors.

// -- Colorizer methods --
public List<ImagePlus> applyColors(List<ImagePlus> imps) {
    final ImporterOptions options = process.getOptions();
    final ImageProcessorReader reader = process.getReader();
    final DimensionSwapper dimSwapper = process.getDimensionSwapper();
    final ChannelFiller channelFiller = process.getChannelFiller();
    final ImageReader imageReader = process.getImageReader();
    for (int i = 0; i < imps.size(); i++) {
        ImagePlus imp = imps.get(i);
        final int series = (Integer) imp.getProperty(ImagePlusReader.PROP_SERIES);
        reader.setSeries(series);
        // get LUT for each channel
        final String stackOrder = dimSwapper.getDimensionOrder();
        final int zSize = imp.getNSlices();
        final int cSize = imp.getNChannels();
        final int tSize = imp.getNFrames();
        final int stackSize = imp.getStackSize();
        final LUT[] channelLUTs = new LUT[cSize];
        boolean hasChannelLUT = false;
        for (int c = 0; c < cSize; c++) {
            final int index = FormatTools.getIndex(stackOrder, zSize, cSize, tSize, stackSize, 0, c, 0);
            channelLUTs[c] = (LUT) imp.getProperty(ImagePlusReader.PROP_LUT + index);
            if (channelLUTs[c] != null)
                hasChannelLUT = true;
        }
        // compute color mode and LUTs to use
        int mode = -1;
        LUT[] luts;
        if (options.isColorModeDefault()) {
            // NB: Default color mode behavior depends on the situation.
            final boolean isRGB = reader.isRGB() || imageReader.isRGB();
            if (isRGB || channelFiller.isFilled()) {
                // NB: The original data had more than one channel per plane
                // (e.g., RGB image planes), so we use the composite display mode.
                mode = CompositeImage.COMPOSITE;
                // preserve original LUTs
                luts = makeLUTs(channelLUTs, true);
            } else if (hasChannelLUT) {
                // NB: The original data had only one channel per plane,
                // but had at least one lookup table defined. We use the color
                // display mode, with missing LUTs as grayscale.
                mode = CompositeImage.COLOR;
                // preserve original LUTs
                luts = makeLUTs(channelLUTs, true);
            } else {
                // NB: The original data had only one channel per plane,
                // and had no lookup tables defined, so we use the grayscale mode.
                mode = CompositeImage.GRAYSCALE;
                luts = null;
            }
        } else if (options.isColorModeComposite()) {
            mode = CompositeImage.COMPOSITE;
            // preserve existing channel LUTs
            luts = makeLUTs(channelLUTs, true);
        } else if (options.isColorModeColorized()) {
            mode = CompositeImage.COLOR;
            // preserve existing channel LUTs
            luts = makeLUTs(channelLUTs, true);
        } else if (options.isColorModeGrayscale()) {
            mode = CompositeImage.GRAYSCALE;
            // use default (grayscale) channel LUTs
            luts = null;
        } else if (options.isColorModeCustom()) {
            mode = CompositeImage.COLOR;
            // override any existing channel LUTs
            luts = makeLUTs(series);
        } else {
            throw new IllegalStateException("Invalid color mode: " + options.getColorMode());
        }
        // apply color mode and LUTs
        final boolean doComposite = !options.isViewStandard() && mode != -1 && cSize > 1 && cSize <= 7;
        if (doComposite) {
            final ImagePlus toClose = imp;
            CompositeImage compImage = new CompositeImage(imp, mode) {

                @Override
                public void close() {
                    super.close();
                    toClose.close();
                }

                @Override
                public void show(String message) {
                    super.show(message);
                    // see ticket #12267
                    if (toClose instanceof VirtualImagePlus) {
                        int channel = getChannel();
                        double min = getDisplayRangeMin();
                        double max = getDisplayRangeMax();
                        for (int c = 0; c < cSize; c++) {
                            setPositionWithoutUpdate(c + 1, getSlice(), getFrame());
                            setDisplayRange(min, max);
                        }
                        reset();
                        setPosition(channel, getSlice(), getFrame());
                    }
                }
            };
            compImage.setProperty(ImagePlusReader.PROP_SERIES, series);
            if (luts != null)
                compImage.setLuts(luts);
            imps.set(i, compImage);
            imp = compImage;
        } else {
            // NB: Cannot use CompositeImage for some reason.
            if (luts != null && luts.length > 0 && luts[0] != null) {
                if (imp instanceof VirtualImagePlus) {
                    ((VirtualImagePlus) imp).setLUTs(luts);
                } else if (cSize == 1)
                    imp.getProcessor().setColorModel(luts[0]);
            }
            if (mode != -1 && cSize > 7) {
                // NB: Cannot use CompositeImage with more than seven channels.
                BF.warn(options.isQuiet(), "Data has too many channels for " + options.getColorMode() + " color mode");
            }
        }
        applyDisplayRanges(imp, series);
    }
    return imps;
}
Also used : ImageProcessorReader(loci.plugins.util.ImageProcessorReader) VirtualImagePlus(loci.plugins.util.VirtualImagePlus) ChannelFiller(loci.formats.ChannelFiller) LUT(ij.process.LUT) VirtualImagePlus(loci.plugins.util.VirtualImagePlus) ImagePlus(ij.ImagePlus) CompositeImage(ij.CompositeImage) DimensionSwapper(loci.formats.DimensionSwapper) ImageReader(loci.formats.ImageReader)

Example 54 with ImageReader

use of loci.formats.ImageReader in project bioformats by openmicroscopy.

the class Colorizer method makeLUTs.

private LUT[] makeLUTs(ColorModel[] cm, boolean colorize) {
    // lookup tables can come from one of three places (in order of precedence):
    // 1) Color attribute defined in the MetadataStore
    // 2) lookup table returned by the reader's get8BitLookupTable or
    // get16BitLookupTable methods
    // 3) EmissionWavelength attribute defined in the MetadataStore
    final ImporterOptions options = process.getOptions();
    final LUT[] luts = new LUT[cm.length];
    for (int c = 0; c < luts.length; c++) {
        if (cm[c] instanceof LUT)
            luts[c] = (LUT) cm[c];
        else if (cm[c] instanceof IndexColorModel) {
            luts[c] = new LUT((IndexColorModel) cm[c], 0, 255);
        }
        Color color = null;
        if (colorize) {
            // rather than always assuming that the first channel is red, the
            // second green, etc. we will take into account the channel color
            // metadata and the acquisition wavelength
            ImageReader reader = process.getImageReader();
            MetadataStore store = reader.getMetadataStore();
            if (store instanceof MetadataRetrieve) {
                MetadataRetrieve retrieve = (MetadataRetrieve) store;
                if (c < retrieve.getChannelCount(reader.getSeries())) {
                    ome.xml.model.primitives.Color metaColor = retrieve.getChannelColor(reader.getSeries(), c);
                    if (metaColor != null) {
                        int r = metaColor.getRed();
                        int g = metaColor.getGreen();
                        int b = metaColor.getBlue();
                        int a = metaColor.getAlpha();
                        color = new Color(r, g, b, a);
                    } else if (luts[c] == null) {
                        Length wavelength = retrieve.getChannelEmissionWavelength(reader.getSeries(), c);
                        if (wavelength != null) {
                            double wave = wavelength.value(UNITS.NANOMETER).doubleValue();
                            if (wave >= BLUE_MIN && wave < BLUE_TO_GREEN_MIN) {
                                color = Color.BLUE;
                            } else if (wave >= BLUE_TO_GREEN_MIN && wave < GREEN_TO_RED_MIN) {
                                color = Color.GREEN;
                            } else if (wave >= GREEN_TO_RED_MIN && wave <= RED_MAX) {
                                color = Color.RED;
                            }
                        }
                    }
                }
            }
        }
        if (color == null && luts[c] == null) {
            color = options.getDefaultCustomColor(c);
        }
        if (color != null) {
            luts[c] = makeLUT(color);
        }
    }
    return luts;
}
Also used : Color(java.awt.Color) LUT(ij.process.LUT) MetadataStore(loci.formats.meta.MetadataStore) Length(ome.units.quantity.Length) ImageReader(loci.formats.ImageReader) MetadataRetrieve(loci.formats.meta.MetadataRetrieve) IndexColorModel(java.awt.image.IndexColorModel)

Example 55 with ImageReader

use of loci.formats.ImageReader in project bioformats by openmicroscopy.

the class ImportProcess method createBaseReader.

/**
 * Initializes an {@link loci.formats.IFormatReader}
 * according to the current configuration.
 */
private void createBaseReader() throws FormatException, IOException {
    if (options.isLocal() || options.isHTTP()) {
        BF.status(options.isQuiet(), "Identifying " + idName);
        imageReader = LociPrefs.makeImageReader();
        baseReader = imageReader.getReader(options.isUsingPatternIds() ? new FilePattern(options.getId()).getFiles()[0] : options.getId());
    } else if (options.isOMERO()) {
        BF.status(options.isQuiet(), "Establishing server connection");
        try {
            ReflectedUniverse r = new ReflectedUniverse();
            r.exec("import loci.ome.io.OmeroReader");
            r.exec("baseReader = new OmeroReader()");
            ClassList<IFormatReader> classes = new ClassList<IFormatReader>(IFormatReader.class);
            r.setVar("classes", classes);
            r.exec("class = baseReader.getClass()");
            r.exec("classes.addClass(class)");
            imageReader = new ImageReader(classes);
            baseReader = imageReader.getReader(options.getId());
        } catch (Exception exc) {
            WindowTools.reportException(exc, options.isQuiet(), "Sorry, there was a problem communicating with the server.");
            cancel();
            return;
        }
    } else {
        WindowTools.reportException(null, options.isQuiet(), "Sorry, there has been an internal error: unknown data source");
        cancel();
        return;
    }
    // attach OME-XML metadata store
    Exception exc = null;
    try {
        ServiceFactory factory = new ServiceFactory();
        OMEXMLService service = factory.getInstance(OMEXMLService.class);
        meta = service.createOMEXMLMetadata();
        omeXML = null;
    } catch (DependencyException de) {
        exc = de;
    } catch (ServiceException se) {
        exc = se;
    }
    if (exc != null) {
        WindowTools.reportException(exc, options.isQuiet(), "Sorry, there was a problem constructing the OME-XML metadata store");
        throw new FormatException(exc);
    }
    baseReader.setMetadataStore(meta);
    BF.status(options.isQuiet(), "");
    DebugTools.enableIJLogging(IJ.debugMode);
}
Also used : IFormatReader(loci.formats.IFormatReader) ServiceException(loci.common.services.ServiceException) ServiceFactory(loci.common.services.ServiceFactory) FilePattern(loci.formats.FilePattern) ReflectedUniverse(loci.common.ReflectedUniverse) ClassList(loci.formats.ClassList) ImageReader(loci.formats.ImageReader) DependencyException(loci.common.services.DependencyException) EnumerationException(ome.xml.model.enums.EnumerationException) ServiceException(loci.common.services.ServiceException) DependencyException(loci.common.services.DependencyException) FormatException(loci.formats.FormatException) IOException(java.io.IOException) OMEXMLService(loci.formats.services.OMEXMLService) FormatException(loci.formats.FormatException)

Aggregations

ImageReader (loci.formats.ImageReader)71 ServiceFactory (loci.common.services.ServiceFactory)23 OMEXMLService (loci.formats.services.OMEXMLService)23 FormatException (loci.formats.FormatException)20 IFormatReader (loci.formats.IFormatReader)20 IMetadata (loci.formats.meta.IMetadata)19 Test (org.testng.annotations.Test)15 IOException (java.io.IOException)11 ChannelFiller (loci.formats.ChannelFiller)11 DependencyException (loci.common.services.DependencyException)10 ServiceException (loci.common.services.ServiceException)10 ChannelSeparator (loci.formats.ChannelSeparator)10 MinMaxCalculator (loci.formats.MinMaxCalculator)10 BufferedImageReader (loci.formats.gui.BufferedImageReader)8 ImageWriter (loci.formats.ImageWriter)7 File (java.io.File)6 FileStitcher (loci.formats.FileStitcher)6 OMETiffWriter (loci.formats.out.OMETiffWriter)6 Location (loci.common.Location)5 DimensionSwapper (loci.formats.DimensionSwapper)5