Search in sources :

Example 86 with FormatException

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

the class Simple_Read method run.

public void run(String arg) {
    OpenDialog od = new OpenDialog("Open Image File...", arg);
    String dir = od.getDirectory();
    String name = od.getFileName();
    String id = dir + name;
    try {
        ImagePlus[] imps = BF.openImagePlus(id);
        for (ImagePlus imp : imps) imp.show();
    } catch (FormatException exc) {
        IJ.error("Sorry, an error occurred: " + exc.getMessage());
    } catch (IOException exc) {
        IJ.error("Sorry, an error occurred: " + exc.getMessage());
    }
}
Also used : IOException(java.io.IOException) ImagePlus(ij.ImagePlus) FormatException(loci.formats.FormatException) OpenDialog(ij.io.OpenDialog)

Example 87 with FormatException

use of loci.formats.FormatException 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 88 with FormatException

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

the class PrintDomains method main.

public static void main(String[] args) {
    // get a list of all available readers
    IFormatReader[] readers = new ImageReader().getReaders();
    final TreeMultimap<String, String> domains = TreeMultimap.create();
    for (IFormatReader reader : readers) {
        try {
            String[] readerDomains = reader.getPossibleDomains("");
            for (String domain : readerDomains) {
                domains.put(domain, reader.getFormat());
            }
        } catch (FormatException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    for (final Map.Entry<String, Collection<String>> domain : domains.asMap().entrySet()) {
        System.out.println(domain.getKey() + ":");
        for (final String readerFormat : domain.getValue()) {
            System.out.println("  " + readerFormat);
        }
    }
}
Also used : IFormatReader(loci.formats.IFormatReader) Collection(java.util.Collection) IOException(java.io.IOException) ImageReader(loci.formats.ImageReader) Map(java.util.Map) FormatException(loci.formats.FormatException)

Example 89 with FormatException

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

the class BFVirtualStack method getProcessor.

// -- VirtualStack API methods --
@Override
public synchronized ImageProcessor getProcessor(int n) {
    reader.setSeries(series);
    // check cache first
    if (currentSlice >= 0 && currentProcessor != null) {
        List<MethodEntry> currentStack = currentProcessor.getMethodStack();
        if (currentStack.size() > 1) {
            methodStacks.get(currentSlice).addAll(currentStack);
        }
    }
    int sliceIndex = planeIndexes == null ? n - 1 : planeIndexes[n - 1];
    int[] pos = reader.getZCTCoords(sliceIndex);
    if (merge)
        pos = new ChannelMerger(reader).getZCTCoords(sliceIndex);
    int[] cachePos = FormatTools.rasterToPosition(len, sliceIndex);
    ImageProcessor ip = null;
    try {
        ip = (ImageProcessor) cache.getObject(cachePos);
        cache.setCurrentPos(cachePos);
    } catch (CacheException exc) {
        exc.printStackTrace();
    }
    // cache missed
    try {
        if (ip == null) {
            ip = reader.openProcessors(reader.getIndex(pos[0], pos[1], pos[2]))[0];
        }
    } catch (FormatException exc) {
        exc.printStackTrace();
    } catch (IOException exc) {
        exc.printStackTrace();
    }
    if (colorize) {
        // apply color table, if necessary
        byte[] lut = new byte[256];
        byte[] blank = new byte[256];
        for (int i = 0; i < lut.length; i++) {
            lut[i] = (byte) i;
            blank[i] = (byte) 0;
        }
        IndexColorModel model = null;
        if (pos[1] < 3) {
            model = new IndexColorModel(8, 256, pos[1] == 0 ? lut : blank, pos[1] == 1 ? lut : blank, pos[1] == 2 ? lut : blank);
        } else
            model = new IndexColorModel(8, 256, lut, lut, lut);
        if (ip != null)
            ip.setColorModel(model);
    } else if (merge) {
        currentSlice = n - 1;
        ImageProcessor[] otherChannels = new ImageProcessor[reader.getSizeC() - 1];
        for (int i = 0; i < otherChannels.length; i++) {
            int channel = i >= pos[1] ? i + 1 : i;
            try {
                cachePos[0] = channel;
                otherChannels[i] = (ImageProcessor) cache.getObject(cachePos);
            } catch (CacheException exc) {
                exc.printStackTrace();
            }
            if (otherChannels[i] == null) {
                try {
                    int index = reader.getIndex(pos[0], channel, pos[2]);
                    otherChannels[i] = reader.openProcessors(index)[0];
                } catch (FormatException exc) {
                    exc.printStackTrace();
                } catch (IOException exc) {
                    exc.printStackTrace();
                }
            }
        }
        currentProcessor = new RecordedImageProcessor(ip, pos[1], otherChannels);
        currentProcessor.setDoRecording(record);
        if (calibrationTable == null) {
            calibrationTable = currentProcessor.getChild().getCalibrationTable();
        } else {
            currentProcessor.setCalibrationTable(calibrationTable);
        }
        return currentProcessor.getChild();
    }
    if (ip != null) {
        currentSlice = n - 1;
        currentProcessor = new RecordedImageProcessor(ip);
        currentProcessor.setDoRecording(record);
        if (calibrationTable == null) {
            calibrationTable = currentProcessor.getChild().getCalibrationTable();
        } else {
            currentProcessor.setCalibrationTable(calibrationTable);
        }
        return currentProcessor.getChild();
    }
    return null;
}
Also used : ImageProcessor(ij.process.ImageProcessor) CacheException(loci.formats.cache.CacheException) ChannelMerger(loci.formats.ChannelMerger) MethodEntry(loci.plugins.util.RecordedImageProcessor.MethodEntry) IOException(java.io.IOException) FormatException(loci.formats.FormatException) IndexColorModel(java.awt.image.IndexColorModel)

Example 90 with FormatException

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

the class ImageProcessorReader method openProcessors.

/**
 * Returns an array of ImageProcessors that represent the given slice.
 * There is one ImageProcessor per RGB channel;
 * i.e., length of returned array == getRGBChannelCount().
 *
 * @param no Position of image plane.
 */
public ImageProcessor[] openProcessors(int no, int x, int y, int w, int h) throws FormatException, IOException {
    // read byte array
    byte[] b = openBytes(no, x, y, w, h);
    int c = getRGBChannelCount();
    int type = getPixelType();
    int bpp = FormatTools.getBytesPerPixel(type);
    boolean interleave = isInterleaved();
    if (b.length != w * h * c * bpp && b.length != w * h * bpp) {
        throw new FormatException("Invalid byte array length: " + b.length + " (expected w=" + w + ", h=" + h + ", c=" + c + ", bpp=" + bpp + ")");
    }
    // create a color model for this plane (null means default)
    final LUT cm = createColorModel();
    // convert byte array to appropriate primitive array type
    boolean isFloat = FormatTools.isFloatingPoint(type);
    boolean isLittle = isLittleEndian();
    boolean isSigned = FormatTools.isSigned(type);
    // construct image processors
    ImageProcessor[] ip = new ImageProcessor[c];
    for (int i = 0; i < c; i++) {
        byte[] channel = ImageTools.splitChannels(b, i, c, bpp, false, interleave);
        Object pixels = DataTools.makeDataArray(channel, bpp, isFloat, isLittle);
        if (pixels instanceof byte[]) {
            byte[] q = (byte[]) pixels;
            if (q.length != w * h) {
                byte[] tmp = q;
                q = new byte[w * h];
                System.arraycopy(tmp, 0, q, 0, Math.min(q.length, tmp.length));
            }
            if (isSigned)
                q = DataTools.makeSigned(q);
            ip[i] = new ByteProcessor(w, h, q, null);
            if (cm != null)
                ip[i].setColorModel(cm);
        } else if (pixels instanceof short[]) {
            short[] q = (short[]) pixels;
            if (q.length != w * h) {
                short[] tmp = q;
                q = new short[w * h];
                System.arraycopy(tmp, 0, q, 0, Math.min(q.length, tmp.length));
            }
            if (isSigned)
                q = DataTools.makeSigned(q);
            ip[i] = new ShortProcessor(w, h, q, cm);
        } else if (pixels instanceof int[]) {
            int[] q = (int[]) pixels;
            if (q.length != w * h) {
                int[] tmp = q;
                q = new int[w * h];
                System.arraycopy(tmp, 0, q, 0, Math.min(q.length, tmp.length));
            }
            ip[i] = new FloatProcessor(w, h, q);
        } else if (pixels instanceof float[]) {
            float[] q = (float[]) pixels;
            if (q.length != w * h) {
                float[] tmp = q;
                q = new float[w * h];
                System.arraycopy(tmp, 0, q, 0, Math.min(q.length, tmp.length));
            }
            ip[i] = new FloatProcessor(w, h, q, null);
        } else if (pixels instanceof double[]) {
            double[] q = (double[]) pixels;
            if (q.length != w * h) {
                double[] tmp = q;
                q = new double[w * h];
                System.arraycopy(tmp, 0, q, 0, Math.min(q.length, tmp.length));
            }
            ip[i] = new FloatProcessor(w, h, q);
        }
    }
    return ip;
}
Also used : ByteProcessor(ij.process.ByteProcessor) FloatProcessor(ij.process.FloatProcessor) LUT(ij.process.LUT) FormatException(loci.formats.FormatException) ShortProcessor(ij.process.ShortProcessor) ImageProcessor(ij.process.ImageProcessor)

Aggregations

FormatException (loci.formats.FormatException)246 IOException (java.io.IOException)91 CoreMetadata (loci.formats.CoreMetadata)86 RandomAccessInputStream (loci.common.RandomAccessInputStream)73 MetadataStore (loci.formats.meta.MetadataStore)66 Location (loci.common.Location)48 DependencyException (loci.common.services.DependencyException)44 ServiceException (loci.common.services.ServiceException)43 Length (ome.units.quantity.Length)39 ServiceFactory (loci.common.services.ServiceFactory)35 ArrayList (java.util.ArrayList)33 IFD (loci.formats.tiff.IFD)32 TiffParser (loci.formats.tiff.TiffParser)25 OMEXMLService (loci.formats.services.OMEXMLService)23 Time (ome.units.quantity.Time)23 Timestamp (ome.xml.model.primitives.Timestamp)23 ImagePlus (ij.ImagePlus)21 ImageReader (loci.formats.ImageReader)20 IMetadata (loci.formats.meta.IMetadata)18 IFormatReader (loci.formats.IFormatReader)14