Search in sources :

Example 1 with CoreMetadata

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

the class LIFReader method translateImageNodes.

private void translateImageNodes(Element imageNode, int i) throws FormatException {
    CoreMetadata ms = core.get(i);
    ms.orderCertain = true;
    ms.metadataComplete = true;
    ms.littleEndian = true;
    ms.falseColor = true;
    NodeList channels = getChannelDescriptionNodes(imageNode);
    NodeList dimensions = getDimensionDescriptionNodes(imageNode);
    HashMap<Long, String> bytesPerAxis = new HashMap<Long, String>();
    Double physicalSizeX = null;
    Double physicalSizeY = null;
    Double physicalSizeZ = null;
    ms.sizeC = channels.getLength();
    for (int ch = 0; ch < channels.getLength(); ch++) {
        Element channel = (Element) channels.item(ch);
        lutNames.add(channel.getAttribute("LUTName"));
        String bytesInc = channel.getAttribute("BytesInc");
        long bytes = bytesInc == null || bytesInc.trim().isEmpty() ? 0 : Long.parseLong(bytesInc.trim());
        if (bytes > 0) {
            bytesPerAxis.put(bytes, "C");
        }
    }
    int extras = 1;
    for (int dim = 0; dim < dimensions.getLength(); dim++) {
        Element dimension = (Element) dimensions.item(dim);
        String v = dimension.getAttribute("DimID");
        int id = v == null || v.trim().isEmpty() ? 0 : Integer.parseInt(v.trim());
        v = dimension.getAttribute("NumberOfElements");
        int len = v == null || v.trim().isEmpty() ? 0 : Integer.parseInt(v.trim());
        v = dimension.getAttribute("BytesInc");
        long nBytes = v == null || v.trim().isEmpty() ? 0 : Long.parseLong(v.trim());
        v = dimension.getAttribute("Length");
        Double physicalLen;
        if (StringUtils.isBlank(v)) {
            physicalLen = 0d;
        } else {
            physicalLen = new Double(v.trim());
        }
        String unit = dimension.getAttribute("Unit");
        double offByOnePhysicalLen = 0d;
        if (len > 1) {
            offByOnePhysicalLen = physicalLen / len;
            physicalLen /= (len - 1);
        } else {
            physicalLen = 0d;
        }
        if (unit.equals("Ks")) {
            physicalLen /= 1000;
            offByOnePhysicalLen /= 1000;
        } else if (unit.equals("m")) {
            physicalLen *= 1000000;
            offByOnePhysicalLen *= 1000000;
        }
        boolean oldPhysicalSize = useOldPhysicalSizeCalculation();
        switch(id) {
            case // X axis
            1:
                ms.sizeX = len;
                ms.rgb = (nBytes % 3) == 0;
                if (ms.rgb)
                    nBytes /= 3;
                ms.pixelType = FormatTools.pixelTypeFromBytes((int) nBytes, false, true);
                physicalSizeX = oldPhysicalSize ? offByOnePhysicalLen : physicalLen;
                break;
            case // Y axis
            2:
                if (ms.sizeY != 0) {
                    if (ms.sizeZ == 1) {
                        ms.sizeZ = len;
                        bytesPerAxis.put(nBytes, "Z");
                        physicalSizeZ = physicalLen;
                    } else if (ms.sizeT == 1) {
                        ms.sizeT = len;
                        bytesPerAxis.put(nBytes, "T");
                    }
                } else {
                    ms.sizeY = len;
                    physicalSizeY = oldPhysicalSize ? offByOnePhysicalLen : physicalLen;
                }
                break;
            case // Z axis
            3:
                if (ms.sizeY == 0) {
                    // XZ scan - swap Y and Z
                    ms.sizeY = len;
                    ms.sizeZ = 1;
                    bytesPerAxis.put(nBytes, "Y");
                    physicalSizeY = oldPhysicalSize ? offByOnePhysicalLen : physicalLen;
                } else {
                    ms.sizeZ = len;
                    bytesPerAxis.put(nBytes, "Z");
                    physicalSizeZ = physicalLen;
                }
                break;
            case // T axis
            4:
                if (ms.sizeY == 0) {
                    // XT scan - swap Y and T
                    ms.sizeY = len;
                    ms.sizeT = 1;
                    bytesPerAxis.put(nBytes, "Y");
                    physicalSizeY = oldPhysicalSize ? offByOnePhysicalLen : physicalLen;
                } else {
                    ms.sizeT = len;
                    bytesPerAxis.put(nBytes, "T");
                }
                break;
            case // tile axis
            10:
                tileCount[i] *= len;
                tileBytesInc[i] = nBytes;
                break;
            default:
                extras *= len;
        }
    }
    physicalSizeXs.add(physicalSizeX);
    physicalSizeYs.add(physicalSizeY);
    if (zSteps[i] == null && physicalSizeZ != null) {
        zSteps[i] = Math.abs(physicalSizeZ);
    }
    if (extras > 1) {
        if (ms.sizeZ == 1)
            ms.sizeZ = extras;
        else {
            if (ms.sizeT == 0)
                ms.sizeT = extras;
            else
                ms.sizeT *= extras;
        }
    }
    if (ms.sizeC == 0)
        ms.sizeC = 1;
    if (ms.sizeZ == 0)
        ms.sizeZ = 1;
    if (ms.sizeT == 0)
        ms.sizeT = 1;
    if (ms.sizeX == 0)
        ms.sizeX = 1;
    if (ms.sizeY == 0)
        ms.sizeY = 1;
    ms.interleaved = ms.rgb;
    ms.indexed = !ms.rgb;
    ms.imageCount = ms.sizeZ * ms.sizeT;
    if (!ms.rgb)
        ms.imageCount *= ms.sizeC;
    else {
        ms.imageCount *= (ms.sizeC / 3);
    }
    Long[] bytes = bytesPerAxis.keySet().toArray(new Long[0]);
    Arrays.sort(bytes);
    ms.dimensionOrder = "XY";
    if (getRGBChannelCount() == 1 || getRGBChannelCount() == getSizeC()) {
        if (getSizeC() > 1 && getSizeT() > 1) {
            ms.dimensionOrder += 'C';
        }
        for (Long nBytes : bytes) {
            String axis = bytesPerAxis.get(nBytes);
            if (ms.dimensionOrder.indexOf(axis) == -1) {
                ms.dimensionOrder += axis;
            }
        }
    }
    if (ms.dimensionOrder.indexOf('Z') == -1) {
        ms.dimensionOrder += 'Z';
    }
    if (ms.dimensionOrder.indexOf('C') == -1) {
        ms.dimensionOrder += 'C';
    }
    if (ms.dimensionOrder.indexOf('T') == -1) {
        ms.dimensionOrder += 'T';
    }
}
Also used : HashMap(java.util.HashMap) NodeList(org.w3c.dom.NodeList) Element(org.w3c.dom.Element) CoreMetadata(loci.formats.CoreMetadata)

Example 2 with CoreMetadata

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

the class LIFReader method translateMetadata.

private void translateMetadata(Element root) throws FormatException {
    Element realRoot = (Element) root.getChildNodes().item(0);
    NodeList toPrune = getNodes(realRoot, "LDM_Block_Sequential_Master");
    if (toPrune != null) {
        for (int i = 0; i < toPrune.getLength(); i++) {
            Element prune = (Element) toPrune.item(i);
            Element parent = (Element) prune.getParentNode();
            parent.removeChild(prune);
        }
    }
    NodeList images = getNodes(realRoot, "Image");
    List<Element> imageNodes = new ArrayList<Element>();
    Long[] oldOffsets = null;
    if (images.getLength() > offsets.size()) {
        oldOffsets = offsets.toArray(new Long[offsets.size()]);
        offsets.clear();
    }
    int nextOffset = 0;
    for (int i = 0; i < images.getLength(); i++) {
        Element image = (Element) images.item(i);
        Element grandparent = (Element) image.getParentNode();
        if (grandparent == null) {
            continue;
        }
        grandparent = (Element) grandparent.getParentNode();
        if (grandparent == null) {
            continue;
        }
        if (!"ProcessingHistory".equals(grandparent.getNodeName())) {
            // image is being referenced from an event list
            imageNodes.add(image);
            if (oldOffsets != null && nextOffset < oldOffsets.length) {
                offsets.add(oldOffsets[nextOffset]);
            }
        }
        grandparent = (Element) grandparent.getParentNode();
        if (grandparent == null) {
            continue;
        }
        grandparent = (Element) grandparent.getParentNode();
        if (grandparent != null) {
            if (!"Image".equals(grandparent.getNodeName())) {
                nextOffset++;
            }
        }
    }
    tileCount = new int[imageNodes.size()];
    Arrays.fill(tileCount, 1);
    tileBytesInc = new long[imageNodes.size()];
    core = new ArrayList<CoreMetadata>(imageNodes.size());
    acquiredDate = new double[imageNodes.size()];
    descriptions = new String[imageNodes.size()];
    laserWavelength = new List[imageNodes.size()];
    laserIntensity = new List[imageNodes.size()];
    laserActive = new List[imageNodes.size()];
    laserFrap = new List[imageNodes.size()];
    timestamps = new Double[imageNodes.size()][];
    activeDetector = new List[imageNodes.size()];
    serialNumber = new String[imageNodes.size()];
    lensNA = new Double[imageNodes.size()];
    magnification = new Double[imageNodes.size()];
    immersions = new String[imageNodes.size()];
    corrections = new String[imageNodes.size()];
    objectiveModels = new String[imageNodes.size()];
    posX = new Length[imageNodes.size()];
    posY = new Length[imageNodes.size()];
    posZ = new Length[imageNodes.size()];
    refractiveIndex = new Double[imageNodes.size()];
    cutIns = new List[imageNodes.size()];
    cutOuts = new List[imageNodes.size()];
    filterModels = new List[imageNodes.size()];
    microscopeModels = new String[imageNodes.size()];
    detectorModels = new List[imageNodes.size()];
    detectorIndexes = new HashMap[imageNodes.size()];
    zSteps = new Double[imageNodes.size()];
    tSteps = new Double[imageNodes.size()];
    pinholes = new Double[imageNodes.size()];
    zooms = new Double[imageNodes.size()];
    expTimes = new Double[imageNodes.size()][];
    gains = new Double[imageNodes.size()][];
    detectorOffsets = new Double[imageNodes.size()][];
    channelNames = new String[imageNodes.size()][];
    exWaves = new Double[imageNodes.size()][];
    imageROIs = new ROI[imageNodes.size()][];
    imageNames = new String[imageNodes.size()];
    core.clear();
    for (int i = 0; i < imageNodes.size(); i++) {
        Element image = imageNodes.get(i);
        CoreMetadata ms = new CoreMetadata();
        core.add(ms);
        int index = core.size() - 1;
        setSeries(index);
        translateImageNames(image, index);
        translateImageNodes(image, index);
        translateAttachmentNodes(image, index);
        translateScannerSettings(image, index);
        translateFilterSettings(image, index);
        translateTimestamps(image, index);
        translateLaserLines(image, index);
        translateROIs(image, index);
        translateSingleROIs(image, index);
        translateDetectors(image, index);
        final Deque<String> nameStack = new ArrayDeque<String>();
        populateOriginalMetadata(image, nameStack);
        addUserCommentMeta(image, i);
    }
    setSeries(0);
    int totalSeries = 0;
    for (int count : tileCount) {
        totalSeries += count;
    }
    ArrayList<CoreMetadata> newCore = new ArrayList<CoreMetadata>();
    for (int i = 0; i < core.size(); i++) {
        for (int tile = 0; tile < tileCount[i]; tile++) {
            newCore.add(core.get(i));
        }
    }
    core = newCore;
}
Also used : Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) ArrayList(java.util.ArrayList) CoreMetadata(loci.formats.CoreMetadata) ArrayDeque(java.util.ArrayDeque)

Example 3 with CoreMetadata

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

the class LegacyND2Reader 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 {
        openFile(id);
        int numSeries = getNumSeries();
        core.clear();
        for (int i = 0; i < numSeries; i++) {
            CoreMetadata ms = new CoreMetadata();
            core.add(ms);
            ms.sizeX = getWidth(i);
            if (ms.sizeX % 2 != 0)
                ms.sizeX++;
            ms.sizeY = getHeight(i);
            ms.sizeZ = getZSlices(i);
            ms.sizeT = getTFrames(i);
            ms.sizeC = getChannels(i);
            int bytes = getBytesPerPixel(i);
            if (bytes % 3 == 0) {
                ms.sizeC *= 3;
                bytes /= 3;
                ms.rgb = true;
            } else
                ms.rgb = false;
            ms.pixelType = FormatTools.pixelTypeFromBytes(bytes, false, true);
            ms.imageCount = ms.sizeZ * ms.sizeT;
            if (!ms.rgb)
                ms.imageCount *= ms.sizeC;
            ms.interleaved = true;
            ms.littleEndian = true;
            ms.dimensionOrder = "XYCZT";
            ms.indexed = false;
            ms.falseColor = false;
        }
    } catch (UnsatisfiedLinkError e) {
        throw new MissingLibraryException(NO_NIKON_MSG, e);
    } catch (Exception e) {
        throw new MissingLibraryException(NO_NIKON_MSG, e);
    }
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this);
    for (int i = 0; i < getSeriesCount(); i++) {
        store.setImageName("Series " + (i + 1), i);
    }
}
Also used : MetadataStore(loci.formats.meta.MetadataStore) MissingLibraryException(loci.formats.MissingLibraryException) CoreMetadata(loci.formats.CoreMetadata) FormatException(loci.formats.FormatException) IOException(java.io.IOException) MissingLibraryException(loci.formats.MissingLibraryException)

Example 4 with CoreMetadata

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

the class LeicaReader method parseFilenames.

private void parseFilenames(int seriesIndex) throws IOException {
    int maxPlanes = 0;
    final List<String> f = new ArrayList<String>();
    int tempImages = in.readInt();
    if (((long) tempImages * nameLength) > in.length()) {
        in.order(!isLittleEndian());
        tempImages = in.readInt();
        in.order(isLittleEndian());
    }
    CoreMetadata ms = core.get(seriesIndex);
    ms.sizeX = in.readInt();
    ms.sizeY = in.readInt();
    in.skipBytes(4);
    int samplesPerPixel = in.readInt();
    ms.rgb = samplesPerPixel > 1;
    ms.sizeC = samplesPerPixel;
    boolean tiffsExist = false;
    String dirPrefix = new Location(currentId).getAbsoluteFile().getParent();
    if (!dirPrefix.endsWith(File.separator))
        dirPrefix += File.separator;
    String prefix = "";
    for (int j = 0; j < tempImages; j++) {
        // read in each filename
        prefix = getString(nameLength);
        f.add(dirPrefix + prefix);
        // test to make sure the path is valid
        Location test = new Location(f.get(f.size() - 1)).getAbsoluteFile();
        LOGGER.debug("Expected to find TIFF file {}", test.getAbsolutePath());
        if (!test.exists()) {
            LOGGER.debug("  file does not exist");
        }
        if (!tiffsExist)
            tiffsExist = test.exists();
    }
    if (!tiffsExist) {
        // Strategy for handling renamed files:
        // 1) Assume that files for each series follow a pattern.
        // 2) Assign each file group to the first series with the correct count.
        LOGGER.info("Handling renamed TIFF files");
        String[] listing = getTIFFList();
        // grab the file patterns
        final List<String> filePatterns = new ArrayList<String>();
        for (String q : listing) {
            Location l = new Location(q).getAbsoluteFile();
            if (!l.exists()) {
                l = new Location(dirPrefix, q).getAbsoluteFile();
            }
            FilePattern pattern = new FilePattern(l);
            if (!pattern.isValid())
                continue;
            AxisGuesser guess = new AxisGuesser(pattern, "XYZCT", 1, 1, 1, false);
            String fp = pattern.getPattern();
            if (guess.getAxisCountS() >= 1) {
                String pre = pattern.getPrefix(guess.getAxisCountS());
                final List<String> fileList = new ArrayList<String>();
                for (int n = 0; n < listing.length; n++) {
                    Location p = new Location(dirPrefix, listing[n]);
                    if (p.getAbsolutePath().startsWith(pre)) {
                        fileList.add(listing[n]);
                    }
                }
                fp = FilePattern.findPattern(l.getAbsolutePath(), dirPrefix, fileList.toArray(new String[fileList.size()]));
            }
            if (fp != null && !filePatterns.contains(fp)) {
                filePatterns.add(fp);
            }
        }
        for (String q : filePatterns) {
            String[] pattern = new FilePattern(q).getFiles();
            if (pattern.length == tempImages) {
                // make sure that this pattern hasn't already been used
                boolean validPattern = true;
                for (int n = 0; n < seriesIndex; n++) {
                    if (files[n] == null)
                        continue;
                    if (files[n].contains(pattern[0])) {
                        validPattern = false;
                        break;
                    }
                }
                if (validPattern) {
                    files[seriesIndex] = new ArrayList<String>();
                    files[seriesIndex].addAll(Arrays.asList(pattern));
                }
            }
        }
    } else {
        files[seriesIndex] = f;
        for (int s = 0; s < seriesIndex; s++) {
            if (files[s] != null) {
                if (files[s].get(0).equals(f.get(0))) {
                    valid[s] = false;
                    files[s] = null;
                }
            }
        }
    }
    if (files[seriesIndex] == null)
        valid[seriesIndex] = false;
    else {
        ms.imageCount = files[seriesIndex].size();
        maxPlanes = (int) Math.max(maxPlanes, ms.imageCount);
    }
}
Also used : ArrayList(java.util.ArrayList) FilePattern(loci.formats.FilePattern) CoreMetadata(loci.formats.CoreMetadata) AxisGuesser(loci.formats.AxisGuesser) Location(loci.common.Location)

Example 5 with CoreMetadata

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

the class LeicaReader method initFile.

// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
    close();
    String leiFile = findLEIFile(id);
    if (leiFile == null || leiFile.trim().length() == 0 || new Location(leiFile).isDirectory()) {
        if (checkSuffix(id, TiffReader.TIFF_SUFFIXES)) {
            super.initFile(id);
            TiffReader r = new TiffReader();
            r.setMetadataStore(getMetadataStore());
            r.setId(id);
            core = new ArrayList<CoreMetadata>(r.getCoreMetadataList());
            metadataStore = r.getMetadataStore();
            final Map<String, Object> globalMetadata = r.getGlobalMetadata();
            for (final Map.Entry<String, Object> entry : globalMetadata.entrySet()) {
                addGlobalMeta(entry.getKey(), entry.getValue());
            }
            r.close();
            files = new List[] { new ArrayList<String>() };
            files[0].add(id);
            tiff = new MinimalTiffReader();
            return;
        } else {
            throw new FormatException("LEI file not found.");
        }
    }
    // parse the LEI file
    super.initFile(leiFile);
    leiFilename = new File(leiFile).exists() ? new Location(leiFile).getAbsolutePath() : id;
    in = new RandomAccessInputStream(leiFile);
    byte[] data = null;
    try {
        data = new byte[(int) in.length()];
        in.read(data);
    } finally {
        in.close();
    }
    in = new RandomAccessInputStream(data);
    MetadataLevel metadataLevel = metadataOptions.getMetadataLevel();
    seriesNames = new ArrayList<String>();
    byte[] fourBytes = new byte[4];
    in.read(fourBytes);
    core.get(0).littleEndian = (fourBytes[0] == TiffConstants.LITTLE && fourBytes[1] == TiffConstants.LITTLE && fourBytes[2] == TiffConstants.LITTLE && fourBytes[3] == TiffConstants.LITTLE);
    boolean realLittleEndian = isLittleEndian();
    in.order(isLittleEndian());
    LOGGER.info("Reading metadata blocks");
    in.skipBytes(8);
    int addr = in.readInt();
    headerIFDs = new IFDList();
    while (addr != 0) {
        IFD ifd = new IFD();
        headerIFDs.add(ifd);
        in.seek(addr + 4);
        int tag = in.readInt();
        while (tag != 0) {
            // create the IFD structure
            int offset = in.readInt();
            long pos = in.getFilePointer();
            in.seek(offset + 12);
            int size = in.readInt();
            ifd.putIFDValue(tag, in.getFilePointer());
            in.seek(pos);
            tag = in.readInt();
        }
        addr = in.readInt();
    }
    numSeries = headerIFDs.size();
    tileWidth = new int[numSeries];
    tileHeight = new int[numSeries];
    core.clear();
    for (int i = 0; i < numSeries; i++) {
        core.add(new CoreMetadata());
    }
    files = new List[numSeries];
    channelNames = new List[getSeriesCount()];
    emWaves = new List[getSeriesCount()];
    exWaves = new List[getSeriesCount()];
    cutInPopulated = new boolean[getSeriesCount()][];
    cutOutPopulated = new boolean[getSeriesCount()][];
    filterRefPopulated = new boolean[getSeriesCount()][];
    for (int i = 0; i < getSeriesCount(); i++) {
        channelNames[i] = new ArrayList();
        emWaves[i] = new ArrayList();
        exWaves[i] = new ArrayList();
    }
    // determine the length of a filename
    LOGGER.info("Parsing metadata blocks");
    core.get(0).littleEndian = !isLittleEndian();
    int seriesIndex = 0;
    int invalidCount = 0;
    valid = new boolean[numSeries];
    timestamps = new String[headerIFDs.size()][];
    for (int i = 0; i < headerIFDs.size(); i++) {
        IFD ifd = headerIFDs.get(i);
        valid[i] = true;
        if (ifd.get(SERIES) != null) {
            long offset = ((Long) ifd.get(SERIES)).longValue();
            in.seek(offset + 8);
            nameLength = in.readInt() * 2;
        }
        in.seek(((Long) ifd.get(IMAGES)).longValue());
        parseFilenames(i);
        if (!valid[i])
            invalidCount++;
    }
    numSeries -= invalidCount;
    if (numSeries <= 0) {
        throw new FormatException("TIFF files not found");
    }
    int[] count = new int[getSeriesCount()];
    for (int i = 0; i < getSeriesCount(); i++) {
        count[i] = core.get(i).imageCount;
    }
    final List<String>[] tempFiles = files;
    IFDList tempIFDs = headerIFDs;
    core = new ArrayList<CoreMetadata>(numSeries);
    files = new List[numSeries];
    headerIFDs = new IFDList();
    int index = 0;
    core.clear();
    for (int i = 0; i < numSeries; i++) {
        CoreMetadata ms = new CoreMetadata();
        while (index < valid.length && !valid[index]) index++;
        if (index >= valid.length) {
            break;
        }
        ms.imageCount = count[index];
        files[i] = tempFiles[index];
        Collections.sort(files[i]);
        headerIFDs.add(tempIFDs.get(index));
        index++;
        core.add(ms);
    }
    tiff = new MinimalTiffReader();
    LOGGER.info("Populating metadata");
    if (headerIFDs == null)
        headerIFDs = ifds;
    seriesDescriptions = new ArrayList<String>();
    physicalSizes = new double[headerIFDs.size()][5];
    pinhole = new double[headerIFDs.size()];
    exposureTime = new double[headerIFDs.size()];
    channelColor = new Color[headerIFDs.size()][];
    for (int i = 0; i < headerIFDs.size(); i++) {
        IFD ifd = headerIFDs.get(i);
        CoreMetadata ms = core.get(i);
        ms.littleEndian = isLittleEndian();
        setSeries(i);
        Integer[] keys = ifd.keySet().toArray(new Integer[ifd.size()]);
        Arrays.sort(keys);
        for (Integer key : keys) {
            long offset = ((Long) ifd.get(key)).longValue();
            in.seek(offset);
            if (key.equals(SERIES)) {
                parseSeriesTag();
            } else if (key.equals(IMAGES)) {
                parseImageTag(i);
            } else if (key.equals(DIMDESCR)) {
                parseDimensionTag(i);
            } else if (key.equals(TIMEINFO) && metadataLevel != MetadataLevel.MINIMUM) {
                parseTimeTag(i);
            } else if (key.equals(EXPERIMENT) && metadataLevel != MetadataLevel.MINIMUM) {
                parseExperimentTag();
            } else if (key.equals(LUTDESC)) {
                parseLUT(i);
            } else if (key.equals(CHANDESC) && metadataLevel != MetadataLevel.MINIMUM) {
                parseChannelTag();
            }
        }
        ms.orderCertain = true;
        ms.littleEndian = isLittleEndian();
        ms.falseColor = true;
        ms.metadataComplete = true;
        ms.interleaved = false;
        String filename = (String) files[i].get(0);
        if (checkSuffix(filename, TiffReader.TIFF_SUFFIXES)) {
            RandomAccessInputStream s = new RandomAccessInputStream(filename, 16);
            try {
                TiffParser parser = new TiffParser(s);
                parser.setDoCaching(false);
                IFD firstIFD = parser.getFirstIFD();
                parser.fillInIFD(firstIFD);
                ms.sizeX = (int) firstIFD.getImageWidth();
                ms.sizeY = (int) firstIFD.getImageLength();
                // override the .lei pixel type, in case a TIFF file was overwritten
                ms.pixelType = firstIFD.getPixelType();
                // won't affect the pixel data
                if (FormatTools.getBytesPerPixel(ms.pixelType) > 1) {
                    ms.littleEndian = firstIFD.isLittleEndian();
                } else {
                    ms.littleEndian = realLittleEndian;
                }
                tileWidth[i] = (int) firstIFD.getTileWidth();
                tileHeight[i] = (int) firstIFD.getTileLength();
            } finally {
                s.close();
            }
        } else {
            ms.littleEndian = realLittleEndian;
        }
    }
    for (int i = 0; i < getSeriesCount(); i++) {
        setSeries(i);
        CoreMetadata ms = core.get(i);
        if (getSizeZ() == 0)
            ms.sizeZ = 1;
        if (getSizeT() == 0)
            ms.sizeT = 1;
        if (getSizeC() == 0)
            ms.sizeC = 1;
        if (getImageCount() == 0)
            ms.imageCount = 1;
        if (getImageCount() == 1 && getSizeZ() * getSizeT() > 1) {
            ms.sizeZ = 1;
            ms.sizeT = 1;
        }
        if (getSizeY() == 1 || getSizeY() == getSizeZ() || getSizeY() == getSizeT()) {
            // XZ or XT scan
            if (getSizeZ() > 1 && getImageCount() == getSizeC() * getSizeT()) {
                ms.sizeY = getSizeZ();
                ms.sizeZ = 1;
            } else if (getSizeT() > 1 && getImageCount() == getSizeC() * getSizeZ()) {
                ms.sizeY = getSizeT();
                ms.sizeT = 1;
            }
        }
        if (isRGB())
            ms.indexed = false;
        ms.dimensionOrder = MetadataTools.makeSaneDimensionOrder(getDimensionOrder());
    }
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this, true);
    // minimum metadata level.
    for (int i = 0; i < getSeriesCount(); i++) {
        store.setImageName(seriesNames.get(i), i);
    }
    if (metadataLevel == MetadataLevel.MINIMUM)
        return;
    for (int i = 0; i < getSeriesCount(); i++) {
        CoreMetadata ms = core.get(i);
        IFD ifd = headerIFDs.get(i);
        long firstPlane = 0;
        if (i < timestamps.length && timestamps[i] != null && timestamps[i].length > 0) {
            firstPlane = DateTools.getTime(timestamps[i][0], DATE_FORMAT, ":");
            String date = DateTools.formatDate(timestamps[i][0], DATE_FORMAT);
            if (date != null) {
                store.setImageAcquisitionDate(new Timestamp(date), i);
            }
        }
        store.setImageDescription(seriesDescriptions.get(i), i);
        String instrumentID = MetadataTools.createLSID("Instrument", i);
        store.setInstrumentID(instrumentID, i);
        // parse instrument data
        nextDetector = 0;
        nextChannel = 0;
        detectors.clear();
        cutInPopulated[i] = new boolean[ms.sizeC];
        cutOutPopulated[i] = new boolean[ms.sizeC];
        filterRefPopulated[i] = new boolean[ms.sizeC];
        Integer[] keys = ifd.keySet().toArray(new Integer[ifd.size()]);
        Arrays.sort(keys);
        int nextInstrumentBlock = 1;
        sequential = DataTools.indexOf(keys, SEQ_SCANNERSET) != -1;
        for (Integer key : keys) {
            if (key.equals(FILTERSET) || key.equals(SCANNERSET) || key.equals(SEQ_SCANNERSET) || key.equals(SEQ_FILTERSET) || (key > SEQ_SCANNERSET && key < SEQ_SCANNERSET_END) || (key > SEQ_FILTERSET && key < SEQ_FILTERSET_END)) {
                if (sequential && (key.equals(FILTERSET) || key.equals(SCANNERSET))) {
                    continue;
                }
                long offset = ((Long) ifd.get(key)).longValue();
                in.seek(offset);
                setSeries(i);
                parseInstrumentData(store, nextInstrumentBlock++);
            }
        }
        activeChannelIndices.clear();
        // link Instrument and Image
        store.setImageInstrumentRef(instrumentID, i);
        Length sizeX = FormatTools.getPhysicalSizeX(physicalSizes[i][0]);
        Length sizeY = FormatTools.getPhysicalSizeY(physicalSizes[i][1]);
        Length sizeZ = FormatTools.getPhysicalSizeZ(physicalSizes[i][2]);
        if (sizeX != null) {
            store.setPixelsPhysicalSizeX(sizeX, i);
        }
        if (sizeY != null) {
            store.setPixelsPhysicalSizeY(sizeY, i);
        }
        if (sizeZ != null) {
            store.setPixelsPhysicalSizeZ(sizeZ, i);
        }
        if ((int) physicalSizes[i][4] > 0) {
            store.setPixelsTimeIncrement(new Time(physicalSizes[i][4], UNITS.SECOND), i);
        }
        for (int j = 0; j < ms.imageCount; j++) {
            if (timestamps[i] != null && j < timestamps[i].length) {
                long time = DateTools.getTime(timestamps[i][j], DATE_FORMAT, ":");
                double elapsedTime = (double) (time - firstPlane) / 1000;
                store.setPlaneDeltaT(new Time(elapsedTime, UNITS.SECOND), i, j);
                if (exposureTime[i] > 0) {
                    store.setPlaneExposureTime(new Time(exposureTime[i], UNITS.SECOND), i, j);
                }
            }
        }
    }
    setSeries(0);
}
Also used : IFD(loci.formats.tiff.IFD) ArrayList(java.util.ArrayList) Time(ome.units.quantity.Time) Timestamp(ome.xml.model.primitives.Timestamp) ArrayList(java.util.ArrayList) IFDList(loci.formats.tiff.IFDList) List(java.util.List) CoreMetadata(loci.formats.CoreMetadata) FormatException(loci.formats.FormatException) MetadataStore(loci.formats.meta.MetadataStore) Length(ome.units.quantity.Length) IFDList(loci.formats.tiff.IFDList) TiffParser(loci.formats.tiff.TiffParser) RandomAccessInputStream(loci.common.RandomAccessInputStream) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) File(java.io.File) Location(loci.common.Location)

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