Search in sources :

Example 1 with MetadataStore

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

the class ImagePlusReader method constructSliceLabel.

private String constructSliceLabel(int ndx, IFormatReader r, IMetadata meta, int series, int zCount, int cCount, int tCount) {
    r.setSeries(series);
    String sliceLabelPattern = LociPrefs.getSliceLabelPattern();
    String order = r.getDimensionOrder();
    int sizeC = r.getEffectiveSizeC();
    int sizeT = r.getSizeT();
    int sizeZ = r.getSizeZ();
    int seriesCount = r.getImageCount();
    int indexBase = LociPrefs.getSliceLabelBaseIndex();
    int[] coordinates = FormatTools.getZCTCoords(order, sizeZ, sizeC, sizeT, sizeZ * sizeC * sizeT, ndx);
    MetadataStore store = r.getMetadataStore();
    MetadataRetrieve retrieve = store instanceof MetadataRetrieve ? (MetadataRetrieve) store : new DummyMetadata();
    String filename = sliceLabelPattern.replaceAll(FormatTools.SERIES_NUM, String.format("%d", series));
    String imageName = retrieve.getImageName(series);
    if (imageName == null)
        imageName = "Series" + series;
    filename = sliceLabelPattern;
    filename = filename.replaceAll(FormatTools.SERIES_NUM, String.format("%d", series));
    filename = filename.replaceAll(FormatTools.SERIES_NAME, imageName);
    if (sizeC > 1) {
        int[] subC;
        String[] subCTypes;
        Modulo moduloC = r.getModuloC();
        if (moduloC.length() > 1) {
            subC = new int[] { r.getSizeC() / moduloC.length(), moduloC.length() };
            subCTypes = new String[] { moduloC.parentType, moduloC.type };
        } else {
            subC = new int[] { r.getSizeC() };
            subCTypes = new String[] { FormatTools.CHANNEL };
        }
        int[] subCPos = FormatTools.rasterToPosition(subC, coordinates[1]);
        StringBuffer channelString = new StringBuffer();
        for (int i = 0; i < subC.length; i++) {
            boolean ch = subCTypes[i] == null || FormatTools.CHANNEL.equals(subCTypes[i]);
            channelString.append(ch ? "c" : subCTypes[i]);
            channelString.append(":");
            channelString.append(subCPos[i] + 1);
            channelString.append("/");
            channelString.append(subC[i]);
            if (i < subC.length - 1)
                channelString.append(", ");
        }
        filename = filename.replaceAll(FormatTools.CHANNEL_NUM, channelString.toString() + " ");
        int channelCount = retrieve.getChannelCount(series);
        if (coordinates[1] < channelCount) {
            String channelName = retrieve.getChannelName(series, coordinates[1]);
            if (channelName == null)
                channelName = String.valueOf(coordinates[1]);
            filename = filename.replaceAll(FormatTools.CHANNEL_NAME, channelName);
        } else {
            filename = filename.replaceAll(FormatTools.CHANNEL_NAME, String.valueOf(coordinates[1]));
        }
    } else {
        filename = filename.replaceAll(FormatTools.CHANNEL_NUM, "");
        filename = filename.replaceAll(FormatTools.CHANNEL_NAME, "");
    }
    if (sizeZ > 1) {
        filename = filename.replaceAll(FormatTools.Z_NUM, "z:" + String.format("%d", coordinates[0] + 1) + "/" + String.format("%d", sizeZ) + " ");
    } else {
        filename = filename.replaceAll(FormatTools.Z_NUM, "");
    }
    if (sizeT > 1) {
        filename = filename.replaceAll(FormatTools.T_NUM, "t:" + String.format("%d", coordinates[2] + 1) + "/" + String.format("%d", sizeT) + " ");
    } else {
        filename = filename.replaceAll(FormatTools.T_NUM, "");
    }
    Timestamp timestamp = retrieve.getImageAcquisitionDate(series);
    long stamp = 0;
    String date = null;
    if (timestamp != null) {
        date = timestamp.getValue();
        if (retrieve.getPlaneCount(series) > ndx) {
            Time deltaT = retrieve.getPlaneDeltaT(series, ndx);
            if (deltaT != null) {
                stamp = (long) (deltaT.value(UNITS.SECOND).doubleValue() * 1000);
            }
        }
        stamp += DateTools.getTime(date, DateTools.ISO8601_FORMAT);
    } else {
        stamp = System.currentTimeMillis();
    }
    date = DateTools.convertDate(stamp, (int) DateTools.UNIX_EPOCH);
    filename = filename.replaceAll(FormatTools.TIMESTAMP, date);
    return filename;
}
Also used : Modulo(loci.formats.Modulo) Time(ome.units.quantity.Time) Timestamp(ome.xml.model.primitives.Timestamp) MetadataStore(loci.formats.meta.MetadataStore) DummyMetadata(loci.formats.meta.DummyMetadata) MetadataRetrieve(loci.formats.meta.MetadataRetrieve)

Example 2 with MetadataStore

use of loci.formats.meta.MetadataStore 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 3 with MetadataStore

use of loci.formats.meta.MetadataStore 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)

Example 4 with MetadataStore

use of loci.formats.meta.MetadataStore 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 5 with MetadataStore

use of loci.formats.meta.MetadataStore 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)

Aggregations

MetadataStore (loci.formats.meta.MetadataStore)180 CoreMetadata (loci.formats.CoreMetadata)130 RandomAccessInputStream (loci.common.RandomAccessInputStream)97 Length (ome.units.quantity.Length)82 FormatException (loci.formats.FormatException)66 Timestamp (ome.xml.model.primitives.Timestamp)54 Location (loci.common.Location)51 Time (ome.units.quantity.Time)41 ArrayList (java.util.ArrayList)34 IFD (loci.formats.tiff.IFD)21 DependencyException (loci.common.services.DependencyException)16 IOException (java.io.IOException)15 TiffParser (loci.formats.tiff.TiffParser)15 NonNegativeInteger (ome.xml.model.primitives.NonNegativeInteger)15 ServiceFactory (loci.common.services.ServiceFactory)14 PositiveInteger (ome.xml.model.primitives.PositiveInteger)13 IFDList (loci.formats.tiff.IFDList)12 MetadataRetrieve (loci.formats.meta.MetadataRetrieve)11 ServiceException (loci.common.services.ServiceException)10 Map (java.util.Map)9