Search in sources :

Example 86 with Length

use of ome.units.quantity.Length 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 87 with Length

use of ome.units.quantity.Length in project bioformats by openmicroscopy.

the class BaseZeissReader method parseMainTags.

// -- Internal FormatReader API methods --
void parseMainTags(int image, MetadataStore store, ArrayList<Tag> tags) throws FormatException, IOException {
    int effectiveSizeC = 0;
    try {
        effectiveSizeC = getEffectiveSizeC();
    } catch (ArithmeticException e) {
    }
    for (Tag t : tags) {
        String key = t.getKey();
        String value = t.getValue();
        try {
            if (key.equals("Image Channel Index")) {
                cIndex = Integer.parseInt(value);
                addGlobalMetaList(key, cIndex);
                continue;
            } else if (key.equals("ImageWidth")) {
                int v = Integer.parseInt(value);
                if (getSizeX() == 0 || v < getSizeX()) {
                    core.get(0).sizeX = v;
                }
                if (realWidth == 0 && v > realWidth)
                    realWidth = v;
            } else if (key.equals("ImageHeight")) {
                int v = Integer.parseInt(value);
                if (getSizeY() == 0 || v < getSizeY())
                    core.get(0).sizeY = v;
                if (realHeight == 0 || v > realHeight)
                    realHeight = v;
            }
            if (cIndex != -1)
                key += " " + cIndex;
            if (!key.startsWith("Camera Acquisition Time") && !key.startsWith("ImageRelativeTime")) {
                String metavalue = value;
                if (key.endsWith("Date")) {
                    try {
                        metavalue = DateTools.convertDate(parseTimestamp(value), DateTools.UNIX, DateTools.ISO8601_FORMAT_MS);
                    } catch (Exception e) {
                    }
                }
                addGlobalMeta(key, metavalue);
            }
            if (key.startsWith("ImageTile") && !(store instanceof DummyMetadata)) {
                if (!tiles.containsKey(new Integer(value))) {
                    tiles.put(Integer.valueOf(value), 1);
                } else {
                    int v = tiles.get(new Integer(value)).intValue() + 1;
                    tiles.put(new Integer(value), new Integer(v));
                }
            }
            if (key.startsWith("MultiChannel Color")) {
                if (cIndex >= 0 && cIndex < effectiveSizeC) {
                    if (channelColors == null || effectiveSizeC > channelColors.length) {
                        channelColors = new int[effectiveSizeC];
                    }
                    if (channelColors[cIndex] == 0) {
                        channelColors[cIndex] = Integer.parseInt(value);
                    }
                } else if (cIndex == effectiveSizeC && channelColors != null && channelColors[0] == 0) {
                    System.arraycopy(channelColors, 1, channelColors, 0, channelColors.length - 1);
                    channelColors[cIndex - 1] = Integer.parseInt(value);
                } else if (channelColors != null && channelColors[0] > 0 && channelColors.length > 1) {
                    int c = 1;
                    while (c < channelColors.length - 1 && channelColors[c] != 0) {
                        c++;
                    }
                    if (channelColors[c] == 0) {
                        channelColors[c] = Integer.parseInt(value);
                    }
                }
            } else if (key.startsWith("Scale Factor for X") && physicalSizeX == null) {
                physicalSizeX = Double.parseDouble(value);
            } else if (key.startsWith("Scale Factor for Y") && physicalSizeY == null) {
                physicalSizeY = Double.parseDouble(value);
            } else if (key.startsWith("Scale Factor for Z") && physicalSizeZ == null) {
                physicalSizeZ = Double.parseDouble(value);
            } else if (key.startsWith("Number Rows") && rowCount == 0) {
                rowCount = parseInt(value);
            } else if (key.startsWith("Number Columns") && colCount == 0) {
                colCount = parseInt(value);
            } else if (key.startsWith("NumberOfRawImages") && rawCount == 0) {
                rawCount = parseInt(value);
            } else if (key.startsWith("Emission Wavelength")) {
                if (cIndex != -1) {
                    Double wave = new Double(value);
                    Length emission = FormatTools.getEmissionWavelength(wave);
                    if (emission != null) {
                        emWavelength.put(cIndex, emission);
                    }
                }
            } else if (key.startsWith("Excitation Wavelength")) {
                if (cIndex != -1) {
                    Double wave = new Double(Double.parseDouble(value));
                    Length excitation = FormatTools.getExcitationWavelength(wave);
                    if (excitation != null) {
                        exWavelength.put(cIndex, excitation);
                    }
                }
            } else if (key.startsWith("Channel Name")) {
                if (cIndex != -1) {
                    channelName.put(cIndex, value);
                }
            } else if (key.startsWith("Exposure Time [ms]")) {
                if (exposureTime.get(new Integer(cIndex)) == null) {
                    double exp = Double.parseDouble(value) / 1000;
                    exposureTime.put(new Integer(cIndex), String.valueOf(exp));
                }
            } else if (key.startsWith("User Name")) {
                String[] username = value.split(" ");
                if (username.length >= 2) {
                    String id = MetadataTools.createLSID("Experimenter", 0);
                    store.setExperimenterID(id, 0);
                    store.setExperimenterFirstName(username[0], 0);
                    store.setExperimenterLastName(username[username.length - 1], 0);
                }
            } else if (key.equals("User company")) {
                String id = MetadataTools.createLSID("Experimenter", 0);
                store.setExperimenterID(id, 0);
                store.setExperimenterInstitution(value, 0);
            } else if (key.startsWith("Objective Magnification")) {
                Double magnification = Double.parseDouble(value);
                store.setObjectiveNominalMagnification(magnification, 0, 0);
            } else if (key.startsWith("Objective ID")) {
                store.setObjectiveID("Objective:" + value, 0, 0);
                store.setObjectiveCorrection(getCorrection("Other"), 0, 0);
                store.setObjectiveImmersion(getImmersion("Other"), 0, 0);
            } else if (key.startsWith("Objective N.A.")) {
                store.setObjectiveLensNA(new Double(value), 0, 0);
            } else if (key.startsWith("Objective Name")) {
                String[] tokens = value.split(" ");
                for (int q = 0; q < tokens.length; q++) {
                    int slash = tokens[q].indexOf('/');
                    if (slash != -1 && slash - q > 0) {
                        Double mag = Double.parseDouble(tokens[q].substring(0, slash - q));
                        String na = tokens[q].substring(slash + 1);
                        store.setObjectiveNominalMagnification(mag, 0, 0);
                        store.setObjectiveLensNA(new Double(na), 0, 0);
                        store.setObjectiveCorrection(getCorrection(tokens[q - 1]), 0, 0);
                        break;
                    }
                }
            } else if (key.startsWith("Objective Working Distance")) {
                store.setObjectiveWorkingDistance(new Length(new Double(value), UNITS.MICROMETER), 0, 0);
            } else if (key.startsWith("Objective Immersion Type")) {
                String immersion = "Other";
                switch(Integer.parseInt(value)) {
                    // case 1: no immersion
                    case 2:
                        immersion = "Oil";
                        break;
                    case 3:
                        immersion = "Water";
                        break;
                }
                store.setObjectiveImmersion(getImmersion(immersion), 0, 0);
            } else if (key.startsWith("Stage Position X")) {
                final Double number = Double.valueOf(value);
                stageX.put(image, new Length(number, UNITS.REFERENCEFRAME));
                addGlobalMetaList("X position for position", value);
            } else if (key.startsWith("Stage Position Y")) {
                final Double number = Double.valueOf(value);
                stageY.put(image, new Length(number, UNITS.REFERENCEFRAME));
                addGlobalMetaList("Y position for position", value);
            } else if (key.startsWith("Orca Analog Gain")) {
                detectorGain.put(cIndex, new Double(value));
            } else if (key.startsWith("Orca Analog Offset")) {
                detectorOffset.put(cIndex, new Double(value));
            } else if (key.startsWith("Comments")) {
                imageDescription = value;
            } else if (key.startsWith("Acquisition Date")) {
                acquisitionDate = new Timestamp(DateTools.convertDate(parseTimestamp(value), DateTools.UNIX, DateTools.ISO8601_FORMAT_MS));
            } else if (image >= 0 && key.startsWith("Camera Acquisition Time")) {
                // Note Double variant for TIFF XML.
                String date = DateTools.convertDate(parseTimestamp(value), DateTools.UNIX, DateTools.ISO8601_FORMAT_MS);
                addSeriesMetaList(key, date);
                if (timepoint != 0) {
                    // First timepoint is duplicated for some reason.
                    timestamps.put(timepoint - 1, date);
                } else {
                    timestamps.put(timepoint, date);
                }
                timepoint++;
            } else if (image >= 0 && key.startsWith("ImageRelativeTime")) {
                Time time = new Time(Double.parseDouble(value), UNITS.DAY);
                String timestr = time.value().toString() + " " + time.unit().getSymbol();
                addSeriesMetaList(key, timestr);
            }
        } catch (NumberFormatException e) {
        }
    }
}
Also used : DateTime(org.joda.time.DateTime) Time(ome.units.quantity.Time) Timestamp(ome.xml.model.primitives.Timestamp) FormatException(loci.formats.FormatException) IOException(java.io.IOException) DummyMetadata(loci.formats.meta.DummyMetadata) Length(ome.units.quantity.Length)

Example 88 with Length

use of ome.units.quantity.Length in project bioformats by openmicroscopy.

the class AFIReader method initFile.

// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
    super.initFile(id);
    // The AFI file is just simple XML that lists the .svs files from
    // which to read pixel data.  Each .svs corresponds to a single channel;
    // we assemble the channels in the order in which they are stored in
    // the XML.
    // 
    // Note that the last two series are identical across the .svs files,
    // so we just use the ones from the first listed file.
    String xml = DataTools.readFile(id);
    XMLTools.parseXML(xml, new AFIHandler());
    String parent = new Location(id).getAbsoluteFile().getParent();
    String[] channelNames = new String[pixels.size()];
    reader = new ChannelSeparator[pixels.size()];
    for (int i = 0; i < pixels.size(); i++) {
        String file = pixels.get(i);
        int underscore = file.indexOf('_');
        int fullStop = file.indexOf('.');
        if (underscore >= 0 && fullStop > underscore) {
            channelNames[i] = file.substring(underscore + 1, fullStop);
        }
        pixels.set(i, new Location(parent, file).getAbsolutePath());
        reader[i] = new ChannelSeparator(new SVSReader());
        reader[i].setFlattenedResolutions(hasFlattenedResolutions());
        reader[i].setId(pixels.get(i));
    }
    core = reader[0].getCoreMetadataList();
    for (int i = 0; i < core.size() - EXTRA_IMAGES; i++) {
        CoreMetadata c = core.get(i);
        c.sizeC = pixels.size();
        c.imageCount = c.sizeC * c.sizeZ * c.sizeT;
        c.rgb = false;
        if (i == 0) {
            c.resolutionCount = core.size() - EXTRA_IMAGES;
        }
    }
    MetadataStore store = makeFilterMetadata();
    boolean minimalMetadata = getMetadataOptions().getMetadataLevel() == MetadataLevel.MINIMUM;
    MetadataTools.populatePixels(store, this, !minimalMetadata);
    String fileID = currentId.substring(currentId.lastIndexOf(File.separator) + 1, currentId.lastIndexOf("."));
    for (int i = 0; i < getSeriesCount(); i++) {
        store.setImageName(fileID + " - image #" + (i + 1), i);
    }
    if (!minimalMetadata) {
        Length[] emission = new Length[pixels.size()];
        Length[] excitation = new Length[pixels.size()];
        Double[] exposure = new Double[pixels.size()];
        Timestamp[] datestamp = new Timestamp[pixels.size()];
        Length[] physicalSizes = null;
        double magnification = Double.NaN;
        for (int c = 0; c < pixels.size(); c++) {
            SVSReader baseReader = (SVSReader) reader[c].getReader();
            emission[c] = baseReader.getEmission();
            excitation[c] = baseReader.getExcitation();
            exposure[c] = baseReader.getExposureTime();
            datestamp[c] = baseReader.getDatestamp();
            physicalSizes = baseReader.getPhysicalSizes();
            if (c == 0) {
                magnification = baseReader.getMagnification();
            }
        }
        String instrument = MetadataTools.createLSID("Instrument", 0);
        String objective = MetadataTools.createLSID("Objective", 0, 0);
        store.setInstrumentID(instrument, 0);
        store.setObjectiveID(objective, 0, 0);
        store.setObjectiveNominalMagnification(magnification, 0, 0);
        for (int i = 0; i < getSeriesCount() - EXTRA_IMAGES; i++) {
            if (datestamp[0] != null) {
                store.setImageAcquisitionDate(datestamp[0], i);
            }
            store.setImageInstrumentRef(instrument, i);
            store.setObjectiveSettingsID(objective, i);
            if (i < physicalSizes.length && physicalSizes[i] != null && physicalSizes[i].value(UNITS.MICROMETER).doubleValue() - Constants.EPSILON > 0) {
                Length size = physicalSizes[i];
                store.setPixelsPhysicalSizeX(size, i);
                store.setPixelsPhysicalSizeY(size, i);
            }
            for (int c = 0; c < channelNames.length; c++) {
                store.setChannelName(channelNames[c], i, c);
                if (emission[c] != null) {
                    store.setChannelEmissionWavelength(emission[c], i, c);
                }
                if (excitation[c] != null) {
                    store.setChannelExcitationWavelength(excitation[c], i, c);
                }
                store.setPlaneExposureTime(FormatTools.createTime(exposure[c], UNITS.SECOND), i, c);
            }
        }
    }
}
Also used : CoreMetadata(loci.formats.CoreMetadata) Timestamp(ome.xml.model.primitives.Timestamp) ChannelSeparator(loci.formats.ChannelSeparator) MetadataStore(loci.formats.meta.MetadataStore) Length(ome.units.quantity.Length) Location(loci.common.Location)

Example 89 with Length

use of ome.units.quantity.Length in project bioformats by openmicroscopy.

the class APLReader method initFile.

// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
    super.initFile(id);
    LOGGER.debug("Initializing {}", id);
    // find the corresponding .mtb file
    if (!checkSuffix(id, "mtb")) {
        if (checkSuffix(id, METADATA_SUFFIXES)) {
            int separator = id.lastIndexOf(File.separator);
            if (separator < 0)
                separator = 0;
            int underscore = id.lastIndexOf("_");
            if (underscore < separator || checkSuffix(id, "apl")) {
                underscore = id.lastIndexOf(".");
            }
            String mtbFile = id.substring(0, underscore) + "_d.mtb";
            if (!new Location(mtbFile).exists()) {
                throw new FormatException(".mtb file not found");
            }
            currentId = new Location(mtbFile).getAbsolutePath();
        } else {
            Location parent = new Location(id).getAbsoluteFile().getParentFile();
            parent = parent.getParentFile();
            String[] list = parent.list(true);
            for (String f : list) {
                if (checkSuffix(f, "mtb")) {
                    currentId = new Location(parent, f).getAbsolutePath();
                    break;
                }
            }
            if (!checkSuffix(currentId, "mtb")) {
                throw new FormatException(".mtb file not found");
            }
        }
    }
    String mtb = new Location(currentId).getAbsolutePath();
    LOGGER.debug("Reading .mtb file '{}'", mtb);
    MDBService mdb = null;
    try {
        ServiceFactory factory = new ServiceFactory();
        mdb = factory.getInstance(MDBService.class);
    } catch (DependencyException de) {
        throw new FormatException("MDB Tools Java library not found", de);
    }
    String[] columnNames = null;
    List<String[]> rows = null;
    try {
        mdb.initialize(mtb);
        rows = mdb.parseDatabase().get(0);
        columnNames = rows.get(0);
        String[] tmpNames = columnNames;
        columnNames = new String[tmpNames.length - 1];
        System.arraycopy(tmpNames, 1, columnNames, 0, columnNames.length);
    } finally {
        mdb.close();
    }
    if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
        for (int i = 1; i < rows.size(); i++) {
            String[] row = rows.get(i);
            for (int q = 0; q < row.length; q++) {
                addGlobalMetaList(columnNames[q], row[q]);
            }
        }
    }
    used = new ArrayList<String>();
    used.add(mtb);
    String tnb = mtb.substring(0, mtb.lastIndexOf("."));
    if (tnb.lastIndexOf("_") > tnb.lastIndexOf(File.separator)) {
        tnb = tnb.substring(0, tnb.lastIndexOf("_"));
    }
    used.add(tnb + "_1.tnb");
    used.add(tnb + ".apl");
    String idPath = new Location(id).getAbsolutePath();
    if (!used.contains(idPath) && checkSuffix(idPath, METADATA_SUFFIXES)) {
        used.add(idPath);
    }
    // calculate indexes to relevant metadata
    int calibrationUnit = DataTools.indexOf(columnNames, "Calibration Unit");
    int colorChannels = DataTools.indexOf(columnNames, "Color Channels");
    int frames = DataTools.indexOf(columnNames, "Frames");
    int calibratedHeight = DataTools.indexOf(columnNames, "Height");
    int calibratedWidth = DataTools.indexOf(columnNames, "Width");
    int path = DataTools.indexOf(columnNames, "Image Path");
    if (path == -1) {
        path = DataTools.indexOf(columnNames, "Path");
    }
    int filename = DataTools.indexOf(columnNames, "File Name");
    int magnification = DataTools.indexOf(columnNames, "Magnification");
    int width = DataTools.indexOf(columnNames, "X-Resolution");
    int height = DataTools.indexOf(columnNames, "Y-Resolution");
    int imageType = DataTools.indexOf(columnNames, "Image Type");
    int imageName = DataTools.indexOf(columnNames, "Image Name");
    int zLayers = DataTools.indexOf(columnNames, "Z-Layers");
    String parentDirectory = mtb.substring(0, mtb.lastIndexOf(File.separator));
    // look for the directory that contains TIFF and XML files
    LOGGER.debug("Searching {} for a directory with TIFFs", parentDirectory);
    Location dir = new Location(parentDirectory);
    String topDirectory = null;
    int index = 2;
    String pathName = rows.get(index++)[path].trim();
    while (pathName.equals("") && index < rows.size()) {
        pathName = rows.get(index++)[path].trim();
    }
    pathName = pathName.replace('\\', File.separatorChar);
    pathName = pathName.replaceAll("/", File.separator);
    String[] dirs = pathName.split(File.separatorChar == '\\' ? "\\\\" : File.separator);
    for (int i = dirs.length - 1; i >= 0; i--) {
        if (dirs[i].indexOf("_DocumentFiles") > 0) {
            Location file = new Location(dir, dirs[i]);
            if (file.exists()) {
                topDirectory = file.getAbsolutePath();
                break;
            }
        }
    }
    if (topDirectory == null) {
        String[] list = dir.list();
        for (String f : list) {
            LOGGER.debug("  '{}'", f);
            Location file = new Location(dir, f);
            if (file.isDirectory() && f.indexOf("_DocumentFiles") > 0) {
                topDirectory = file.getAbsolutePath();
                LOGGER.debug("Found {}", topDirectory);
                break;
            }
        }
    }
    if (topDirectory == null) {
        throw new FormatException("Could not find a directory with TIFF files.");
    }
    final List<Integer> seriesIndexes = new ArrayList<Integer>();
    for (int i = 1; i < rows.size(); i++) {
        String file = parseFilename(rows.get(i), filename, path);
        if (file.equals(""))
            continue;
        file = topDirectory + File.separator + file;
        if (new Location(file).exists() && checkSuffix(file, "tif")) {
            seriesIndexes.add(i);
        }
    }
    int seriesCount = seriesIndexes.size();
    core.clear();
    tiffFiles = new String[seriesCount];
    xmlFiles = new String[seriesCount];
    parser = new TiffParser[seriesCount];
    ifds = new IFDList[seriesCount];
    for (int i = 0; i < seriesCount; i++) {
        CoreMetadata ms = new CoreMetadata();
        core.add(ms);
        int secondRow = seriesIndexes.get(i);
        int firstRow = secondRow - 1;
        String[] row2 = rows.get(firstRow);
        String[] row3 = rows.get(secondRow);
        if (frames > -1) {
            ms.sizeT = parseDimension(row3[frames]);
        }
        if (zLayers > -1) {
            ms.sizeZ = parseDimension(row3[zLayers]);
        }
        if (colorChannels > -1) {
            ms.sizeC = parseDimension(row3[colorChannels]);
        } else if (imageType > -1) {
            if (row3[imageType] != null && row3[imageType].equals("RGB")) {
                ms.sizeC = 3;
            }
        }
        ms.dimensionOrder = "XYCZT";
        if (ms.sizeZ == 0)
            ms.sizeZ = 1;
        if (ms.sizeC == 0)
            ms.sizeC = 1;
        if (ms.sizeT == 0)
            ms.sizeT = 1;
        xmlFiles[i] = topDirectory + File.separator + parseFilename(row2, filename, path);
        tiffFiles[i] = topDirectory + File.separator + parseFilename(row3, filename, path);
        parser[i] = new TiffParser(tiffFiles[i]);
        parser[i].setDoCaching(false);
        ifds[i] = parser[i].getIFDs();
        for (IFD ifd : ifds[i]) {
            parser[i].fillInIFD(ifd);
        }
        // get core metadata from TIFF file
        IFD ifd = ifds[i].get(0);
        PhotoInterp photo = ifd.getPhotometricInterpretation();
        int samples = ifd.getSamplesPerPixel();
        ms.sizeX = (int) ifd.getImageWidth();
        ms.sizeY = (int) ifd.getImageLength();
        ms.rgb = samples > 1 || photo == PhotoInterp.RGB;
        ms.pixelType = ifd.getPixelType();
        ms.littleEndian = ifd.isLittleEndian();
        ms.indexed = photo == PhotoInterp.RGB_PALETTE && ifd.containsKey(IFD.COLOR_MAP);
        ms.imageCount = ifds[i].size();
        if (ms.sizeZ * ms.sizeT * (ms.rgb ? 1 : ms.sizeC) != ms.imageCount) {
            ms.sizeT = ms.imageCount / (ms.rgb ? 1 : ms.sizeC);
            ms.sizeZ = 1;
        }
    }
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this);
    for (int i = 0; i < seriesCount; i++) {
        String[] row = rows.get(seriesIndexes.get(i));
        // populate Image data
        MetadataTools.setDefaultCreationDate(store, mtb, i);
        store.setImageName(row[imageName].trim(), i);
        if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
            // populate Dimensions data
            // calculate physical X and Y sizes
            double realWidth = Double.parseDouble(row[calibratedWidth]);
            double realHeight = Double.parseDouble(row[calibratedHeight]);
            String units = row[calibrationUnit];
            CoreMetadata ms = core.get(i);
            double px = realWidth / ms.sizeX;
            double py = realHeight / ms.sizeY;
            Length physicalSizeX = FormatTools.getPhysicalSizeX(px, units);
            Length physicalSizeY = FormatTools.getPhysicalSizeY(py, units);
            if (physicalSizeX != null) {
                store.setPixelsPhysicalSizeX(physicalSizeX, i);
            }
            if (physicalSizeY != null) {
                store.setPixelsPhysicalSizeY(physicalSizeY, i);
            }
        }
    }
    setSeries(0);
}
Also used : MDBService(loci.formats.services.MDBService) ServiceFactory(loci.common.services.ServiceFactory) IFD(loci.formats.tiff.IFD) ArrayList(java.util.ArrayList) PhotoInterp(loci.formats.tiff.PhotoInterp) DependencyException(loci.common.services.DependencyException) CoreMetadata(loci.formats.CoreMetadata) FormatException(loci.formats.FormatException) MetadataStore(loci.formats.meta.MetadataStore) Length(ome.units.quantity.Length) TiffParser(loci.formats.tiff.TiffParser) Location(loci.common.Location)

Example 90 with Length

use of ome.units.quantity.Length in project bioformats by openmicroscopy.

the class OMEXMLServiceTest method testIntegerUnitProperty.

/**
 * Test that the XML serialization of integer unit properties does not
 * include a decimal point. In the schema a shape's font size is
 * {@code type="OME:NonNegativeInt"} which in OMERO is mapped to a
 * {@code double}.
 * @throws ServiceException unexpected
 */
@Test
public void testIntegerUnitProperty() throws ServiceException {
    final Length propertyValue = new Length(12.0d, UNITS.POINT);
    final StringBuffer expectedText = new StringBuffer();
    expectedText.append(" FontSize=");
    expectedText.append('"');
    expectedText.append(propertyValue.value().longValue());
    expectedText.append('"');
    final OMEXMLMetadata metadata = service.createOMEXMLMetadata();
    metadata.setROIID("test ROI", 0);
    metadata.setPointID("test point", 0, 0);
    metadata.setPointX(0.0, 0, 0);
    metadata.setPointY(0.0, 0, 0);
    metadata.setPointFontSize(propertyValue, 0, 0);
    final String xml = service.getOMEXML(metadata);
    assertTrue(xml.contains(expectedText));
}
Also used : Length(ome.units.quantity.Length) OMEXMLMetadata(loci.formats.ome.OMEXMLMetadata) Test(org.testng.annotations.Test)

Aggregations

Length (ome.units.quantity.Length)154 MetadataStore (loci.formats.meta.MetadataStore)82 CoreMetadata (loci.formats.CoreMetadata)74 Timestamp (ome.xml.model.primitives.Timestamp)52 RandomAccessInputStream (loci.common.RandomAccessInputStream)48 Time (ome.units.quantity.Time)46 FormatException (loci.formats.FormatException)39 Location (loci.common.Location)34 ArrayList (java.util.ArrayList)29 IMetadata (loci.formats.meta.IMetadata)13 NonNegativeInteger (ome.xml.model.primitives.NonNegativeInteger)13 ServiceFactory (loci.common.services.ServiceFactory)12 IOException (java.io.IOException)11 DependencyException (loci.common.services.DependencyException)11 PositiveInteger (ome.xml.model.primitives.PositiveInteger)11 MetadataRetrieve (loci.formats.meta.MetadataRetrieve)10 ElectricPotential (ome.units.quantity.ElectricPotential)9 Test (org.testng.annotations.Test)9 Element (org.w3c.dom.Element)9 NodeList (org.w3c.dom.NodeList)9