Search in sources :

Example 36 with IMetadata

use of loci.formats.meta.IMetadata in project bioformats by openmicroscopy.

the class Exporter method run.

// -- Exporter API methods --
/**
 * Executes the plugin.
 */
public void run() {
    String outfile = null;
    Boolean splitZ = null;
    Boolean splitC = null;
    Boolean splitT = null;
    Boolean padded = null;
    Boolean saveRoi = null;
    String compression = null;
    Boolean windowless = Boolean.FALSE;
    if (plugin.arg != null) {
        outfile = Macro.getValue(plugin.arg, "outfile", null);
        String z = Macro.getValue(plugin.arg, "splitZ", null);
        String c = Macro.getValue(plugin.arg, "splitC", null);
        String t = Macro.getValue(plugin.arg, "splitT", null);
        String zeroPad = Macro.getValue(plugin.arg, "padded", null);
        String sr = Macro.getValue(plugin.arg, "saveRoi", null);
        compression = Macro.getValue(plugin.arg, "compression", null);
        String id = Macro.getValue(plugin.arg, "imageid", null);
        splitZ = z == null ? null : Boolean.valueOf(z);
        splitC = c == null ? null : Boolean.valueOf(c);
        splitT = t == null ? null : Boolean.valueOf(t);
        padded = zeroPad == null ? null : Boolean.valueOf(zeroPad);
        saveRoi = sr == null ? null : Boolean.valueOf(sr);
        if (id != null) {
            try {
                int imageID = Integer.parseInt(id);
                ImagePlus plus = WindowManager.getImage(imageID);
                if (plus != null)
                    imp = plus;
            } catch (Exception e) {
            // nothing to do, we use the current imagePlus
            }
        }
        String w = Macro.getValue(plugin.arg, "windowless", null);
        if (w != null) {
            windowless = Boolean.valueOf(w);
        }
        plugin.arg = null;
    }
    if (outfile == null) {
        String options = Macro.getOptions();
        if (options != null) {
            String save = Macro.getValue(options, "save", null);
            if (save != null)
                outfile = save;
        }
    }
    // create a temporary file if window less
    if (windowless && (outfile == null || outfile.length() == 0)) {
        File tmp = null;
        try {
            String name = removeExtension(imp.getTitle());
            String n = name + ".ome.tif";
            tmp = File.createTempFile(name, ".ome.tif");
            File p = tmp.getParentFile();
            File[] list = p.listFiles();
            // make sure we delete a previous tmp file with same name if any
            if (list != null) {
                File toDelete = null;
                for (int i = 0; i < list.length; i++) {
                    if (list[i].getName().equals(n)) {
                        toDelete = list[i];
                        break;
                    }
                }
                if (toDelete != null) {
                    toDelete.delete();
                }
            }
            outfile = new File(p, n).getAbsolutePath();
            if (Recorder.record)
                Recorder.recordPath("outputfile", outfile);
            IJ.log("exporter outputfile " + outfile);
        } catch (Exception e) {
        // fall back to window mode.
        } finally {
            if (tmp != null)
                tmp.delete();
        }
    }
    File f = null;
    if (outfile == null || outfile.length() == 0) {
        // open a dialog prompting for the filename to save
        // NB: Copied and adapted from ij.io.SaveDIalog.jSaveDispatchThread,
        // so that the save dialog has a file filter for choosing output format.
        String dir = null, name = null;
        JFileChooser fc = GUITools.buildFileChooser(new ImageWriter(), false);
        fc.setDialogTitle("Bio-Formats Exporter");
        String defaultDir = OpenDialog.getDefaultDirectory();
        if (defaultDir != null)
            fc.setCurrentDirectory(new File(defaultDir));
        // set OME-TIFF as the default output format
        FileFilter[] ff = fc.getChoosableFileFilters();
        FileFilter defaultFilter = null;
        for (int i = 0; i < ff.length; i++) {
            if (ff[i] instanceof ExtensionFileFilter) {
                ExtensionFileFilter eff = (ExtensionFileFilter) ff[i];
                if (i == 0 || eff.getExtension().equals("ome.tif")) {
                    defaultFilter = eff;
                    break;
                }
            }
        }
        if (defaultFilter != null)
            fc.setFileFilter(defaultFilter);
        int returnVal = fc.showSaveDialog(IJ.getInstance());
        if (returnVal != JFileChooser.APPROVE_OPTION) {
            Macro.abort();
            return;
        }
        f = fc.getSelectedFile();
        dir = fc.getCurrentDirectory().getPath() + File.separator;
        name = fc.getName(f);
        if (f.exists()) {
            int ret = JOptionPane.showConfirmDialog(fc, "The file " + f.getName() + " already exists. \n" + "Would you like to replace it?", "Replace?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
            if (ret != JOptionPane.OK_OPTION)
                f = null;
        } else {
            // ensure filename matches selected filter
            FileFilter filter = fc.getFileFilter();
            if (filter instanceof ExtensionFileFilter) {
                ExtensionFileFilter eff = (ExtensionFileFilter) filter;
                String[] ext = eff.getExtensions();
                String lName = name.toLowerCase();
                boolean hasExtension = false;
                for (int i = 0; i < ext.length; i++) {
                    if (lName.endsWith("." + ext[i])) {
                        hasExtension = true;
                        break;
                    }
                }
                if (!hasExtension && ext.length > 0) {
                    // append chosen extension
                    name = name + "." + ext[0];
                }
                f = fc.getSelectedFile();
                String filePath = f.getAbsolutePath();
                if (!filePath.endsWith("." + ext[0])) {
                    f = new File(filePath + '.' + ext[0]);
                }
                if (f.exists()) {
                    int ret1 = JOptionPane.showConfirmDialog(fc, "The file " + f.getName() + " already exists. \n" + "Would you like to replace it?", "Replace?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
                    if (ret1 != JOptionPane.OK_OPTION)
                        f = null;
                }
            }
        }
        if (f == null)
            Macro.abort();
        else {
            // do some ImageJ bookkeeping
            OpenDialog.setDefaultDirectory(dir);
            if (Recorder.record)
                Recorder.recordPath("save", dir + name);
        }
        if (dir == null || name == null)
            return;
        outfile = new File(dir, name).getAbsolutePath();
        if (outfile == null)
            return;
    }
    if (windowless) {
        if (splitZ == null)
            splitZ = Boolean.FALSE;
        if (splitC == null)
            splitC = Boolean.FALSE;
        if (splitT == null)
            splitT = Boolean.FALSE;
        if (padded == null)
            padded = Boolean.FALSE;
    }
    if (splitZ == null || splitC == null || splitT == null) {
        // ask if we want to export multiple files
        GenericDialog multiFile = new GenericDialog("Bio-Formats Exporter - Multiple Files");
        multiFile.addCheckbox("Write_each_Z_section to a separate file", false);
        multiFile.addCheckbox("Write_each_timepoint to a separate file", false);
        multiFile.addCheckbox("Write_each_channel to a separate file", false);
        multiFile.addCheckbox("Use zero padding for filename indexes", false);
        multiFile.showDialog();
        splitZ = multiFile.getNextBoolean();
        splitT = multiFile.getNextBoolean();
        splitC = multiFile.getNextBoolean();
        padded = multiFile.getNextBoolean();
        if (multiFile.wasCanceled())
            return;
    }
    try (IFormatWriter w = new ImageWriter().getWriter(outfile)) {
        int ptype = 0;
        int channels = 1;
        switch(imp.getType()) {
            case ImagePlus.GRAY8:
            case ImagePlus.COLOR_256:
                ptype = FormatTools.UINT8;
                break;
            case ImagePlus.COLOR_RGB:
                channels = 3;
                ptype = FormatTools.UINT8;
                break;
            case ImagePlus.GRAY16:
                ptype = FormatTools.UINT16;
                break;
            case ImagePlus.GRAY32:
                ptype = FormatTools.FLOAT;
                break;
        }
        String title = imp.getTitle();
        w.setWriteSequentially(true);
        FileInfo fi = imp.getOriginalFileInfo();
        String xml = fi == null ? null : fi.description == null ? null : fi.description.indexOf("xml") == -1 ? null : fi.description;
        OMEXMLService service = null;
        IMetadata store = null;
        try {
            ServiceFactory factory = new ServiceFactory();
            service = factory.getInstance(OMEXMLService.class);
            store = service.createOMEXMLMetadata(xml);
        } catch (DependencyException de) {
        } catch (ServiceException se) {
        }
        if (store == null)
            IJ.error("OME-XML Java library not found.");
        OMEXMLMetadataRoot root = (OMEXMLMetadataRoot) store.getRoot();
        if (root.sizeOfROIList() > 0) {
            while (root.sizeOfROIList() > 0) {
                ROI roi = root.getROI(0);
                root.removeROI(roi);
            }
            store.setRoot(root);
        }
        if (xml == null) {
            store.createRoot();
        } else if (store.getImageCount() > 1) {
            // the original dataset had multiple series
            // we need to modify the IMetadata to represent the correct series
            ArrayList<Integer> matchingSeries = new ArrayList<Integer>();
            for (int series = 0; series < store.getImageCount(); series++) {
                String type = store.getPixelsType(series).toString();
                int pixelType = FormatTools.pixelTypeFromString(type);
                if (pixelType == ptype) {
                    String imageName = store.getImageName(series);
                    if (title.indexOf(imageName) >= 0) {
                        matchingSeries.add(series);
                    }
                }
            }
            int series = 0;
            if (matchingSeries.size() > 1) {
                for (int i = 0; i < matchingSeries.size(); i++) {
                    int index = matchingSeries.get(i);
                    String name = store.getImageName(index);
                    boolean valid = true;
                    for (int j = 0; j < matchingSeries.size(); j++) {
                        if (i != j) {
                            String compName = store.getImageName(matchingSeries.get(j));
                            if (compName.indexOf(name) >= 0) {
                                valid = false;
                                break;
                            }
                        }
                    }
                    if (valid) {
                        series = index;
                        break;
                    }
                }
            } else if (matchingSeries.size() == 1)
                series = matchingSeries.get(0);
            ome.xml.model.Image exportImage = root.getImage(series);
            List<ome.xml.model.Image> allImages = root.copyImageList();
            for (ome.xml.model.Image img : allImages) {
                if (!img.equals(exportImage)) {
                    root.removeImage(img);
                }
            }
            store.setRoot(root);
        }
        store.setPixelsSizeX(new PositiveInteger(imp.getWidth()), 0);
        store.setPixelsSizeY(new PositiveInteger(imp.getHeight()), 0);
        store.setPixelsSizeZ(new PositiveInteger(imp.getNSlices()), 0);
        store.setPixelsSizeC(new PositiveInteger(channels * imp.getNChannels()), 0);
        store.setPixelsSizeT(new PositiveInteger(imp.getNFrames()), 0);
        if (store.getImageID(0) == null) {
            store.setImageID(MetadataTools.createLSID("Image", 0), 0);
        }
        if (store.getPixelsID(0) == null) {
            store.setPixelsID(MetadataTools.createLSID("Pixels", 0), 0);
        }
        // reset the pixel type, unless the only change is signedness
        // this prevents problems if the user changed the bit depth of the image
        boolean applyCalibrationFunction = false;
        try {
            int originalType = -1;
            if (store.getPixelsType(0) != null) {
                originalType = FormatTools.pixelTypeFromString(store.getPixelsType(0).toString());
            }
            if (ptype != originalType && (store.getPixelsType(0) == null || !FormatTools.isSigned(originalType) || FormatTools.getBytesPerPixel(originalType) != FormatTools.getBytesPerPixel(ptype))) {
                store.setPixelsType(PixelType.fromString(FormatTools.getPixelTypeString(ptype)), 0);
            } else if (FormatTools.isSigned(originalType)) {
                applyCalibrationFunction = true;
            }
        } catch (EnumerationException e) {
        }
        if (store.getPixelsBinDataCount(0) == 0 || store.getPixelsBinDataBigEndian(0, 0) == null) {
            store.setPixelsBinDataBigEndian(Boolean.FALSE, 0, 0);
        }
        if (store.getPixelsDimensionOrder(0) == null) {
            try {
                store.setPixelsDimensionOrder(DimensionOrder.fromString(ORDER), 0);
            } catch (EnumerationException e) {
            }
        }
        LUT[] luts = new LUT[imp.getNChannels()];
        for (int c = 0; c < imp.getNChannels(); c++) {
            if (c >= store.getChannelCount(0) || store.getChannelID(0, c) == null) {
                String lsid = MetadataTools.createLSID("Channel", 0, c);
                store.setChannelID(lsid, 0, c);
            }
            store.setChannelSamplesPerPixel(new PositiveInteger(channels), 0, 0);
            if (imp instanceof CompositeImage) {
                luts[c] = ((CompositeImage) imp).getChannelLut(c + 1);
            }
        }
        Calibration cal = imp.getCalibration();
        store.setPixelsPhysicalSizeX(FormatTools.getPhysicalSizeX(cal.pixelWidth), 0);
        store.setPixelsPhysicalSizeY(FormatTools.getPhysicalSizeY(cal.pixelHeight), 0);
        store.setPixelsPhysicalSizeZ(FormatTools.getPhysicalSizeZ(cal.pixelDepth), 0);
        store.setPixelsTimeIncrement(new Time(new Double(cal.frameInterval), UNITS.SECOND), 0);
        if (imp.getImageStackSize() != imp.getNChannels() * imp.getNSlices() * imp.getNFrames()) {
            if (!windowless) {
                IJ.showMessageWithCancel("Bio-Formats Exporter Warning", "The number of planes in the stack (" + imp.getImageStackSize() + ") does not match the number of expected planes (" + (imp.getNChannels() * imp.getNSlices() * imp.getNFrames()) + ")." + "\nIf you select 'OK', only " + imp.getImageStackSize() + " planes will be exported. If you wish to export all of the " + "planes,\nselect 'Cancel' and convert the Image5D window " + "to a stack.");
            }
            store.setPixelsSizeZ(new PositiveInteger(imp.getImageStackSize()), 0);
            store.setPixelsSizeC(new PositiveInteger(1), 0);
            store.setPixelsSizeT(new PositiveInteger(1), 0);
        }
        Object info = imp.getProperty("Info");
        if (info != null) {
            String imageInfo = info.toString();
            if (imageInfo != null) {
                String[] lines = imageInfo.split("\n");
                for (String line : lines) {
                    int eq = line.lastIndexOf("=");
                    if (eq > 0) {
                        String key = line.substring(0, eq).trim();
                        String value = line.substring(eq + 1).trim();
                        if (key.endsWith("BitsPerPixel")) {
                            w.setValidBitsPerPixel(Integer.parseInt(value));
                            break;
                        }
                    }
                }
            }
        }
        // NB: Animation rate code copied from ij.plugin.Animator#doOptions().
        final int rate;
        if (cal.fps != 0.0) {
            rate = (int) cal.fps;
        } else if (cal.frameInterval != 0.0 && cal.getTimeUnit().equals("sec")) {
            rate = (int) (1.0 / cal.frameInterval);
        } else {
            // NB: Code from ij.plugin.Animator#animationRate initializer.
            // The value is 7 by default in ImageJ, so must be 7 here as well.
            rate = (int) Prefs.getDouble(Prefs.FPS, 7.0);
        }
        if (rate > 0)
            w.setFramesPerSecond(rate);
        String[] outputFiles = new String[] { outfile };
        int sizeZ = store.getPixelsSizeZ(0).getValue();
        int sizeC = store.getPixelsSizeC(0).getValue();
        int sizeT = store.getPixelsSizeT(0).getValue();
        if (splitZ || splitC || splitT) {
            int nFiles = 1;
            if (splitZ) {
                nFiles *= sizeZ;
            }
            if (splitC) {
                nFiles *= sizeC;
            }
            if (splitT) {
                nFiles *= sizeT;
            }
            outputFiles = new String[nFiles];
            int dot = outfile.indexOf(".", outfile.lastIndexOf(File.separator));
            String base = outfile.substring(0, dot);
            String ext = outfile.substring(dot);
            int nextFile = 0;
            for (int z = 0; z < (splitZ ? sizeZ : 1); z++) {
                for (int c = 0; c < (splitC ? sizeC : 1); c++) {
                    for (int t = 0; t < (splitT ? sizeT : 1); t++) {
                        int index = FormatTools.getIndex(ORDER, sizeZ, sizeC, sizeT, sizeZ * sizeC * sizeT, z, c, t);
                        String pattern = base + (splitZ ? "_Z%z" : "") + (splitC ? "_C%c" : "") + (splitT ? "_T%t" : "") + ext;
                        outputFiles[nextFile++] = FormatTools.getFilename(0, index, store, pattern, padded);
                    }
                }
            }
        }
        if (!w.getFormat().startsWith("OME")) {
            if (splitZ) {
                store.setPixelsSizeZ(new PositiveInteger(1), 0);
            }
            if (splitC) {
                store.setPixelsSizeC(new PositiveInteger(1), 0);
            }
            if (splitT) {
                store.setPixelsSizeT(new PositiveInteger(1), 0);
            }
        }
        // prompt for options
        String[] codecs = w.getCompressionTypes();
        ImageProcessor proc = imp.getImageStack().getProcessor(1);
        Image firstImage = proc.createImage();
        firstImage = AWTImageTools.makeBuffered(firstImage, proc.getColorModel());
        int thisType = AWTImageTools.getPixelType((BufferedImage) firstImage);
        if (proc instanceof ColorProcessor) {
            thisType = FormatTools.UINT8;
        } else if (proc instanceof ShortProcessor) {
            thisType = FormatTools.UINT16;
        }
        boolean notSupportedType = !w.isSupportedType(thisType);
        if (notSupportedType) {
            IJ.error("Pixel type (" + FormatTools.getPixelTypeString(thisType) + ") not supported by this format.");
            return;
        }
        if (codecs != null && codecs.length > 1) {
            boolean selected = false;
            if (compression != null) {
                for (int i = 0; i < codecs.length; i++) {
                    if (codecs[i].equals(compression)) {
                        selected = true;
                        break;
                    }
                }
            }
            if (!selected && !windowless) {
                GenericDialog gd = new GenericDialog("Bio-Formats Exporter Options");
                gd.addChoice("Compression type: ", codecs, codecs[0]);
                if (saveRoi != null) {
                    gd.addCheckbox("Export ROIs", saveRoi.booleanValue());
                } else {
                    gd.addCheckbox("Export ROIs", true);
                }
                gd.showDialog();
                saveRoi = gd.getNextBoolean();
                if (gd.wasCanceled())
                    return;
                compression = gd.getNextChoice();
            }
        }
        boolean in = false;
        if (outputFiles.length > 1) {
            for (int i = 0; i < outputFiles.length; i++) {
                if (new File(outputFiles[i]).exists()) {
                    in = true;
                    break;
                }
            }
        }
        if (in && !windowless) {
            int ret1 = JOptionPane.showConfirmDialog(null, "Some files already exist. \n" + "Would you like to replace them?", "Replace?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
            if (ret1 != JOptionPane.OK_OPTION) {
                return;
            }
            // Delete the files overwrite does not correctly work
            for (int i = 0; i < outputFiles.length; i++) {
                new File(outputFiles[i]).delete();
            }
        }
        // delete the file.
        if (f != null)
            f.delete();
        if (compression != null) {
            w.setCompression(compression);
        }
        // Save ROI's
        if (saveRoi != null && saveRoi.booleanValue()) {
            ROIHandler.saveROIs(store);
        }
        w.setMetadataRetrieve(store);
        // convert and save slices
        int size = imp.getImageStackSize();
        ImageStack is = imp.getImageStack();
        boolean doStack = w.canDoStacks() && size > 1;
        int start = doStack ? 0 : imp.getCurrentSlice() - 1;
        int end = doStack ? size : start + 1;
        boolean littleEndian = false;
        if (w.getMetadataRetrieve().getPixelsBigEndian(0) != null) {
            littleEndian = !w.getMetadataRetrieve().getPixelsBigEndian(0).booleanValue();
        } else if (w.getMetadataRetrieve().getPixelsBinDataCount(0) == 0) {
            littleEndian = !w.getMetadataRetrieve().getPixelsBinDataBigEndian(0, 0).booleanValue();
        }
        byte[] plane = null;
        w.setInterleaved(false);
        int[] no = new int[outputFiles.length];
        for (int i = start; i < end; i++) {
            if (doStack) {
                BF.status(false, "Saving plane " + (i + 1) + "/" + size);
                BF.progress(false, i, size);
            } else
                BF.status(false, "Saving image");
            proc = is.getProcessor(i + 1);
            if (proc instanceof RecordedImageProcessor) {
                proc = ((RecordedImageProcessor) proc).getChild();
            }
            int x = proc.getWidth();
            int y = proc.getHeight();
            if (proc instanceof ByteProcessor) {
                if (applyCalibrationFunction) {
                    // don't alter 'pixels' directly as that will
                    // affect the open ImagePlus
                    byte[] pixels = (byte[]) proc.getPixels();
                    plane = new byte[pixels.length];
                    float[] calibration = proc.getCalibrationTable();
                    for (int pixel = 0; pixel < pixels.length; pixel++) {
                        plane[pixel] = (byte) calibration[pixels[pixel] & 0xff];
                    }
                } else {
                    plane = (byte[]) proc.getPixels();
                }
            } else if (proc instanceof ShortProcessor) {
                short[] pixels = (short[]) proc.getPixels();
                if (applyCalibrationFunction) {
                    // don't alter 'pixels' directly as that will
                    // affect the open ImagePlus
                    plane = new byte[pixels.length * 2];
                    float[] calibration = proc.getCalibrationTable();
                    for (int pixel = 0; pixel < pixels.length; pixel++) {
                        short v = (short) calibration[pixels[pixel] & 0xffff];
                        DataTools.unpackBytes(v, plane, pixel * 2, 2, littleEndian);
                    }
                } else {
                    plane = DataTools.shortsToBytes(pixels, littleEndian);
                }
            } else if (proc instanceof FloatProcessor) {
                plane = DataTools.floatsToBytes((float[]) proc.getPixels(), littleEndian);
            } else if (proc instanceof ColorProcessor) {
                byte[][] pix = new byte[3][x * y];
                ((ColorProcessor) proc).getRGB(pix[0], pix[1], pix[2]);
                plane = new byte[3 * x * y];
                System.arraycopy(pix[0], 0, plane, 0, x * y);
                System.arraycopy(pix[1], 0, plane, x * y, x * y);
                System.arraycopy(pix[2], 0, plane, 2 * x * y, x * y);
                if (i == start) {
                    sizeC /= 3;
                }
            }
            int fileIndex = 0;
            if (doStack) {
                int[] coords = FormatTools.getZCTCoords(ORDER, sizeZ, sizeC, sizeT, size, i);
                int realZ = sizeZ;
                int realC = sizeC;
                int realT = sizeT;
                if (!splitZ) {
                    coords[0] = 0;
                    realZ = 1;
                }
                if (!splitC) {
                    coords[1] = 0;
                    realC = 1;
                }
                if (!splitT) {
                    coords[2] = 0;
                    realT = 1;
                }
                fileIndex = FormatTools.getIndex(ORDER, realZ, realC, realT, realZ * realC * realT, coords[0], coords[1], coords[2]);
            }
            if (notSupportedType) {
                IJ.error("Pixel type not supported by this format.");
            } else {
                w.changeOutputFile(outputFiles[fileIndex]);
                int currentChannel = FormatTools.getZCTCoords(ORDER, sizeZ, sizeC, sizeT, imp.getStackSize(), i)[1];
                if (luts[currentChannel] != null) {
                    // expand to 16-bit LUT if necessary
                    int bpp = FormatTools.getBytesPerPixel(thisType);
                    if (bpp == 1) {
                        w.setColorModel(luts[currentChannel]);
                    } else if (bpp == 2) {
                        int lutSize = luts[currentChannel].getMapSize();
                        byte[][] lut = new byte[3][lutSize];
                        luts[currentChannel].getReds(lut[0]);
                        luts[currentChannel].getGreens(lut[1]);
                        luts[currentChannel].getBlues(lut[2]);
                        short[][] newLut = new short[3][65536];
                        int bins = newLut[0].length / lut[0].length;
                        for (int c = 0; c < newLut.length; c++) {
                            for (int q = 0; q < newLut[c].length; q++) {
                                int index = q / bins;
                                newLut[c][q] = (short) ((lut[c][index] * lut[0].length) + (q % bins));
                            }
                        }
                        w.setColorModel(new Index16ColorModel(16, newLut[0].length, newLut, littleEndian));
                    }
                } else if (!proc.isDefaultLut()) {
                    w.setColorModel(proc.getColorModel());
                }
                w.saveBytes(no[fileIndex]++, plane);
            }
        }
        w.close();
    } catch (FormatException e) {
        WindowTools.reportException(e);
    } catch (IOException e) {
        WindowTools.reportException(e);
    }
}
Also used : ServiceFactory(loci.common.services.ServiceFactory) ArrayList(java.util.ArrayList) Image(java.awt.Image) BufferedImage(java.awt.image.BufferedImage) CompositeImage(ij.CompositeImage) OMEXMLService(loci.formats.services.OMEXMLService) Index16ColorModel(loci.formats.gui.Index16ColorModel) ImageProcessor(ij.process.ImageProcessor) RecordedImageProcessor(loci.plugins.util.RecordedImageProcessor) IMetadata(loci.formats.meta.IMetadata) FileInfo(ij.io.FileInfo) List(java.util.List) ArrayList(java.util.ArrayList) ImageStack(ij.ImageStack) FloatProcessor(ij.process.FloatProcessor) DependencyException(loci.common.services.DependencyException) ROI(ome.xml.model.ROI) FormatException(loci.formats.FormatException) IFormatWriter(loci.formats.IFormatWriter) JFileChooser(javax.swing.JFileChooser) ServiceException(loci.common.services.ServiceException) OMEXMLMetadataRoot(ome.xml.meta.OMEXMLMetadataRoot) File(java.io.File) ExtensionFileFilter(loci.formats.gui.ExtensionFileFilter) EnumerationException(ome.xml.model.enums.EnumerationException) ByteProcessor(ij.process.ByteProcessor) ImageWriter(loci.formats.ImageWriter) Time(ome.units.quantity.Time) ColorProcessor(ij.process.ColorProcessor) CompositeImage(ij.CompositeImage) GenericDialog(ij.gui.GenericDialog) RecordedImageProcessor(loci.plugins.util.RecordedImageProcessor) ExtensionFileFilter(loci.formats.gui.ExtensionFileFilter) FileFilter(javax.swing.filechooser.FileFilter) PositiveInteger(ome.xml.model.primitives.PositiveInteger) LUT(ij.process.LUT) Calibration(ij.measure.Calibration) IOException(java.io.IOException) ImagePlus(ij.ImagePlus) ServiceException(loci.common.services.ServiceException) DependencyException(loci.common.services.DependencyException) EnumerationException(ome.xml.model.enums.EnumerationException) FormatException(loci.formats.FormatException) IOException(java.io.IOException) ShortProcessor(ij.process.ShortProcessor) PositiveInteger(ome.xml.model.primitives.PositiveInteger)

Example 37 with IMetadata

use of loci.formats.meta.IMetadata in project bioformats by openmicroscopy.

the class FormatReader method setId.

/**
 * Initializes a reader from the input file name.
 *
 * Calls {@link #initFile(String id)} to initializes the input file, reads
 * all of the metadata and sets the reader up for reading planes.
 * The performance of this method depends on the format and can be up to
 * several minutes for large file sets.
 *
 *  @param id a {@link String} specifying the path to the file
 */
@Override
public void setId(String id) throws FormatException, IOException {
    LOGGER.debug("{} initializing {}", this.getClass().getSimpleName(), id);
    if (currentId == null || !new Location(id).getAbsolutePath().equals(new Location(currentId).getAbsolutePath())) {
        initFile(id);
        MetadataStore store = getMetadataStore();
        if (saveOriginalMetadata) {
            if (store instanceof OMEXMLMetadata) {
                setupService();
                Hashtable<String, Object> allMetadata = new Hashtable<String, Object>();
                allMetadata.putAll(metadata);
                for (int series = 0; series < getSeriesCount(); series++) {
                    String name = "Series " + series;
                    try {
                        String realName = ((IMetadata) store).getImageName(series);
                        if (realName != null && realName.trim().length() != 0) {
                            name = realName;
                        }
                    } catch (Exception e) {
                    }
                    setSeries(series);
                    MetadataTools.merge(getSeriesMetadata(), allMetadata, name + " ");
                }
                setSeries(0);
                service.populateOriginalMetadata((OMEXMLMetadata) store, allMetadata);
            }
        }
        if (store instanceof OMEXMLMetadata) {
            ((OMEXMLMetadata) store).resolveReferences();
            setupService();
            if (getMetadataOptions().isValidate()) {
                try {
                    String omexml = service.getOMEXML((MetadataRetrieve) store);
                    service.validateOMEXML(omexml);
                } catch (ServiceException | NullPointerException e) {
                    LOGGER.warn("OMEXMLService unable to create OME-XML metadata object.", e);
                }
            }
            for (int series = 0; series < getSeriesCount(); series++) {
                setSeries(series);
                if (getModuloZ().length() > 1 || getModuloC().length() > 1 || getModuloT().length() > 1) {
                    service.addModuloAlong((OMEXMLMetadata) store, core.get(series), series);
                }
            }
            setSeries(0);
        }
    }
}
Also used : Hashtable(java.util.Hashtable) ServiceException(loci.common.services.ServiceException) DependencyException(loci.common.services.DependencyException) EnumerationException(ome.xml.model.enums.EnumerationException) IOException(java.io.IOException) MetadataStore(loci.formats.meta.MetadataStore) IMetadata(loci.formats.meta.IMetadata) ServiceException(loci.common.services.ServiceException) OMEXMLMetadata(loci.formats.ome.OMEXMLMetadata) Location(loci.common.Location)

Example 38 with IMetadata

use of loci.formats.meta.IMetadata in project bioformats by openmicroscopy.

the class OMEXMLServiceImpl method convertMetadata.

/**
 * @see OMEXMLService#convertMetadata(java.lang.String, loci.formats.meta.MetadataStore)
 */
@Override
public void convertMetadata(String xml, MetadataStore dest) throws ServiceException {
    OMEXMLMetadataRoot ome = createRoot(transformToLatestVersion(xml));
    String rootVersion = getOMEXMLVersion(ome);
    String storeVersion = getOMEXMLVersion(dest);
    if (rootVersion.equals(storeVersion)) {
        // correct schema version; populate OME-XML string directly
        if (!(dest instanceof OMEXMLMetadata)) {
            throw new IllegalArgumentException("Expecting OMEXMLMetadata instance.");
        }
        dest.setRoot(ome);
    } else {
        // metadata store is incompatible; create an OME-XML
        // metadata object and copy it into the destination
        IMetadata src = createOMEXMLMetadata(xml);
        convertMetadata(src, dest);
        // make sure that physical sizes are corrected
        for (int image = 0; image < src.getImageCount(); image++) {
            Length physicalSizeX = src.getPixelsPhysicalSizeX(image);
            if (physicalSizeX != null && physicalSizeX.value() != null) {
                physicalSizeX = FormatTools.getPhysicalSize(physicalSizeX.value().doubleValue(), physicalSizeX.unit().getSymbol());
                dest.setPixelsPhysicalSizeX(physicalSizeX, image);
            }
            Length physicalSizeY = src.getPixelsPhysicalSizeY(image);
            if (physicalSizeY != null && physicalSizeY.value() != null) {
                physicalSizeY = FormatTools.getPhysicalSize(physicalSizeY.value().doubleValue(), physicalSizeY.unit().getSymbol());
                dest.setPixelsPhysicalSizeY(physicalSizeY, image);
            }
            Length physicalSizeZ = src.getPixelsPhysicalSizeZ(image);
            if (physicalSizeZ != null && physicalSizeZ.value() != null) {
                physicalSizeZ = FormatTools.getPhysicalSize(physicalSizeZ.value().doubleValue(), physicalSizeZ.unit().getSymbol());
                dest.setPixelsPhysicalSizeZ(physicalSizeZ, image);
            }
        }
    }
}
Also used : IMetadata(loci.formats.meta.IMetadata) Length(ome.units.quantity.Length) OMEXMLMetadata(loci.formats.ome.OMEXMLMetadata) OMEXMLMetadataRoot(ome.xml.meta.OMEXMLMetadataRoot)

Example 39 with IMetadata

use of loci.formats.meta.IMetadata in project bioformats by openmicroscopy.

the class PlugInBioFormatsImporter method readImage.

public void readImage() {
    final ViewUserInterface mipav = ViewUserInterface.getReference();
    // prompt user to choose a file
    if (chooser == null) {
        chooser = GUITools.buildFileChooser(reader);
        chooser.setCurrentDirectory(new File(Preferences.getImageDirectory()));
    }
    JFrame parent = mipav.getMainFrame();
    int rval = chooser.showOpenDialog(parent);
    // user canceled
    if (rval != JFileChooser.APPROVE_OPTION)
        return;
    final File file = chooser.getSelectedFile();
    // load the image in a separate thread
    Thread importerThread = new Thread("BioFormats-Importer") {

        public void run() {
            String name = file.getName();
            String dir = file.getParent();
            // open file using Bio-Formats
            setMessage(mipav, "Importing " + name + "...", true);
            String id = file.getPath();
            try {
                long tic = System.currentTimeMillis();
                IMetadata store;
                try {
                    ServiceFactory factory = new ServiceFactory();
                    OMEXMLService service = factory.getInstance(OMEXMLService.class);
                    store = service.createOMEXMLMetadata();
                } catch (DependencyException exc) {
                    throw new FormatException("Could not create OME-XML store.", exc);
                } catch (ServiceException exc) {
                    throw new FormatException("Could not create OME-XML store.", exc);
                }
                reader.setMetadataStore(store);
                reader.setId(id);
                // MIPAV assumes 4-D data in XYZT order
                reader.setOutputOrder("XYZTC");
                // harvest some core metadata
                int imageCount = reader.getImageCount();
                boolean little = reader.isLittleEndian();
                int pixelType = reader.getPixelType();
                int bpp = FormatTools.getBytesPerPixel(pixelType);
                boolean floating = FormatTools.isFloatingPoint(pixelType);
                int sizeX = reader.getSizeX();
                int sizeY = reader.getSizeY();
                int sizeZ = reader.getSizeZ();
                int sizeT = reader.getSizeT();
                int sizeC = reader.getSizeC();
                String imageName = store.getImageName(0);
                if (sizeC > 1) {
                    throw new FormatException("Multichannel data is unsupported at the moment");
                }
                // compute MIPAV buffer type
                int mipavType;
                switch(pixelType) {
                    case FormatTools.INT8:
                        mipavType = ModelStorageBase.BYTE;
                        break;
                    case FormatTools.UINT8:
                        mipavType = ModelStorageBase.UBYTE;
                        break;
                    case FormatTools.INT16:
                        mipavType = ModelStorageBase.SHORT;
                        break;
                    case FormatTools.UINT16:
                        mipavType = ModelStorageBase.USHORT;
                        break;
                    case FormatTools.INT32:
                        mipavType = ModelStorageBase.INTEGER;
                        break;
                    case FormatTools.UINT32:
                        mipavType = ModelStorageBase.UINTEGER;
                        break;
                    case FormatTools.FLOAT:
                        mipavType = ModelStorageBase.FLOAT;
                        break;
                    case FormatTools.DOUBLE:
                        mipavType = ModelStorageBase.DOUBLE;
                        break;
                    default:
                        throw new FormatException("Unsupported pixel type: " + pixelType);
                }
                // harvest physical resolution
                Length dimPhysSizeX = store.getPixelsPhysicalSizeX(0);
                Length dimPhysSizeY = store.getPixelsPhysicalSizeY(0);
                Length dimPhysSizeZ = store.getPixelsPhysicalSizeZ(0);
                Time dimTimeInc = store.getPixelsTimeIncrement(0);
                float physSizeX = dimPhysSizeX == null ? 1.0f : dimPhysSizeX.value(UNITS.MICROMETER).floatValue();
                float physSizeY = dimPhysSizeY == null ? 1.0f : dimPhysSizeY.value(UNITS.MICROMETER).floatValue();
                float physSizeZ = dimPhysSizeZ == null ? 1.0f : dimPhysSizeZ.value(UNITS.MICROMETER).floatValue();
                float timeInc = dimTimeInc == null ? 1.0f : dimTimeInc.value(UNITS.SECOND).floatValue();
                // compute dimensional extents
                int[] dimExtents = { sizeX, sizeY, sizeZ, sizeT };
                float[] res = { physSizeX, physSizeY, physSizeZ, timeInc };
                int[] units = { FileInfoBase.MICROMETERS, FileInfoBase.MICROMETERS, FileInfoBase.MICROMETERS, FileInfoBase.SECONDS };
                // create MIPAV image object
                ModelImage modelImage = new ModelImage(mipavType, dimExtents, imageName);
                // import planes into MIPAV image
                byte[] buf = new byte[bpp * sizeX * sizeY];
                for (int i = 0; i < imageCount; i++) {
                    setMessage(mipav, "Reading plane #" + (i + 1) + "/" + imageCount, false);
                    reader.openBytes(i, buf);
                    // convert byte array to appropriate primitive type
                    int offset = i * buf.length;
                    Object array = DataTools.makeDataArray(buf, bpp, floating, little);
                    // assign data to MIPAV image object
                    switch(mipavType) {
                        case ModelStorageBase.BYTE:
                        case ModelStorageBase.UBYTE:
                            modelImage.importData(offset, (byte[]) array, false);
                            break;
                        case ModelStorageBase.SHORT:
                        case ModelStorageBase.USHORT:
                            modelImage.importData(offset, (short[]) array, false);
                            break;
                        case ModelStorageBase.INTEGER:
                        case ModelStorageBase.UINTEGER:
                            modelImage.importData(offset, (int[]) array, false);
                            break;
                        case ModelStorageBase.FLOAT:
                            modelImage.importData(offset, (float[]) array, false);
                            break;
                        case ModelStorageBase.DOUBLE:
                            modelImage.importData(offset, (double[]) array, false);
                            break;
                        default:
                            throw new FormatException("Unknown buffer type: " + mipavType);
                    }
                }
                setMessage(mipav, "Finishing import...", true);
                // create a FileInfo object for each image plane
                FileInfoBase[] fileInfo = new FileInfoBase[imageCount];
                for (int i = 0; i < imageCount; i++) {
                    // HACK: Use FileInfoImageXML since FileInfoBase is abstract.
                    fileInfo[i] = new FileInfoImageXML(name, dir, FileUtility.XML);
                    fileInfo[i].setExtents(dimExtents);
                    fileInfo[i].setResolutions(res);
                    fileInfo[i].setUnitsOfMeasure(units);
                    fileInfo[i].setDataType(mipavType);
                }
                modelImage.setFileInfo(fileInfo);
                // scale color range and display MIPAV image
                modelImage.calcMinMax();
                new ViewJFrameImage(modelImage);
                long toc = System.currentTimeMillis();
                long time = toc - tic;
                long avg = time / imageCount;
                setMessage(mipav, name + ": Read " + imageCount + " planes in " + (time / 1000f) + " seconds (" + avg + " ms/plane)", true);
            } catch (FormatException exc) {
                exc.printStackTrace();
                MipavUtil.displayError("An error occurred parsing the file: " + exc.getMessage());
            } catch (IOException exc) {
                exc.printStackTrace();
                MipavUtil.displayError("An I/O error occurred reading the file: " + exc.getMessage());
            }
        }
    };
    importerThread.start();
}
Also used : ModelImage(gov.nih.mipav.model.structures.ModelImage) ServiceFactory(loci.common.services.ServiceFactory) Time(ome.units.quantity.Time) OMEXMLService(loci.formats.services.OMEXMLService) FileInfoBase(gov.nih.mipav.model.file.FileInfoBase) IMetadata(loci.formats.meta.IMetadata) JFrame(javax.swing.JFrame) ViewUserInterface(gov.nih.mipav.view.ViewUserInterface) FileInfoImageXML(gov.nih.mipav.model.file.FileInfoImageXML) IOException(java.io.IOException) DependencyException(loci.common.services.DependencyException) FormatException(loci.formats.FormatException) ServiceException(loci.common.services.ServiceException) ViewJFrameImage(gov.nih.mipav.view.ViewJFrameImage) Length(ome.units.quantity.Length) File(java.io.File) PlugInFile(gov.nih.mipav.plugins.PlugInFile)

Example 40 with IMetadata

use of loci.formats.meta.IMetadata in project bioformats by openmicroscopy.

the class SixteenBitLosslessJPEG2000Test method testLosslessPixels.

@Test
public void testLosslessPixels() throws Exception {
    int failureCount = 0;
    for (int v = Short.MIN_VALUE; v < Short.MAX_VALUE; v += increment) {
        int index = v + Short.MAX_VALUE + 1;
        byte[] pixels = DataTools.shortToBytes((short) v, false);
        String file = index + ".jp2";
        ByteArrayHandle tmpFile = new ByteArrayHandle(1);
        Location.mapFile(file, tmpFile);
        IMetadata metadata16;
        try {
            ServiceFactory factory = new ServiceFactory();
            OMEXMLService service = factory.getInstance(OMEXMLService.class);
            metadata16 = service.createOMEXMLMetadata();
        } catch (DependencyException exc) {
            throw new FormatException("Could not create OME-XML store.", exc);
        } catch (ServiceException exc) {
            throw new FormatException("Could not create OME-XML store.", exc);
        }
        MetadataTools.populateMetadata(metadata16, 0, "foo", false, "XYCZT", "uint16", 1, 1, 1, 1, 1, 1);
        IFormatWriter writer16 = new JPEG2000Writer();
        writer16.setMetadataRetrieve(metadata16);
        writer16.setId(file);
        writer16.saveBytes(0, pixels);
        writer16.close();
        byte[] buf = tmpFile.getBytes();
        byte[] realData = new byte[(int) tmpFile.length()];
        System.arraycopy(buf, 0, realData, 0, realData.length);
        tmpFile.close();
        tmpFile = new ByteArrayHandle(realData);
        Location.mapFile(file, tmpFile);
        ImageReader reader = new ImageReader();
        reader.setId(file);
        byte[] plane = reader.openBytes(0);
        for (int q = 0; q < plane.length; q++) {
            if (plane[q] != pixels[q]) {
                LOGGER.debug("FAILED on {}", DataTools.bytesToShort(pixels, false));
                failureCount++;
                break;
            }
        }
        reader.close();
        tmpFile.close();
        Location.mapFile(file, null);
    }
    assertEquals(failureCount, 0);
}
Also used : JPEG2000Writer(loci.formats.out.JPEG2000Writer) ServiceFactory(loci.common.services.ServiceFactory) DependencyException(loci.common.services.DependencyException) OMEXMLService(loci.formats.services.OMEXMLService) FormatException(loci.formats.FormatException) IFormatWriter(loci.formats.IFormatWriter) IMetadata(loci.formats.meta.IMetadata) ServiceException(loci.common.services.ServiceException) ByteArrayHandle(loci.common.ByteArrayHandle) ImageReader(loci.formats.ImageReader) Test(org.testng.annotations.Test)

Aggregations

IMetadata (loci.formats.meta.IMetadata)62 ServiceFactory (loci.common.services.ServiceFactory)35 OMEXMLService (loci.formats.services.OMEXMLService)35 FormatException (loci.formats.FormatException)19 ImageReader (loci.formats.ImageReader)19 ServiceException (loci.common.services.ServiceException)17 Test (org.testng.annotations.Test)17 DependencyException (loci.common.services.DependencyException)15 SkipException (org.testng.SkipException)15 Length (ome.units.quantity.Length)13 IOException (java.io.IOException)9 ImageWriter (loci.formats.ImageWriter)6 Time (ome.units.quantity.Time)6 PositiveInteger (ome.xml.model.primitives.PositiveInteger)6 File (java.io.File)5 IFormatReader (loci.formats.IFormatReader)5 IFormatWriter (loci.formats.IFormatWriter)5 OMETiffWriter (loci.formats.out.OMETiffWriter)5 TiffWriter (loci.formats.out.TiffWriter)5 EnumerationException (ome.xml.model.enums.EnumerationException)4