Search in sources :

Example 6 with MissingLibraryException

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

the class ImageConverter method testConvert.

// -- Utility methods --
/**
 * A utility method for converting a file from the command line.
 */
public boolean testConvert(IFormatWriter writer, String[] args) throws FormatException, IOException {
    nextOutputIndex.clear();
    options.setValidate(validate);
    writer.setMetadataOptions(options);
    firstTile = true;
    boolean success = parseArgs(args);
    if (!success) {
        return false;
    }
    if (printVersion) {
        CommandLineTools.printVersion();
        return true;
    }
    CommandLineTools.runUpgradeCheck(args);
    if (in == null || out == null) {
        printUsage();
        return false;
    }
    if (new Location(out).exists()) {
        if (overwrite == null) {
            LOGGER.warn("Output file {} exists.", out);
            LOGGER.warn("Do you want to overwrite it? ([y]/n)");
            BufferedReader r = new BufferedReader(new InputStreamReader(System.in, Constants.ENCODING));
            String choice = r.readLine().trim().toLowerCase();
            overwrite = !choice.startsWith("n");
        }
        if (!overwrite) {
            LOGGER.warn("Exiting; next time, please specify an output file that " + "does not exist.");
            return false;
        } else {
            new Location(out).delete();
        }
    }
    if (map != null)
        Location.mapId(in, map);
    long start = System.currentTimeMillis();
    LOGGER.info(in);
    reader = new ImageReader();
    if (stitch) {
        reader = new FileStitcher(reader);
        Location f = new Location(in);
        String pat = null;
        if (!f.exists()) {
            pat = in;
        } else {
            pat = FilePattern.findPattern(f);
        }
        if (pat != null)
            in = pat;
    }
    if (separate)
        reader = new ChannelSeparator(reader);
    if (merge)
        reader = new ChannelMerger(reader);
    if (fill)
        reader = new ChannelFiller(reader);
    minMax = null;
    if (autoscale) {
        reader = new MinMaxCalculator(reader);
        minMax = (MinMaxCalculator) reader;
    }
    reader.setMetadataOptions(options);
    reader.setGroupFiles(group);
    reader.setMetadataFiltered(true);
    reader.setOriginalMetadataPopulated(true);
    OMEXMLService service = null;
    try {
        ServiceFactory factory = new ServiceFactory();
        service = factory.getInstance(OMEXMLService.class);
        reader.setMetadataStore(service.createOMEXMLMetadata());
    } catch (DependencyException de) {
        throw new MissingLibraryException(OMEXMLServiceImpl.NO_OME_XML_MSG, de);
    } catch (ServiceException se) {
        throw new FormatException(se);
    }
    reader.setId(in);
    MetadataStore store = reader.getMetadataStore();
    MetadataTools.populatePixels(store, reader, false, false);
    boolean dimensionsSet = true;
    if (width == 0 || height == 0) {
        // otherwise default to series 0
        if (series >= 0) {
            reader.setSeries(series);
        }
        width = reader.getSizeX();
        height = reader.getSizeY();
        dimensionsSet = false;
    }
    if (channel >= reader.getEffectiveSizeC()) {
        throw new FormatException("Invalid channel '" + channel + "' (" + reader.getEffectiveSizeC() + " channels in source file)");
    }
    if (timepoint >= reader.getSizeT()) {
        throw new FormatException("Invalid timepoint '" + timepoint + "' (" + reader.getSizeT() + " timepoints in source file)");
    }
    if (zSection >= reader.getSizeZ()) {
        throw new FormatException("Invalid Z section '" + zSection + "' (" + reader.getSizeZ() + " Z sections in source file)");
    }
    if (store instanceof MetadataRetrieve) {
        try {
            String xml = service.getOMEXML(service.asRetrieve(store));
            OMEXMLMetadataRoot root = (OMEXMLMetadataRoot) store.getRoot();
            IMetadata meta = service.createOMEXMLMetadata(xml);
            if (series >= 0) {
                Image exportImage = new Image(root.getImage(series));
                Pixels exportPixels = new Pixels(root.getImage(series).getPixels());
                exportImage.setPixels(exportPixels);
                OMEXMLMetadataRoot newRoot = (OMEXMLMetadataRoot) meta.getRoot();
                while (newRoot.sizeOfImageList() > 0) {
                    newRoot.removeImage(newRoot.getImage(0));
                }
                newRoot.addImage(exportImage);
                meta.setRoot(newRoot);
                meta.setPixelsSizeX(new PositiveInteger(width), 0);
                meta.setPixelsSizeY(new PositiveInteger(height), 0);
                if (autoscale) {
                    store.setPixelsType(PixelType.UINT8, 0);
                }
                if (channel >= 0) {
                    meta.setPixelsSizeC(new PositiveInteger(1), 0);
                }
                if (zSection >= 0) {
                    meta.setPixelsSizeZ(new PositiveInteger(1), 0);
                }
                if (timepoint >= 0) {
                    meta.setPixelsSizeT(new PositiveInteger(1), 0);
                }
                writer.setMetadataRetrieve((MetadataRetrieve) meta);
            } else {
                for (int i = 0; i < reader.getSeriesCount(); i++) {
                    meta.setPixelsSizeX(new PositiveInteger(width), 0);
                    meta.setPixelsSizeY(new PositiveInteger(height), 0);
                    if (autoscale) {
                        store.setPixelsType(PixelType.UINT8, i);
                    }
                    if (channel >= 0) {
                        meta.setPixelsSizeC(new PositiveInteger(1), 0);
                    }
                    if (zSection >= 0) {
                        meta.setPixelsSizeZ(new PositiveInteger(1), 0);
                    }
                    if (timepoint >= 0) {
                        meta.setPixelsSizeT(new PositiveInteger(1), 0);
                    }
                }
                writer.setMetadataRetrieve((MetadataRetrieve) meta);
            }
        } catch (ServiceException e) {
            throw new FormatException(e);
        }
    }
    writer.setWriteSequentially(true);
    if (writer instanceof TiffWriter) {
        ((TiffWriter) writer).setBigTiff(bigtiff);
    } else if (writer instanceof ImageWriter) {
        IFormatWriter w = ((ImageWriter) writer).getWriter(out);
        if (w instanceof TiffWriter) {
            ((TiffWriter) w).setBigTiff(bigtiff);
        }
    }
    String format = writer.getFormat();
    LOGGER.info("[{}] -> {} [{}]", new Object[] { reader.getFormat(), out, format });
    long mid = System.currentTimeMillis();
    int total = 0;
    int num = writer.canDoStacks() ? reader.getSeriesCount() : 1;
    long read = 0, write = 0;
    int first = series == -1 ? 0 : series;
    int last = series == -1 ? num : series + 1;
    long timeLastLogged = System.currentTimeMillis();
    for (int q = first; q < last; q++) {
        reader.setSeries(q);
        firstTile = true;
        if (!dimensionsSet) {
            width = reader.getSizeX();
            height = reader.getSizeY();
        }
        int writerSeries = series == -1 ? q : 0;
        writer.setSeries(writerSeries);
        writer.setInterleaved(reader.isInterleaved() && !autoscale);
        writer.setValidBitsPerPixel(reader.getBitsPerPixel());
        int numImages = writer.canDoStacks() ? reader.getImageCount() : 1;
        int startPlane = (int) Math.max(0, firstPlane);
        int endPlane = (int) Math.min(numImages, lastPlane);
        numImages = endPlane - startPlane;
        if (channel >= 0) {
            numImages /= reader.getEffectiveSizeC();
        }
        if (zSection >= 0) {
            numImages /= reader.getSizeZ();
        }
        if (timepoint >= 0) {
            numImages /= reader.getSizeT();
        }
        total += numImages;
        int count = 0;
        for (int i = startPlane; i < endPlane; i++) {
            int[] coords = reader.getZCTCoords(i);
            if ((zSection >= 0 && coords[0] != zSection) || (channel >= 0 && coords[1] != channel) || (timepoint >= 0 && coords[2] != timepoint)) {
                continue;
            }
            String outputName = FormatTools.getFilename(q, i, reader, out, zeroPadding);
            if (outputName.equals(FormatTools.getTileFilename(0, 0, 0, outputName))) {
                writer.setId(outputName);
                if (compression != null)
                    writer.setCompression(compression);
            } else {
                int tileNum = outputName.indexOf(FormatTools.TILE_NUM);
                int tileX = outputName.indexOf(FormatTools.TILE_X);
                int tileY = outputName.indexOf(FormatTools.TILE_Y);
                if (tileNum < 0 && (tileX < 0 || tileY < 0)) {
                    throw new FormatException("Invalid file name pattern; " + FormatTools.TILE_NUM + " or both of " + FormatTools.TILE_X + " and " + FormatTools.TILE_Y + " must be specified.");
                }
            }
            int outputIndex = 0;
            if (nextOutputIndex.containsKey(outputName)) {
                outputIndex = nextOutputIndex.get(outputName);
            }
            long s = System.currentTimeMillis();
            long m = convertPlane(writer, i, outputIndex, outputName);
            long e = System.currentTimeMillis();
            read += m - s;
            write += e - m;
            nextOutputIndex.put(outputName, outputIndex + 1);
            if (i == endPlane - 1) {
                nextOutputIndex.remove(outputName);
            }
            // log number of planes processed every second or so
            if (count == numImages - 1 || (e - timeLastLogged) / 1000 > 0) {
                int current = (count - startPlane) + 1;
                int percent = 100 * current / numImages;
                StringBuilder sb = new StringBuilder();
                sb.append("\t");
                int numSeries = last - first;
                if (numSeries > 1) {
                    sb.append("Series ");
                    sb.append(q);
                    sb.append(": converted ");
                } else
                    sb.append("Converted ");
                LOGGER.info(sb.toString() + "{}/{} planes ({}%)", new Object[] { current, numImages, percent });
                timeLastLogged = e;
            }
            count++;
        }
    }
    writer.close();
    long end = System.currentTimeMillis();
    LOGGER.info("[done]");
    // output timing results
    float sec = (end - start) / 1000f;
    long initial = mid - start;
    float readAvg = (float) read / total;
    float writeAvg = (float) write / total;
    LOGGER.info("{}s elapsed ({}+{}ms per plane, {}ms overhead)", new Object[] { sec, readAvg, writeAvg, initial });
    return true;
}
Also used : ServiceFactory(loci.common.services.ServiceFactory) ChannelMerger(loci.formats.ChannelMerger) ImageWriter(loci.formats.ImageWriter) ChannelFiller(loci.formats.ChannelFiller) Image(ome.xml.model.Image) OMEXMLService(loci.formats.services.OMEXMLService) Pixels(ome.xml.model.Pixels) IMetadata(loci.formats.meta.IMetadata) ImageReader(loci.formats.ImageReader) MetadataRetrieve(loci.formats.meta.MetadataRetrieve) PositiveInteger(ome.xml.model.primitives.PositiveInteger) TiffWriter(loci.formats.out.TiffWriter) InputStreamReader(java.io.InputStreamReader) DependencyException(loci.common.services.DependencyException) ChannelSeparator(loci.formats.ChannelSeparator) FormatException(loci.formats.FormatException) MetadataStore(loci.formats.meta.MetadataStore) IFormatWriter(loci.formats.IFormatWriter) FileStitcher(loci.formats.FileStitcher) ServiceException(loci.common.services.ServiceException) OMEXMLMetadataRoot(ome.xml.meta.OMEXMLMetadataRoot) BufferedReader(java.io.BufferedReader) MinMaxCalculator(loci.formats.MinMaxCalculator) MissingLibraryException(loci.formats.MissingLibraryException) Location(loci.common.Location)

Example 7 with MissingLibraryException

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

the class ImageInfo method printOMEXML.

public void printOMEXML() throws MissingLibraryException, ServiceException {
    LOGGER.info("");
    MetadataStore ms = reader.getMetadataStore();
    if (baseReader instanceof ImageReader) {
        baseReader = ((ImageReader) baseReader).getReader();
    }
    OMEXMLService service;
    try {
        ServiceFactory factory = new ServiceFactory();
        service = factory.getInstance(OMEXMLService.class);
    } catch (DependencyException de) {
        throw new MissingLibraryException(OMEXMLServiceImpl.NO_OME_XML_MSG, de);
    }
    String version = service.getOMEXMLVersion(ms);
    if (version == null)
        LOGGER.info("Generating OME-XML");
    else {
        LOGGER.info("Generating OME-XML (schema version {})", version);
    }
    if (ms instanceof MetadataRetrieve) {
        if (omexmlOnly) {
            DebugTools.setRootLevel("INFO");
        }
        String xml = service.getOMEXML((MetadataRetrieve) ms);
        LOGGER.info("{}", XMLTools.indentXML(xml, xmlSpaces, true));
        if (omexmlOnly) {
            DebugTools.setRootLevel("OFF");
        }
    } else {
        LOGGER.info("The metadata could not be converted to OME-XML.");
        if (omexmlVersion == null) {
            LOGGER.info("The OME-XML Java library is probably not available.");
        } else {
            LOGGER.info("{} is probably not a legal schema version.", omexmlVersion);
        }
    }
}
Also used : MetadataStore(loci.formats.meta.MetadataStore) ServiceFactory(loci.common.services.ServiceFactory) MissingLibraryException(loci.formats.MissingLibraryException) ImageReader(loci.formats.ImageReader) BufferedImageReader(loci.formats.gui.BufferedImageReader) DependencyException(loci.common.services.DependencyException) MetadataRetrieve(loci.formats.meta.MetadataRetrieve) OMEXMLService(loci.formats.services.OMEXMLService)

Example 8 with MissingLibraryException

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

the class OBFReader method initFile.

@Override
protected void initFile(String id) throws FormatException, IOException {
    super.initFile(id);
    currentInflatedFrame.series = -1;
    currentInflatedFrame.number = -1;
    in = new RandomAccessInputStream(id);
    file_version = getFileVersion(in);
    long stackPosition = in.readLong();
    final int lengthOfDescription = in.readInt();
    final String description = in.readString(lengthOfDescription);
    metadata.put("Description", description);
    if (file_version >= 2) {
        final long meta_data_position = in.readLong();
        final long current_position = in.getFilePointer();
        in.seek(meta_data_position);
        for (String key = readString(); key.length() > 0; key = readString()) {
            if (key.equals("ome_xml")) {
                final String ome_xml = readString();
                try {
                    ServiceFactory factory = new ServiceFactory();
                    OMEXMLService service = factory.getInstance(OMEXMLService.class);
                    if (service.validateOMEXML(ome_xml)) {
                        ome_meta_data = service.createOMEXMLMetadata(ome_xml);
                        for (int image = 0; image != ome_meta_data.getImageCount(); ++image) {
                            if (ome_meta_data.getPixelsBigEndian(image) == null) {
                                ome_meta_data.setPixelsBigEndian(Boolean.FALSE, image);
                            }
                            int channels = ome_meta_data.getChannelCount(image);
                            for (int channel = 0; channel != channels; ++channel) {
                                if (ome_meta_data.getChannelSamplesPerPixel(image, channel) == null) {
                                    ome_meta_data.setChannelSamplesPerPixel(new PositiveInteger(1), image, channel);
                                }
                            }
                        }
                        service.convertMetadata(ome_meta_data, metadataStore);
                        OMEXMLMetadata reference = service.getOMEMetadata(service.asRetrieve(metadataStore));
                        for (int image = 0; image != ome_meta_data.getImageCount(); ++image) {
                            service.addMetadataOnly(reference, image);
                        }
                    }
                } catch (DependencyException exception) {
                    throw new MissingLibraryException(OMEXMLServiceImpl.NO_OME_XML_MSG, exception);
                } catch (ServiceException exception) {
                    throw new FormatException(exception);
                } catch (Exception e) {
                    LOGGER.warn("Could not parse OME-XML metadata", e);
                }
                break;
            } else {
                addGlobalMeta(key, readString());
            }
        }
        in.seek(current_position);
    }
    if (stackPosition != 0) {
        core.clear();
        do {
            stackPosition = initStack(stackPosition);
        } while (stackPosition != 0);
    }
    if (ome_meta_data == null) {
        MetadataTools.populatePixels(metadataStore, this);
        for (int image = 0; image != core.size(); ++image) {
            CoreMetadata meta_data = core.get(image);
            final String name = meta_data.seriesMetadata.get("Name").toString();
            metadataStore.setImageName(name, image);
            @SuppressWarnings("unchecked") final List<Double> lengths = (List<Double>) meta_data.seriesMetadata.get("Lengths");
            if (lengths.size() > 0) {
                double lengthX = Math.abs(lengths.get(0));
                if (lengthX < 0.01) {
                    lengthX *= 1000000;
                }
                if (lengthX > 0) {
                    Length physicalSizeX = FormatTools.getPhysicalSizeX(lengthX / meta_data.sizeX, UNITS.MICROMETER);
                    if (physicalSizeX != null) {
                        metadataStore.setPixelsPhysicalSizeX(physicalSizeX, image);
                    }
                }
            }
            if (lengths.size() > 1) {
                double lengthY = Math.abs(lengths.get(1));
                if (lengthY < 0.01) {
                    lengthY *= 1000000;
                }
                if (lengthY > 0) {
                    Length physicalSizeY = FormatTools.getPhysicalSizeY(lengthY / meta_data.sizeY, UNITS.MICROMETER);
                    if (physicalSizeY != null) {
                        metadataStore.setPixelsPhysicalSizeY(physicalSizeY, image);
                    }
                }
            }
            if (lengths.size() > 2) {
                double lengthZ = Math.abs(lengths.get(2));
                if (lengthZ < 0.01) {
                    lengthZ *= 1000000;
                }
                if (lengthZ > 0) {
                    Length physicalSizeZ = FormatTools.getPhysicalSizeZ(lengthZ / meta_data.sizeZ, UNITS.MICROMETER);
                    if (physicalSizeZ != null) {
                        metadataStore.setPixelsPhysicalSizeZ(physicalSizeZ, image);
                    }
                }
            }
        }
    }
}
Also used : PositiveInteger(ome.xml.model.primitives.PositiveInteger) ServiceFactory(loci.common.services.ServiceFactory) DependencyException(loci.common.services.DependencyException) CoreMetadata(loci.formats.CoreMetadata) OMEXMLService(loci.formats.services.OMEXMLService) DataFormatException(java.util.zip.DataFormatException) FormatException(loci.formats.FormatException) ServiceException(loci.common.services.ServiceException) DependencyException(loci.common.services.DependencyException) DataFormatException(java.util.zip.DataFormatException) MissingLibraryException(loci.formats.MissingLibraryException) FormatException(loci.formats.FormatException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXException(org.xml.sax.SAXException) ServiceException(loci.common.services.ServiceException) Length(ome.units.quantity.Length) OMEXMLMetadata(loci.formats.ome.OMEXMLMetadata) MissingLibraryException(loci.formats.MissingLibraryException) ArrayList(java.util.ArrayList) NodeList(org.w3c.dom.NodeList) List(java.util.List) RandomAccessInputStream(loci.common.RandomAccessInputStream)

Example 9 with MissingLibraryException

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

the class OMETiffReader method setupService.

private void setupService() throws FormatException {
    try {
        ServiceFactory factory = new ServiceFactory();
        service = factory.getInstance(OMEXMLService.class);
    } catch (DependencyException de) {
        throw new MissingLibraryException(OMEXMLServiceImpl.NO_OME_XML_MSG, de);
    }
}
Also used : ServiceFactory(loci.common.services.ServiceFactory) MissingLibraryException(loci.formats.MissingLibraryException) DependencyException(loci.common.services.DependencyException) OMEXMLService(loci.formats.services.OMEXMLService)

Example 10 with MissingLibraryException

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

the class ImageInfo method configureReaderPreInit.

public void configureReaderPreInit() throws FormatException, IOException {
    if (omexml) {
        reader.setOriginalMetadataPopulated(originalMetadata);
        try {
            ServiceFactory factory = new ServiceFactory();
            OMEXMLService service = factory.getInstance(OMEXMLService.class);
            reader.setMetadataStore(service.createOMEXMLMetadata(null, omexmlVersion));
        } catch (DependencyException de) {
            throw new MissingLibraryException(OMEXMLServiceImpl.NO_OME_XML_MSG, de);
        } catch (ServiceException se) {
            throw new FormatException(se);
        }
    }
    // check file format
    if (reader instanceof ImageReader) {
        // determine format
        ImageReader ir = (ImageReader) reader;
        if (new Location(id).exists()) {
            LOGGER.info("Checking file format [{}]", ir.getFormat(id));
        }
    } else {
        // verify format
        LOGGER.info("Checking {} format [{}]", reader.getFormat(), reader.isThisType(id) ? "yes" : "no");
    }
    LOGGER.info("Initializing reader");
    if (stitch) {
        reader = new FileStitcher(reader, true);
        Location f = new Location(id);
        String pat = null;
        if (!f.exists()) {
            ((FileStitcher) reader).setUsingPatternIds(true);
            pat = id;
        } else {
            pat = FilePattern.findPattern(f);
        }
        if (pat != null)
            id = pat;
    }
    if (expand)
        reader = new ChannelFiller(reader);
    if (separate)
        reader = new ChannelSeparator(reader);
    if (merge)
        reader = new ChannelMerger(reader);
    if (cache) {
        if (cachedir != null) {
            reader = new Memoizer(reader, 0, new File(cachedir));
        } else {
            reader = new Memoizer(reader, 0);
        }
    }
    minMaxCalc = null;
    if (minmax || autoscale)
        reader = minMaxCalc = new MinMaxCalculator(reader);
    dimSwapper = null;
    if (swapOrder != null || shuffleOrder != null) {
        reader = dimSwapper = new DimensionSwapper(reader);
    }
    reader = biReader = new BufferedImageReader(reader);
    reader.close();
    reader.setNormalized(normalize);
    reader.setMetadataFiltered(filter);
    reader.setGroupFiles(group);
    options.setMetadataLevel(doMeta ? MetadataLevel.ALL : MetadataLevel.MINIMUM);
    options.setValidate(validate);
    reader.setMetadataOptions(options);
    reader.setFlattenedResolutions(flat);
}
Also used : ServiceFactory(loci.common.services.ServiceFactory) Memoizer(loci.formats.Memoizer) ChannelMerger(loci.formats.ChannelMerger) ChannelFiller(loci.formats.ChannelFiller) BufferedImageReader(loci.formats.gui.BufferedImageReader) DependencyException(loci.common.services.DependencyException) OMEXMLService(loci.formats.services.OMEXMLService) FormatException(loci.formats.FormatException) ChannelSeparator(loci.formats.ChannelSeparator) ServiceException(loci.common.services.ServiceException) FileStitcher(loci.formats.FileStitcher) MinMaxCalculator(loci.formats.MinMaxCalculator) MissingLibraryException(loci.formats.MissingLibraryException) DimensionSwapper(loci.formats.DimensionSwapper) ImageReader(loci.formats.ImageReader) BufferedImageReader(loci.formats.gui.BufferedImageReader) File(java.io.File) Location(loci.common.Location)

Aggregations

MissingLibraryException (loci.formats.MissingLibraryException)17 DependencyException (loci.common.services.DependencyException)15 ServiceFactory (loci.common.services.ServiceFactory)15 FormatException (loci.formats.FormatException)10 MetadataStore (loci.formats.meta.MetadataStore)9 CoreMetadata (loci.formats.CoreMetadata)8 ServiceException (loci.common.services.ServiceException)7 OMEXMLService (loci.formats.services.OMEXMLService)7 Location (loci.common.Location)4 MetadataRetrieve (loci.formats.meta.MetadataRetrieve)4 Length (ome.units.quantity.Length)4 IOException (java.io.IOException)3 RandomAccessInputStream (loci.common.RandomAccessInputStream)3 ImageReader (loci.formats.ImageReader)3 OMEXMLMetadata (loci.formats.ome.OMEXMLMetadata)3 NetCDFService (loci.formats.services.NetCDFService)3 File (java.io.File)2 ArrayList (java.util.ArrayList)2 IRandomAccess (loci.common.IRandomAccess)2 ChannelFiller (loci.formats.ChannelFiller)2