Search in sources :

Example 6 with CoreMetadata

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

the class LeicaReader method parseInstrumentData.

private void parseInstrumentData(MetadataStore store, int blockNum) throws FormatException, IOException {
    int series = getSeries();
    // read 24 byte SAFEARRAY
    in.skipBytes(4);
    int cbElements = in.readInt();
    in.skipBytes(8);
    int nElements = in.readInt();
    in.skipBytes(4);
    long initialOffset = in.getFilePointer();
    long elementOffset = 0;
    LOGGER.trace("Element LOOP; series {} at offset {}", series, initialOffset);
    for (int j = 0; j < nElements; j++) {
        elementOffset = initialOffset + j * cbElements;
        LOGGER.trace("Seeking to: {}", elementOffset);
        in.seek(elementOffset);
        String contentID = getString(128);
        LOGGER.trace("contentID: {}", contentID);
        String description = getString(64);
        LOGGER.trace("description: {}", description);
        String data = getString(64);
        int dataType = in.readShort();
        LOGGER.trace("dataType: {}", dataType);
        in.skipBytes(6);
        // read data
        switch(dataType) {
            case 2:
                data = String.valueOf(in.readShort());
                break;
            case 3:
                data = String.valueOf(in.readInt());
                break;
            case 4:
                data = String.valueOf(in.readFloat());
                break;
            case 5:
                data = String.valueOf(in.readDouble());
                break;
            case 7:
            case 11:
                data = in.read() == 0 ? "false" : "true";
                break;
            case 17:
                data = in.readString(1);
                break;
        }
        LOGGER.trace("data: {}", data);
        if (data.trim().length() == 0) {
            LOGGER.trace("Zero length dat string, continuing...");
            continue;
        }
        String[] tokens = contentID.split("\\|");
        LOGGER.trace("Parsing tokens: {}", tokens);
        if (tokens[0].startsWith("CDetectionUnit")) {
            if (tokens[1].startsWith("PMT")) {
                // detector information
                Detector detector = new Detector();
                int lastDetector = detectors.size() - 1;
                if (detectors.size() > 0 && detectors.get(lastDetector).id == Integer.parseInt(tokens[3])) {
                    detector = detectors.get(lastDetector);
                } else {
                    detectors.add(detector);
                }
                detector.id = Integer.parseInt(tokens[3]);
                detector.name = tokens[1];
                try {
                    if (tokens[2].equals("VideoOffset")) {
                        detector.offset = new Double(data);
                    } else if (tokens[2].equals("HighVoltage")) {
                        detector.voltage = new Double(data);
                    } else if (tokens[2].equals("State")) {
                        detector.active = data.equals("Active");
                        String index = tokens[1].substring(tokens[1].indexOf(' ') + 1);
                        detector.index = -1;
                        try {
                            detector.index = Integer.parseInt(index) - 1;
                        } catch (NumberFormatException e) {
                        }
                        if (detector.active && detector.index >= 0) {
                            activeChannelIndices.add(detector.index);
                        }
                    }
                } catch (NumberFormatException e) {
                    LOGGER.debug("Failed to parse detector metadata", e);
                }
            }
        } else if (tokens[0].startsWith("CTurret")) {
            // objective information
            int objective = Integer.parseInt(tokens[3]);
            if (tokens[2].equals("NumericalAperture")) {
                store.setObjectiveLensNA(new Double(data), series, objective);
            } else if (tokens[2].equals("Objective")) {
                String[] objectiveData = data.split(" ");
                final StringBuilder model = new StringBuilder();
                String mag = null, na = null;
                String immersion = null, correction = null;
                for (int i = 0; i < objectiveData.length; i++) {
                    if (objectiveData[i].indexOf('x') != -1 && mag == null && na == null) {
                        int xIndex = objectiveData[i].indexOf('x');
                        mag = objectiveData[i].substring(0, xIndex).trim();
                        na = objectiveData[i].substring(xIndex + 1).trim();
                    } else if (mag == null && na == null) {
                        model.append(objectiveData[i]);
                        model.append(" ");
                    } else if (correction == null) {
                        correction = objectiveData[i];
                    } else if (immersion == null) {
                        immersion = objectiveData[i];
                    }
                }
                if (immersion != null)
                    immersion = immersion.trim();
                if (correction != null)
                    correction = correction.trim();
                Correction realCorrection = getCorrection(correction);
                Correction testCorrection = getCorrection(immersion);
                Immersion realImmersion = getImmersion(immersion);
                Immersion testImmersion = getImmersion(correction);
                // Correction and Immersion are reversed
                if ((testCorrection != Correction.OTHER && realCorrection == Correction.OTHER) || (testImmersion != Immersion.OTHER && realImmersion == Immersion.OTHER)) {
                    String tmp = correction;
                    correction = immersion;
                    immersion = tmp;
                }
                store.setObjectiveImmersion(getImmersion(immersion), series, objective);
                store.setObjectiveCorrection(getCorrection(correction), series, objective);
                store.setObjectiveModel(model.toString().trim(), series, objective);
                store.setObjectiveLensNA(new Double(na), series, objective);
                Double magnification = Double.parseDouble(mag);
                store.setObjectiveNominalMagnification(magnification, series, objective);
            } else if (tokens[2].equals("OrderNumber")) {
                store.setObjectiveSerialNumber(data, series, objective);
            } else if (tokens[2].equals("RefractionIndex")) {
                store.setObjectiveSettingsRefractiveIndex(new Double(data), series);
            }
            // link Objective to Image
            String objectiveID = MetadataTools.createLSID("Objective", series, objective);
            store.setObjectiveID(objectiveID, series, objective);
            if (objective == 0) {
                store.setObjectiveSettingsID(objectiveID, series);
            }
        } else if (tokens[0].startsWith("CSpectrophotometerUnit")) {
            int ndx = tokens[1].lastIndexOf(" ");
            int channel = Integer.parseInt(tokens[1].substring(ndx + 1)) - 1;
            if (tokens[2].equals("Wavelength")) {
                Double wavelength = Double.parseDouble(data);
                store.setFilterModel(tokens[1], series, channel);
                String filterID = MetadataTools.createLSID("Filter", series, channel);
                store.setFilterID(filterID, series, channel);
                int index = activeChannelIndices.indexOf(channel);
                if (index >= 0 && index < getEffectiveSizeC()) {
                    if (!filterRefPopulated[series][index]) {
                        store.setLightPathEmissionFilterRef(filterID, series, index, 0);
                        filterRefPopulated[series][index] = true;
                    }
                    if (tokens[3].equals("0") && !cutInPopulated[series][index]) {
                        Length cutIn = FormatTools.getCutIn(wavelength);
                        if (cutIn != null) {
                            store.setTransmittanceRangeCutIn(cutIn, series, channel);
                        }
                        cutInPopulated[series][index] = true;
                    } else if (tokens[3].equals("1") && !cutOutPopulated[series][index]) {
                        Length cutOut = FormatTools.getCutOut(wavelength);
                        if (cutOut != null) {
                            store.setTransmittanceRangeCutOut(cutOut, series, channel);
                        }
                        cutOutPopulated[series][index] = true;
                    }
                }
            } else if (tokens[2].equals("Stain")) {
                if (activeChannelIndices.contains(channel)) {
                    int nNames = channelNames[series].size();
                    String prevValue = nNames == 0 ? "" : (String) channelNames[series].get(nNames - 1);
                    if (!prevValue.equals(data)) {
                        channelNames[series].add(data);
                    }
                }
            }
        } else if (tokens[0].startsWith("CXYZStage")) {
            CoreMetadata ms = core.get(series);
            // NB: there is only one stage position specified for each series
            if (tokens[2].equals("XPos")) {
                for (int q = 0; q < ms.imageCount; q++) {
                    final Double number = Double.valueOf(data);
                    final Length length = new Length(number, UNITS.REFERENCEFRAME);
                    store.setPlanePositionX(length, series, q);
                    if (q == 0) {
                        addGlobalMetaList("X position for position", data);
                    }
                }
            } else if (tokens[2].equals("YPos")) {
                for (int q = 0; q < ms.imageCount; q++) {
                    final Double number = Double.valueOf(data);
                    final Length length = new Length(number, UNITS.REFERENCEFRAME);
                    store.setPlanePositionY(length, series, q);
                    if (q == 0) {
                        addGlobalMetaList("Y position for position", data);
                    }
                }
            } else if (tokens[2].equals("ZPos")) {
                final Double number = Double.valueOf(data);
                final Length length = new Length(number, UNITS.REFERENCEFRAME);
                store.setStageLabelName("Position", series);
                store.setStageLabelZ(length, series);
                addGlobalMetaList("Z position for position", data);
            }
        } else if (tokens[0].equals("CScanActuator") && tokens[1].equals("Z Scan Actuator") && tokens[2].equals("Position")) {
            final double pos = Double.parseDouble(data) * 1000000;
            store.setStageLabelName("Position", series);
            store.setStageLabelZ(new Length(pos, UNITS.REFERENCEFRAME), series);
            addGlobalMetaList("Z position for position", pos);
        }
        if (contentID.equals("dblVoxelX")) {
            physicalSizes[series][0] = Double.parseDouble(data);
        } else if (contentID.equals("dblVoxelY")) {
            physicalSizes[series][1] = Double.parseDouble(data);
        } else if (contentID.equals("dblStepSize")) {
            double size = Double.parseDouble(data);
            if (size > 0) {
                physicalSizes[series][2] = size;
            }
        } else if (contentID.equals("dblPinhole")) {
            // pinhole is stored in meters
            pinhole[series] = Double.parseDouble(data) * 1000000;
        } else if (contentID.startsWith("nDelayTime")) {
            exposureTime[series] = Double.parseDouble(data);
            if (contentID.endsWith("_ms")) {
                exposureTime[series] /= 1000;
            }
        }
        addSeriesMeta("Block " + blockNum + " " + contentID, data);
    }
    for (Detector detector : detectors) {
        // link Detector to Image, if the detector was actually used
        if (detector.active) {
            store.setDetectorOffset(detector.offset, series, nextDetector);
            store.setDetectorVoltage(new ElectricPotential(detector.voltage, UNITS.VOLT), series, nextDetector);
            store.setDetectorType(getDetectorType("PMT"), series, nextDetector);
            String detectorID = MetadataTools.createLSID("Detector", series, nextDetector);
            store.setDetectorID(detectorID, series, nextDetector);
            if (nextDetector == 0) {
                // overwritten
                for (int c = 0; c < getEffectiveSizeC(); c++) {
                    store.setDetectorSettingsID(detectorID, series, c);
                }
            }
            if (nextChannel < getEffectiveSizeC()) {
                store.setDetectorSettingsID(detectorID, series, nextChannel);
                if (nextChannel < channelNames[series].size()) {
                    String name = (String) channelNames[series].get(nextChannel);
                    if (name == null || name.trim().equals("") || name.equals("None")) {
                        channelNames[series].set(nextChannel, detector.name);
                    }
                } else {
                    while (channelNames[series].size() < nextChannel) {
                        channelNames[series].add("");
                    }
                    channelNames[series].add(detector.name);
                }
                nextChannel++;
            }
            nextDetector++;
        }
    }
    detectors.clear();
    for (int i = 0; i < getSeriesCount(); i++) {
        setSeries(i);
        for (int channel = 0; channel < getEffectiveSizeC(); channel++) {
            if (channel < channelNames[i].size()) {
                String name = (String) channelNames[i].get(channel);
                if (name != null && !name.trim().equals("") && !name.equals("None")) {
                    store.setChannelName(name, i, channel);
                }
            }
            if (channel < emWaves[i].size()) {
                Double wave = new Double(emWaves[i].get(channel).toString());
                Length emission = FormatTools.getEmissionWavelength(wave);
                if (emission != null) {
                    store.setChannelEmissionWavelength(emission, i, channel);
                }
            }
            if (channel < exWaves[i].size()) {
                Double wave = new Double(exWaves[i].get(channel).toString());
                Length ex = FormatTools.getExcitationWavelength(wave);
                if (ex != null) {
                    store.setChannelExcitationWavelength(ex, i, channel);
                }
            }
            if (i < pinhole.length) {
                store.setChannelPinholeSize(new Length(pinhole[i], UNITS.MICROMETER), i, channel);
            }
            if (channel < channelColor[i].length) {
                store.setChannelColor(channelColor[i][channel], i, channel);
            }
        }
    }
    setSeries(0);
}
Also used : Immersion(ome.xml.model.enums.Immersion) Correction(ome.xml.model.enums.Correction) CoreMetadata(loci.formats.CoreMetadata) ElectricPotential(ome.units.quantity.ElectricPotential) Length(ome.units.quantity.Length)

Example 7 with CoreMetadata

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

the class LiFlimReader method initCoreMetadata.

private void initCoreMetadata() throws FormatException {
    // check version number
    if (DataTools.indexOf(KNOWN_VERSIONS, version) < 0) {
        LOGGER.warn("Unknown LI-FLIM version: {}", version);
    }
    // check compression type
    if (COMPRESSION_NONE.equals(compression))
        gzip = false;
    else if (COMPRESSION_GZIP.equals(compression))
        gzip = true;
    else {
        throw new UnsupportedCompressionException("Unknown compression type: " + compression);
    }
    // check dimensional extents
    int sizeP = Integer.parseInt(phases);
    int sizeF = Integer.parseInt(frequencies);
    int p = backgroundP == null ? 1 : Integer.parseInt(backgroundP);
    int f = backgroundF == null ? 1 : Integer.parseInt(backgroundF);
    // populate core metadata
    CoreMetadata ms = core.get(0);
    ms.sizeX = Integer.parseInt(xLen);
    ms.sizeY = Integer.parseInt(yLen);
    ms.sizeZ = Integer.parseInt(zLen) * sizeF;
    ms.sizeC = Integer.parseInt(channels);
    ms.sizeT = Integer.parseInt(timestamps) * sizeP;
    ms.imageCount = getSizeZ() * getSizeT();
    ms.rgb = getSizeC() > 1;
    ms.indexed = false;
    ms.dimensionOrder = "XYCZT";
    ms.pixelType = getPixelTypeFromString(datatype);
    ms.littleEndian = true;
    ms.interleaved = true;
    ms.falseColor = false;
    ms.moduloZ.type = FormatTools.FREQUENCY;
    ms.moduloZ.step = ms.sizeZ / sizeF;
    ms.moduloZ.start = 0;
    ms.moduloZ.end = ms.sizeZ - 1;
    ms.moduloT.type = FormatTools.PHASE;
    ms.moduloT.step = ms.sizeT / sizeP;
    ms.moduloT.start = 0;
    ms.moduloT.end = ms.sizeT - 1;
    if (backgroundX != null) {
        ms = new CoreMetadata();
        ms.sizeX = Integer.parseInt(backgroundX);
        ms.sizeY = Integer.parseInt(backgroundY);
        ms.sizeZ = Integer.parseInt(backgroundZ) * f;
        ms.sizeC = Integer.parseInt(backgroundC);
        ms.sizeT = Integer.parseInt(backgroundT) * p;
        ms.imageCount = ms.sizeZ * ms.sizeT;
        ms.rgb = ms.sizeC > 1;
        ms.indexed = false;
        ms.dimensionOrder = "XYCZT";
        ms.pixelType = getPixelTypeFromString(backgroundDatatype);
        ms.littleEndian = true;
        ms.interleaved = true;
        ms.falseColor = false;
        ms.moduloZ.type = FormatTools.FREQUENCY;
        ms.moduloZ.step = ms.sizeZ / f;
        ms.moduloZ.start = 0;
        ms.moduloZ.end = ms.sizeZ - 1;
        ms.moduloT.type = FormatTools.PHASE;
        ms.moduloT.step = ms.sizeT / p;
        ms.moduloT.start = 0;
        ms.moduloT.end = ms.sizeT - 1;
        core.add(ms);
    }
}
Also used : UnsupportedCompressionException(loci.formats.UnsupportedCompressionException) CoreMetadata(loci.formats.CoreMetadata)

Example 8 with CoreMetadata

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

the class MINCReader method initFile.

// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
    super.initFile(id);
    try {
        ServiceFactory factory = new ServiceFactory();
        netcdf = factory.getInstance(NetCDFService.class);
        netcdf.setFile(id);
    } catch (DependencyException e) {
        throw new MissingLibraryException(e);
    }
    if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
        Vector<String> variableList = netcdf.getVariableList();
        for (String variable : variableList) {
            Hashtable<String, Object> attributes = netcdf.getVariableAttributes(variable);
            String[] keys = attributes.keySet().toArray(new String[0]);
            Arrays.sort(keys);
            for (String key : keys) {
                if (attributes.get(key) instanceof Object[]) {
                    final StringBuilder sb = new StringBuilder();
                    Object[] o = (Object[]) attributes.get(key);
                    for (Object q : o) {
                        sb.append(q.toString());
                    }
                    addGlobalMeta(variable + " " + key, sb.toString());
                } else {
                    addGlobalMeta(variable + " " + key, attributes.get(key));
                }
            }
        }
    }
    CoreMetadata m = core.get(0);
    try {
        Object pixels = netcdf.getVariableValue("/image");
        if (pixels == null) {
            pixels = netcdf.getVariableValue("/minc-2.0/image/0/image");
            isMINC2 = true;
        }
        m.littleEndian = isMINC2;
        boolean signed = false;
        if (isMINC2) {
            Hashtable<String, Object> attrs = netcdf.getVariableAttributes("/minc-2.0/image/0/image");
            String unsigned = attrs.get("_Unsigned").toString();
            if (!unsigned.startsWith("true")) {
                signed = true;
            }
        } else {
            Hashtable<String, Object> attrs = netcdf.getVariableAttributes("/image");
            String signtype = attrs.get("signtype").toString();
            if (signtype.startsWith("signed")) {
                signed = true;
            }
        }
        if (pixels instanceof byte[][][]) {
            m.pixelType = signed ? FormatTools.INT8 : FormatTools.UINT8;
            pixelData = (byte[][][]) pixels;
        } else if (pixels instanceof byte[][][][]) {
            byte[][][][] actualPixels = (byte[][][][]) pixels;
            m.pixelType = signed ? FormatTools.INT8 : FormatTools.UINT8;
            pixelData = new byte[actualPixels.length * actualPixels[0].length][][];
            int nextPlane = 0;
            for (int t = 0; t < actualPixels.length; t++) {
                for (int z = 0; z < actualPixels[t].length; z++) {
                    pixelData[nextPlane++] = actualPixels[t][z];
                }
            }
        } else if (pixels instanceof short[][][]) {
            m.pixelType = signed ? FormatTools.INT16 : FormatTools.UINT16;
            short[][][] s = (short[][][]) pixels;
            pixelData = new byte[s.length][][];
            for (int i = 0; i < s.length; i++) {
                pixelData[i] = new byte[s[i].length][];
                for (int j = 0; j < s[i].length; j++) {
                    pixelData[i][j] = DataTools.shortsToBytes(s[i][j], isLittleEndian());
                }
            }
        } else if (pixels instanceof int[][][]) {
            m.pixelType = signed ? FormatTools.INT32 : FormatTools.UINT32;
            int[][][] s = (int[][][]) pixels;
            pixelData = new byte[s.length][][];
            for (int i = 0; i < s.length; i++) {
                pixelData[i] = new byte[s[i].length][];
                for (int j = 0; j < s[i].length; j++) {
                    pixelData[i][j] = DataTools.intsToBytes(s[i][j], isLittleEndian());
                }
            }
        } else if (pixels instanceof float[][][]) {
            m.pixelType = FormatTools.FLOAT;
            float[][][] s = (float[][][]) pixels;
            pixelData = new byte[s.length][][];
            for (int i = 0; i < s.length; i++) {
                pixelData[i] = new byte[s[i].length][];
                for (int j = 0; j < s[i].length; j++) {
                    pixelData[i][j] = DataTools.floatsToBytes(s[i][j], isLittleEndian());
                }
            }
        } else if (pixels instanceof double[][][]) {
            m.pixelType = FormatTools.DOUBLE;
            double[][][] s = (double[][][]) pixels;
            pixelData = new byte[s.length][][];
            for (int i = 0; i < s.length; i++) {
                pixelData[i] = new byte[s[i].length][];
                for (int j = 0; j < s[i].length; j++) {
                    pixelData[i][j] = DataTools.doublesToBytes(s[i][j], isLittleEndian());
                }
            }
        }
    } catch (ServiceException e) {
        throw new FormatException(e);
    }
    Length physicalX = null;
    Length physicalY = null;
    Length physicalZ = null;
    Length xPosition = null;
    Length yPosition = null;
    Length zPosition = null;
    if (isMINC2) {
        Hashtable<String, Object> attrs = netcdf.getVariableAttributes("/minc-2.0/dimensions/xspace");
        m.sizeX = Integer.parseInt(attrs.get("length").toString());
        physicalX = getStepSize(attrs);
        xPosition = getStart(attrs);
        attrs = netcdf.getVariableAttributes("/minc-2.0/dimensions/yspace");
        m.sizeY = Integer.parseInt(attrs.get("length").toString());
        physicalY = getStepSize(attrs);
        yPosition = getStart(attrs);
        attrs = netcdf.getVariableAttributes("/minc-2.0/dimensions/zspace");
        m.sizeZ = Integer.parseInt(attrs.get("length").toString());
        physicalZ = getStepSize(attrs);
        zPosition = getStart(attrs);
    } else {
        m.sizeX = netcdf.getDimension("/xspace");
        m.sizeY = netcdf.getDimension("/yspace");
        m.sizeZ = netcdf.getDimension("/zspace");
        Hashtable<String, Object> attrs = netcdf.getVariableAttributes("/xspace");
        physicalX = getStepSize(attrs);
        xPosition = getStart(attrs);
        attrs = netcdf.getVariableAttributes("/yspace");
        physicalY = getStepSize(attrs);
        yPosition = getStart(attrs);
        attrs = netcdf.getVariableAttributes("/zspace");
        physicalZ = getStepSize(attrs);
        zPosition = getStart(attrs);
    }
    try {
        m.sizeT = netcdf.getDimension("/time");
    } catch (NullPointerException e) {
        m.sizeT = 1;
    }
    m.sizeC = 1;
    m.imageCount = getSizeZ() * getSizeT() * getSizeC();
    m.rgb = false;
    m.indexed = false;
    m.dimensionOrder = "XYZCT";
    String history = null;
    if (isMINC2) {
        history = netcdf.getAttributeValue("/minc-2.0/ident");
    } else {
        history = netcdf.getAttributeValue("/history");
    }
    addGlobalMeta("Comment", history);
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this, xPosition != null || yPosition != null || zPosition != null);
    if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
        store.setImageDescription(history, 0);
        if (physicalX != null) {
            store.setPixelsPhysicalSizeX(physicalX, 0);
        }
        if (physicalY != null) {
            store.setPixelsPhysicalSizeY(physicalY, 0);
        }
        if (physicalZ != null) {
            store.setPixelsPhysicalSizeZ(physicalZ, 0);
        }
        for (int i = 0; i < getImageCount(); i++) {
            if (xPosition != null) {
                store.setPlanePositionX(xPosition, 0, i);
            }
            if (yPosition != null) {
                store.setPlanePositionY(yPosition, 0, i);
            }
            if (zPosition != null) {
                int z = getZCTCoords(i)[0];
                Double pos = zPosition.value().doubleValue();
                if (physicalZ != null && z > 0) {
                    pos += z * physicalZ.value().doubleValue();
                }
                store.setPlanePositionZ(FormatTools.createLength(pos, zPosition.unit()), 0, i);
            }
        }
    }
}
Also used : ServiceFactory(loci.common.services.ServiceFactory) DependencyException(loci.common.services.DependencyException) CoreMetadata(loci.formats.CoreMetadata) FormatException(loci.formats.FormatException) MetadataStore(loci.formats.meta.MetadataStore) ServiceException(loci.common.services.ServiceException) Length(ome.units.quantity.Length) MissingLibraryException(loci.formats.MissingLibraryException) NetCDFService(loci.formats.services.NetCDFService)

Example 9 with CoreMetadata

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

the class MRWReader method initFile.

// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
    super.initFile(id);
    in = new RandomAccessInputStream(id);
    CoreMetadata m = core.get(0);
    // magic number
    in.skipBytes(4);
    offset = in.readInt() + 8;
    while (in.getFilePointer() < offset) {
        String blockName = in.readString(4);
        int len = in.readInt();
        long fp = in.getFilePointer();
        if (blockName.endsWith("PRD")) {
            in.skipBytes(8);
            sensorHeight = in.readShort();
            sensorWidth = in.readShort();
            m.sizeY = in.readShort();
            m.sizeX = in.readShort();
            dataSize = in.read();
            in.skipBytes(1);
            storageMethod = in.read();
            in.skipBytes(4);
            bayerPattern = in.read();
        } else if (blockName.endsWith("WBG")) {
            wbg = new float[4];
            byte[] wbScale = new byte[4];
            in.read(wbScale);
            for (int i = 0; i < wbg.length; i++) {
                float coeff = in.readShort();
                wbg[i] = coeff / (64 << wbScale[i]);
            }
        } else if (blockName.endsWith("TTW") && getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
            byte[] b = new byte[len];
            in.read(b);
            RandomAccessInputStream ras = new RandomAccessInputStream(b);
            TiffParser tp = new TiffParser(ras);
            IFDList ifds = tp.getIFDs();
            for (IFD ifd : ifds) {
                Integer[] keys = (Integer[]) ifd.keySet().toArray(new Integer[0]);
                // CTR FIXME - getIFDTagName is for debugging only!
                for (int q = 0; q < keys.length; q++) {
                    addGlobalMeta(IFD.getIFDTagName(keys[q].intValue()), ifd.get(keys[q]));
                }
            }
            IFDList exifIFDs = tp.getExifIFDs();
            for (IFD exif : exifIFDs) {
                for (Integer key : exif.keySet()) {
                    addGlobalMeta(IFD.getIFDTagName(key.intValue()), exif.get(key));
                }
            }
            ras.close();
        }
        in.seek(fp + len);
    }
    m.pixelType = FormatTools.UINT16;
    m.rgb = true;
    m.littleEndian = false;
    m.dimensionOrder = "XYCZT";
    m.imageCount = 1;
    m.sizeC = 3;
    m.sizeZ = 1;
    m.sizeT = 1;
    m.interleaved = true;
    m.bitsPerPixel = dataSize;
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this);
}
Also used : MetadataStore(loci.formats.meta.MetadataStore) IFD(loci.formats.tiff.IFD) IFDList(loci.formats.tiff.IFDList) TiffParser(loci.formats.tiff.TiffParser) RandomAccessInputStream(loci.common.RandomAccessInputStream) CoreMetadata(loci.formats.CoreMetadata)

Example 10 with CoreMetadata

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

the class JPXReader method initFile.

// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
    super.initFile(id);
    in = new RandomAccessInputStream(id);
    CoreMetadata ms0 = core.get(0);
    JPEG2000MetadataParser metadataParser = new JPEG2000MetadataParser(in);
    if (metadataParser.isRawCodestream()) {
        LOGGER.info("Codestream is raw, using codestream dimensions.");
        ms0.sizeX = metadataParser.getCodestreamSizeX();
        ms0.sizeY = metadataParser.getCodestreamSizeY();
        ms0.sizeC = metadataParser.getCodestreamSizeC();
        ms0.pixelType = metadataParser.getCodestreamPixelType();
    } else {
        LOGGER.info("Codestream is JP2 boxed, using header dimensions.");
        ms0.sizeX = metadataParser.getHeaderSizeX();
        ms0.sizeY = metadataParser.getHeaderSizeY();
        ms0.sizeC = metadataParser.getHeaderSizeC();
        ms0.pixelType = metadataParser.getHeaderPixelType();
    }
    lut = metadataParser.getLookupTable();
    findPixelOffsets();
    ms0.sizeZ = 1;
    ms0.sizeT = pixelOffsets.size();
    ms0.imageCount = getSizeZ() * getSizeT();
    ms0.dimensionOrder = "XYCZT";
    ms0.rgb = getSizeC() > 1;
    ms0.interleaved = true;
    ms0.littleEndian = false;
    ms0.indexed = !isRGB() && lut != null;
    // New core metadata now that we know how many sub-resolutions we have.
    if (resolutionLevels != null) {
        int seriesCount = resolutionLevels + 1;
        for (int i = 1; i < seriesCount; i++) {
            CoreMetadata ms = new CoreMetadata(this, 0);
            core.add(ms);
            ms.sizeX = core.get(i - 1).sizeX / 2;
            ms.sizeY = core.get(i - 1).sizeY / 2;
            ms.thumbnail = true;
        }
    }
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this, true);
}
Also used : MetadataStore(loci.formats.meta.MetadataStore) RandomAccessInputStream(loci.common.RandomAccessInputStream) CoreMetadata(loci.formats.CoreMetadata)

Aggregations

CoreMetadata (loci.formats.CoreMetadata)211 MetadataStore (loci.formats.meta.MetadataStore)130 RandomAccessInputStream (loci.common.RandomAccessInputStream)108 FormatException (loci.formats.FormatException)87 Length (ome.units.quantity.Length)74 Location (loci.common.Location)55 ArrayList (java.util.ArrayList)50 Timestamp (ome.xml.model.primitives.Timestamp)44 IFD (loci.formats.tiff.IFD)33 Time (ome.units.quantity.Time)30 IOException (java.io.IOException)21 TiffParser (loci.formats.tiff.TiffParser)19 PhotoInterp (loci.formats.tiff.PhotoInterp)17 NonNegativeInteger (ome.xml.model.primitives.NonNegativeInteger)16 IFDList (loci.formats.tiff.IFDList)15 DependencyException (loci.common.services.DependencyException)14 ServiceFactory (loci.common.services.ServiceFactory)13 PositiveInteger (ome.xml.model.primitives.PositiveInteger)13 IniList (loci.common.IniList)9 HashMap (java.util.HashMap)8