Search in sources :

Example 11 with Color

use of ome.xml.model.primitives.Color in project bioformats by openmicroscopy.

the class CellH5Reader method parseROIs.

private void parseROIs(int s) {
    int objectIdx = 0;
    List<Color> classColors = new ArrayList<Color>();
    int roiIndexOffset = 0;
    CellH5Coordinate coord = CellH5PositionList.get(0);
    for (String cellObjectName : cellObjectNames) {
        LOGGER.info("Parse segmentation ROIs for cell object {} : {}", cellObjectName, objectIdx);
        String featureName = CellH5Constants.FEATURE + cellObjectName + "/";
        String pathToBoundingBox = coord.pathToPosition + featureName + CellH5Constants.BBOX;
        String pathToClassDefinition = CellH5Constants.DEFINITION + featureName + CellH5Constants.CLASS_LABELS;
        boolean hasClassification = false;
        if (jhdf.exists(pathToClassDefinition)) {
            String classColorHexString;
            HDF5CompoundDataMap[] classDef = jhdf.readCompoundArrayDataMap(pathToClassDefinition);
            for (int cls = 0; cls < classDef.length; cls++) {
                classColorHexString = (String) classDef[cls].get("color");
                classColors.add(hex2Rgb(classColorHexString));
            }
            if (classDef.length > 0) {
                hasClassification = true;
                classes = jhdf.readCompoundArrayDataMap(coord.pathToPosition + featureName + CellH5Constants.PREDICTED_CLASS_LABELS);
            }
        }
        if (jhdf.exists(pathToBoundingBox)) {
            bbox = jhdf.readCompoundArrayDataMap(pathToBoundingBox);
            times = jhdf.readCompoundArrayDataMap(coord.pathToPosition + CellH5Constants.OBJECT + cellObjectName);
            int roiChannel = getChannelIndexOfCellObjectName(cellObjectName);
            int roiZSlice = 0;
            for (int roiIndex = 0; roiIndex < bbox.length; roiIndex++) {
                int roiManagerRoiIndex = roiIndex + roiIndexOffset;
                int roiTime = (Integer) times[roiIndex].get("time_idx");
                int objectLabelId = (Integer) times[roiIndex].get("obj_label_id");
                int left = (Integer) bbox[roiIndex].get("left");
                int right = (Integer) bbox[roiIndex].get("right");
                int top = (Integer) bbox[roiIndex].get("top");
                int bottom = (Integer) bbox[roiIndex].get("bottom");
                int width = right - left;
                int height = bottom - top;
                String roiID = MetadataTools.createLSID("ROI", roiManagerRoiIndex);
                store.setROIID(roiID, roiManagerRoiIndex);
                store.setImageROIRef(roiID, s, roiManagerRoiIndex);
                store.setROIName(cellObjectName + " " + objectLabelId, roiManagerRoiIndex);
                String shapeID = MetadataTools.createLSID("Shape", roiManagerRoiIndex, 0);
                store.setRectangleID(shapeID, roiManagerRoiIndex, 0);
                store.setRectangleX((double) left, roiManagerRoiIndex, 0);
                store.setRectangleY((double) top, roiManagerRoiIndex, 0);
                store.setRectangleWidth((double) width, roiManagerRoiIndex, 0);
                store.setRectangleHeight((double) height, roiManagerRoiIndex, 0);
                store.setRectangleText(cellObjectName, roiManagerRoiIndex, 0);
                store.setRectangleTheT(new NonNegativeInteger(roiTime), roiManagerRoiIndex, 0);
                store.setRectangleTheC(new NonNegativeInteger(roiChannel), roiManagerRoiIndex, 0);
                store.setRectangleTheZ(new NonNegativeInteger(roiZSlice), roiManagerRoiIndex, 0);
                Color strokeColor;
                if (hasClassification) {
                    int classLabelIDx = (Integer) classes[roiIndex].get("label_idx");
                    strokeColor = classColors.get(classLabelIDx);
                } else {
                    strokeColor = new Color(COLORS[objectIdx][0], COLORS[objectIdx][1], COLORS[objectIdx][2], 0xff);
                }
                store.setRectangleStrokeColor(strokeColor, roiManagerRoiIndex, 0);
            }
            objectIdx++;
            roiIndexOffset += bbox.length;
        } else {
            LOGGER.info("No Segmentation data found...");
            break;
        }
    }
}
Also used : NonNegativeInteger(ome.xml.model.primitives.NonNegativeInteger) HDF5CompoundDataMap(ch.systemsx.cisd.hdf5.HDF5CompoundDataMap) NonNegativeInteger(ome.xml.model.primitives.NonNegativeInteger) Color(ome.xml.model.primitives.Color) ArrayList(java.util.ArrayList)

Example 12 with Color

use of ome.xml.model.primitives.Color in project bioformats by openmicroscopy.

the class CellVoyagerReader method readChannel.

private ChannelInfo readChannel(final Element channelEl) {
    final ChannelInfo ci = new ChannelInfo();
    ci.isEnabled = Boolean.parseBoolean(getChildText(channelEl, "IsEnabled"));
    ci.channelNumber = Integer.parseInt(getChildText(channelEl, "Number"));
    final Element acquisitionSettings = getChild(channelEl, "AcquisitionSetting");
    final Element cameraEl = getChild(acquisitionSettings, "Camera");
    ci.tileWidth = Integer.parseInt(getChildText(cameraEl, "EffectiveHorizontalPixels_pixel"));
    ci.tileHeight = Integer.parseInt(getChildText(cameraEl, "EffectiveVerticalPixels_pixel"));
    ci.unmagnifiedPixelWidth = Double.parseDouble(getChildText(cameraEl, "HorizonalCellSize_um"));
    ci.unmagnifiedPixelHeight = Double.parseDouble(getChildText(cameraEl, "VerticalCellSize_um"));
    final Element colorElement = getChild(channelEl, new String[] { "ContrastEnhanceParam", "Color" });
    final int r = Integer.parseInt(getChildText(colorElement, "R"));
    final int g = Integer.parseInt(getChildText(colorElement, "G"));
    final int b = Integer.parseInt(getChildText(colorElement, "B"));
    final int a = Integer.parseInt(getChildText(colorElement, "A"));
    final Color channelColor = new Color(r, g, b, a);
    ci.color = channelColor;
    // Build a channel name from excitation, emission and fluorophore name
    final String excitationType = getChild(channelEl, "Excitation").getAttribute("xsi:type");
    final String excitationName = getChildText(channelEl, new String[] { "Excitation", "Name", "Value" });
    final String emissionName = getChildText(channelEl, new String[] { "Emission", "Name", "Value" });
    String fluorophoreName = getChildText(channelEl, new String[] { "Emission", "FluorescentProbe", "Value" });
    if (null == fluorophoreName) {
        fluorophoreName = "ΓΈ";
    }
    final String channelName = "Ex: " + excitationType + "(" + excitationName + ") / Em: " + emissionName + " / Fl: " + fluorophoreName;
    ci.name = channelName;
    return ci;
}
Also used : Element(org.w3c.dom.Element) Color(ome.xml.model.primitives.Color)

Example 13 with Color

use of ome.xml.model.primitives.Color in project bioformats by openmicroscopy.

the class ZeissCZIReader method initFile.

// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
    super.initFile(id);
    parser = XMLTools.createBuilder();
    // switch to the master file if this is part of a multi-file dataset
    int lastDot = id.lastIndexOf(".");
    String base = lastDot < 0 ? id : id.substring(0, lastDot);
    if (base.endsWith(")") && isGroupFiles()) {
        LOGGER.info("Checking for master file");
        int lastFileSeparator = base.lastIndexOf(File.separator);
        int end = base.lastIndexOf(" (");
        if (end < 0 || end < lastFileSeparator) {
            end = base.lastIndexOf("(");
        }
        if (end > 0 && end > lastFileSeparator) {
            base = base.substring(0, end) + ".czi";
            if (new Location(base).exists()) {
                LOGGER.info("Initializing master file {}", base);
                initFile(base);
                return;
            }
        }
    }
    CoreMetadata ms0 = core.get(0);
    ms0.littleEndian = true;
    pixels = new HashMap<Integer, String>();
    segments = new ArrayList<Segment>();
    planes = new ArrayList<SubBlock>();
    readSegments(id);
    // check if we have the master file in a multi-file dataset
    // file names are not stored in the files; we have to rely on a
    // specific naming convention:
    // 
    // master_file.czi
    // master_file (1).czi
    // master_file (2).czi
    // ...
    // 
    // the number of files is also not stored, so we have to manually check
    // for all files with a matching name
    Location file = new Location(id).getAbsoluteFile();
    base = file.getName();
    lastDot = base.lastIndexOf(".");
    if (lastDot >= 0) {
        base = base.substring(0, lastDot);
    }
    Location parent = file.getParentFile();
    String[] list = parent.list(true);
    for (String f : list) {
        if (f.startsWith(base + "(") || f.startsWith(base + " (")) {
            String part = f.substring(f.lastIndexOf("(") + 1, f.lastIndexOf(")"));
            try {
                pixels.put(Integer.parseInt(part), new Location(parent, f).getAbsolutePath());
            } catch (NumberFormatException e) {
                LOGGER.debug("{} not included in multi-file dataset", f);
            }
        }
    }
    Integer[] keys = pixels.keySet().toArray(new Integer[pixels.size()]);
    Arrays.sort(keys);
    for (Integer key : keys) {
        readSegments(pixels.get(key));
    }
    calculateDimensions();
    if (planes.size() == 0) {
        throw new FormatException("Pixel data could not be found; this file may be corrupted");
    }
    int firstX = planes.get(0).x;
    int firstY = planes.get(0).y;
    if (getSizeC() == 0) {
        ms0.sizeC = 1;
    }
    if (getSizeZ() == 0) {
        ms0.sizeZ = 1;
    }
    if (getSizeT() == 0) {
        ms0.sizeT = 1;
    }
    if (getImageCount() == 0) {
        ms0.imageCount = ms0.sizeZ * ms0.sizeT;
    }
    int originalC = getSizeC();
    convertPixelType(planes.get(0).directoryEntry.pixelType);
    // remove any invalid SubBlocks
    int bpp = FormatTools.getBytesPerPixel(getPixelType());
    if (isRGB()) {
        bpp *= (getSizeC() / originalC);
    }
    int fullResBlockCount = planes.size();
    for (int i = 0; i < planes.size(); i++) {
        long planeSize = (long) planes.get(i).x * planes.get(i).y * bpp;
        int compression = planes.get(i).directoryEntry.compression;
        if (compression == UNCOMPRESSED || compression == JPEGXR) {
            long size = planes.get(i).dataSize;
            if (size < planeSize || planeSize >= Integer.MAX_VALUE || size < 0) {
                // check for reduced resolution in the pyramid
                DimensionEntry[] entries = planes.get(i).directoryEntry.dimensionEntries;
                int pyramidType = planes.get(i).directoryEntry.pyramidType;
                if ((pyramidType == 1 || pyramidType == 2 || compression == JPEGXR) && (compression == JPEGXR || size == entries[0].storedSize * entries[1].storedSize * bpp)) {
                    int scale = planes.get(i).x / entries[0].storedSize;
                    if (scale == 1 || (((scale % 2) == 0 || (scale % 3) == 0) && allowAutostitching())) {
                        if (scale > 1 && scaleFactor == 0) {
                            scaleFactor = scale % 2 == 0 ? 2 : 3;
                        }
                        planes.get(i).coreIndex = 0;
                        while (scale > 1) {
                            scale /= scaleFactor;
                            planes.get(i).coreIndex++;
                        }
                        if (planes.get(i).coreIndex > maxResolution) {
                            maxResolution = planes.get(i).coreIndex;
                        }
                    } else {
                        LOGGER.trace("removing block #{}; calculated size = {}, recorded size = {}, scale = {}", i, planeSize, size, scale);
                        planes.remove(i);
                        i--;
                    }
                } else {
                    LOGGER.trace("removing block #{}; calculated size = {}, recorded size = {}", i, planeSize, size);
                    planes.remove(i);
                    i--;
                }
                fullResBlockCount--;
            } else {
                scanDim = (int) (size / planeSize);
            }
        } else {
            byte[] pixels = planes.get(i).readPixelData();
            if (pixels.length < planeSize || planeSize >= Integer.MAX_VALUE) {
                LOGGER.trace("removing block #{}; calculated size = {}, decoded size = {}", i, planeSize, pixels.length);
                planes.remove(i);
                i--;
            } else {
                scanDim = (int) (pixels.length / planeSize);
            }
        }
    }
    if (getSizeZ() == 0) {
        ms0.sizeZ = 1;
    }
    if (getSizeC() == 0) {
        ms0.sizeC = 1;
    }
    if (getSizeT() == 0) {
        ms0.sizeT = 1;
    }
    // set modulo annotations
    // rotations -> modulo Z
    // illuminations -> modulo C
    // phases -> modulo T
    LOGGER.trace("rotations = {}", rotations);
    LOGGER.trace("illuminations = {}", illuminations);
    LOGGER.trace("phases = {}", phases);
    LOGGER.trace("positions = {}", positions);
    LOGGER.trace("acquisitions = {}", acquisitions);
    LOGGER.trace("mosaics = {}", mosaics);
    LOGGER.trace("angles = {}", angles);
    ms0.moduloZ.step = ms0.sizeZ;
    ms0.moduloZ.end = ms0.sizeZ * (rotations - 1);
    ms0.moduloZ.type = FormatTools.ROTATION;
    ms0.sizeZ *= rotations;
    ms0.moduloC.step = ms0.sizeC;
    ms0.moduloC.end = ms0.sizeC * (illuminations - 1);
    ms0.moduloC.type = FormatTools.ILLUMINATION;
    ms0.moduloC.parentType = FormatTools.CHANNEL;
    ms0.sizeC *= illuminations;
    ms0.moduloT.step = ms0.sizeT;
    ms0.moduloT.end = ms0.sizeT * (phases - 1);
    ms0.moduloT.type = FormatTools.PHASE;
    ms0.sizeT *= phases;
    // finish populating the core metadata
    int seriesCount = positions * acquisitions * angles;
    int originalMosaicCount = mosaics;
    if (maxResolution == 0) {
        seriesCount *= mosaics;
    } else {
        prestitched = true;
    }
    ms0.imageCount = getSizeZ() * (isRGB() ? getSizeC() / 3 : getSizeC()) * getSizeT();
    LOGGER.trace("Size Z = {}", getSizeZ());
    LOGGER.trace("Size C = {}", getSizeC());
    LOGGER.trace("Size T = {}", getSizeT());
    LOGGER.trace("is RGB = {}", isRGB());
    LOGGER.trace("calculated image count = {}", ms0.imageCount);
    LOGGER.trace("number of available planes = {}", planes.size());
    LOGGER.trace("prestitched = {}", prestitched);
    LOGGER.trace("scanDim = {}", scanDim);
    int calculatedSeries = fullResBlockCount / getImageCount();
    if (((mosaics == seriesCount) || (positions == seriesCount)) && ((seriesCount == calculatedSeries) || (maxResolution > 0 && seriesCount * mosaics == calculatedSeries)) && prestitched != null && prestitched) {
        boolean equalTiles = true;
        for (SubBlock plane : planes) {
            if (plane.x != planes.get(0).x || plane.y != planes.get(0).y) {
                equalTiles = false;
                break;
            }
        }
        if ((getSizeX() > planes.get(0).x || (getSizeX() == planes.get(0).x && calculatedSeries == seriesCount * mosaics * positions)) && !equalTiles && allowAutostitching()) {
            // image was fused; treat the mosaics as a single image
            seriesCount = 1;
            positions = 1;
            acquisitions = 1;
            mosaics = 1;
            angles = 1;
        } else {
            int newX = planes.get(planes.size() - 1).x;
            int newY = planes.get(planes.size() - 1).y;
            if (allowAutostitching() && (ms0.sizeX < newX || ms0.sizeY < newY)) {
                prestitched = true;
                mosaics = 1;
            } else {
                prestitched = maxResolution > 0;
            }
            ms0.sizeX = newX;
            ms0.sizeY = newY;
        }
    } else if (!allowAutostitching() && calculatedSeries > seriesCount) {
        ms0.sizeX = firstX;
        ms0.sizeY = firstY;
        prestitched = true;
    }
    if (ms0.imageCount * seriesCount > planes.size() * scanDim && planes.size() > 0) {
        if (planes.size() != ms0.imageCount && planes.size() != ms0.sizeT && (planes.size() % (seriesCount * getSizeZ())) == 0) {
            if (!isGroupFiles() && planes.size() == (ms0.imageCount * seriesCount) / positions) {
                seriesCount /= positions;
                positions = 1;
            }
        } else if (planes.size() == ms0.sizeT || planes.size() == ms0.imageCount || (!isGroupFiles() && positions > 1)) {
            positions = 1;
            acquisitions = 1;
            mosaics = 1;
            angles = 1;
            seriesCount = 1;
        } else if (seriesCount > mosaics && mosaics > 1 && prestitched != null && prestitched) {
            seriesCount /= mosaics;
            mosaics = 1;
        }
    }
    ms0.dimensionOrder = "XYCZT";
    ArrayList<Integer> pixelTypes = new ArrayList<Integer>();
    pixelTypes.add(planes.get(0).directoryEntry.pixelType);
    if (maxResolution == 0) {
        for (SubBlock plane : planes) {
            if (!pixelTypes.contains(plane.directoryEntry.pixelType)) {
                pixelTypes.add(plane.directoryEntry.pixelType);
            }
            plane.pixelTypeIndex = pixelTypes.indexOf(plane.directoryEntry.pixelType);
        }
        if (seriesCount * pixelTypes.size() > 1) {
            core.clear();
            for (int j = 0; j < pixelTypes.size(); j++) {
                for (int i = 0; i < seriesCount; i++) {
                    CoreMetadata add = new CoreMetadata(ms0);
                    if (pixelTypes.size() > 1) {
                        int newC = originalC / pixelTypes.size();
                        add.sizeC = newC;
                        add.imageCount = add.sizeZ * add.sizeT;
                        add.rgb = false;
                        convertPixelType(add, pixelTypes.get(j));
                    }
                    core.add(add);
                }
            }
        }
    }
    if (seriesCount > 1 || maxResolution > 0) {
        core.clear();
        for (int i = 0; i < seriesCount; i++) {
            CoreMetadata add = new CoreMetadata(ms0);
            add.resolutionCount = maxResolution + 1;
            core.add(add);
            for (int r = 0; r < maxResolution; r++) {
                CoreMetadata resolution = new CoreMetadata(add);
                resolution.resolutionCount = 1;
                core.add(resolution);
            }
        }
    }
    assignPlaneIndices();
    if (maxResolution > 0) {
        tileWidth = new int[core.size()];
        tileHeight = new int[core.size()];
        for (int s = 0; s < core.size(); ) {
            if (s > 0) {
                core.get(s).sizeX = 0;
                core.get(s).sizeY = 0;
                calculateDimensions(s, true);
            }
            if (originalMosaicCount > 1) {
                // calculate total stitched size if the image was not fused
                int minRow = Integer.MAX_VALUE;
                int maxRow = Integer.MIN_VALUE;
                int minCol = Integer.MAX_VALUE;
                int maxCol = Integer.MIN_VALUE;
                int x = 0, y = 0;
                int lastX = 0, lastY = 0;
                for (SubBlock plane : planes) {
                    if (plane.coreIndex != s) {
                        continue;
                    }
                    if (x == 0 && y == 0) {
                        x = plane.x;
                        y = plane.y;
                    }
                    if (plane.row < minRow) {
                        minRow = plane.row;
                    }
                    if (plane.row > maxRow) {
                        maxRow = plane.row;
                    }
                    if (plane.col < minCol) {
                        minCol = plane.col;
                    }
                    if (plane.col > maxCol) {
                        maxCol = plane.col;
                    }
                    if (plane.x > tileWidth[s]) {
                        tileWidth[s] = plane.x;
                    }
                    if (plane.y > tileHeight[s]) {
                        tileHeight[s] = plane.y;
                    }
                    if (plane.row == maxRow && plane.col == maxCol) {
                        lastX = plane.x;
                        lastY = plane.y;
                    }
                }
                // don't overwrite the dimensions if stitching already occurred
                if (core.get(s).sizeX == x && core.get(s).sizeY == y) {
                    core.get(s).sizeX = (lastX + maxCol) - minCol;
                    core.get(s).sizeY = (lastY + maxRow) - minRow;
                }
            }
            boolean keepMissingPyramid = false;
            for (int r = 0; r < core.get(s).resolutionCount; r++) {
                boolean hasValidPlane = false;
                for (SubBlock plane : planes) {
                    if (plane.coreIndex == s + r) {
                        hasValidPlane = true;
                        break;
                    }
                }
                if (!hasValidPlane && r > 0 && !keepMissingPyramid) {
                    core.remove(s + r);
                    core.get(s).resolutionCount--;
                    // adjust the core indexes of any subsequent planes
                    for (SubBlock plane : planes) {
                        if (plane.coreIndex > s + r) {
                            plane.coreIndex--;
                        }
                    }
                    r--;
                } else {
                    int div = (int) Math.pow(scaleFactor, r);
                    if (r == 0 && s > 0 && core.get(s).sizeX == 1) {
                        core.get(s).sizeX = core.get(s - maxResolution).sizeX;
                        core.get(s).sizeY = core.get(s - maxResolution).sizeY;
                    } else {
                        core.get(s + r).sizeX = core.get(s).sizeX / div;
                        core.get(s + r).sizeY = core.get(s).sizeY / div;
                    }
                    tileWidth[s + r] = tileWidth[s] / div;
                    tileHeight[s + r] = tileHeight[s] / div;
                }
                if (r == 0 && !hasValidPlane) {
                    keepMissingPyramid = true;
                }
            }
            s += core.get(s).resolutionCount;
        }
    }
    // check for PALM data; requires planes to split into separate series
    String firstXML = null;
    boolean canSkipXML = true;
    String currentPath = new Location(currentId).getAbsolutePath();
    boolean isPALM = false;
    if (planes.size() <= 2 && getImageCount() <= 2) {
        for (Segment segment : segments) {
            String path = new Location(segment.filename).getAbsolutePath();
            if (currentPath.equals(path) && segment instanceof Metadata) {
                segment.fillInData();
                String xml = ((Metadata) segment).xml;
                xml = XMLTools.sanitizeXML(xml);
                if (firstXML == null && canSkipXML) {
                    firstXML = xml;
                }
                if (canSkipXML && firstXML.equals(xml)) {
                    isPALM = checkPALM(xml);
                } else if (!firstXML.equals(xml)) {
                    canSkipXML = false;
                }
                ((Metadata) segment).clearXML();
            }
        }
    }
    if (isPALM) {
        LOGGER.debug("Detected PALM data");
        core.get(0).sizeC = 1;
        core.get(0).imageCount = core.get(0).sizeZ * core.get(0).sizeT;
        for (int i = 0; i < planes.size(); i++) {
            SubBlock p = planes.get(i);
            int storedX = p.directoryEntry.dimensionEntries[0].storedSize;
            int storedY = p.directoryEntry.dimensionEntries[1].storedSize;
            if (p.planeIndex >= getImageCount()) {
                if (core.size() == 1) {
                    CoreMetadata second = new CoreMetadata(core.get(0));
                    core.add(second);
                }
                p.coreIndex = 1;
                p.planeIndex -= (planes.size() / 2);
                core.get(1).sizeX = storedX;
                core.get(1).sizeY = storedY;
            } else {
                core.get(0).sizeX = storedX;
                core.get(0).sizeY = storedY;
            }
        }
        if (core.size() == 2) {
            // prevent misidentification of PALM data; each plane should be a different size
            if (core.get(0).sizeX == core.get(1).sizeX && core.get(0).sizeY == core.get(1).sizeY) {
                isPALM = false;
                core.remove(1);
                core.get(0).sizeC = 2;
                core.get(0).imageCount *= getSizeC();
                for (int i = 0; i < planes.size(); i++) {
                    SubBlock p = planes.get(i);
                    if (p.coreIndex == 1) {
                        p.coreIndex = 0;
                        p.planeIndex += (planes.size() / 2);
                    }
                }
            }
        }
    }
    // find and add attached label/overview images
    readAttachments();
    // populate the OME metadata
    store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this, true);
    firstXML = null;
    canSkipXML = true;
    for (Segment segment : segments) {
        String path = new Location(segment.filename).getAbsolutePath();
        if (currentPath.equals(path) && segment instanceof Metadata) {
            segment.fillInData();
            String xml = ((Metadata) segment).xml;
            xml = XMLTools.sanitizeXML(xml);
            if (firstXML == null && canSkipXML) {
                firstXML = xml;
            }
            if (canSkipXML && firstXML.equals(xml)) {
                translateMetadata(xml);
            } else if (!firstXML.equals(xml)) {
                canSkipXML = false;
            }
            ((Metadata) segment).clearXML();
        } else if (segment instanceof Attachment) {
            AttachmentEntry entry = ((Attachment) segment).attachment;
            String name = entry.name.trim();
            if (name.equals("TimeStamps")) {
                segment.fillInData();
                RandomAccessInputStream s = new RandomAccessInputStream(((Attachment) segment).attachmentData);
                try {
                    s.order(isLittleEndian());
                    s.seek(8);
                    while (s.getFilePointer() + 8 <= s.length()) {
                        timestamps.add(s.readDouble());
                    }
                } finally {
                    s.close();
                }
            }
        }
        segment.close();
    }
    if (rotationLabels != null) {
        ms0.moduloZ.labels = rotationLabels;
        ms0.moduloZ.end = ms0.moduloZ.start;
    }
    if (illuminationLabels != null) {
        ms0.moduloC.labels = illuminationLabels;
        ms0.moduloC.end = ms0.moduloC.start;
    }
    if (phaseLabels != null) {
        ms0.moduloT.labels = phaseLabels;
        ms0.moduloT.end = ms0.moduloT.start;
    }
    for (int i = 0; i < planes.size(); i++) {
        SubBlock p = planes.get(i);
        Coordinate c = new Coordinate(p.coreIndex, p.planeIndex, getImageCount());
        ArrayList<Integer> indices = new ArrayList<Integer>();
        if (indexIntoPlanes.containsKey(c)) {
            indices = indexIntoPlanes.get(c);
        }
        indices.add(i);
        indexIntoPlanes.put(c, indices);
        // Add series metadata : populate position list
        int nameWidth = String.valueOf(getSeriesCount()).length();
        for (DimensionEntry dimension : p.directoryEntry.dimensionEntries) {
            if (dimension == null) {
                continue;
            }
            switch(dimension.dimension.charAt(0)) {
                case 'S':
                    setCoreIndex(p.coreIndex);
                    int seriesId = p.coreIndex + 1;
                    // add padding to make sure the original metadata table is organized properly in ImageJ
                    String sIndex = String.format("Positions|Series %0" + nameWidth + "d|", seriesId);
                    addSeriesMetaList(sIndex, dimension.start);
                    break;
            }
        }
        setCoreIndex(0);
    }
    if (channels.size() > 0 && channels.get(0).color != null && !isRGB()) {
        for (int i = 0; i < seriesCount; i++) {
            core.get(i).indexed = true;
        }
    }
    String experimenterID = MetadataTools.createLSID("Experimenter", 0);
    store.setExperimenterID(experimenterID, 0);
    store.setExperimenterEmail(userEmail, 0);
    store.setExperimenterFirstName(userFirstName, 0);
    store.setExperimenterInstitution(userInstitution, 0);
    store.setExperimenterLastName(userLastName, 0);
    store.setExperimenterMiddleName(userMiddleName, 0);
    store.setExperimenterUserName(userName, 0);
    String name = new Location(getCurrentFile()).getName();
    if (imageName != null && imageName.trim().length() > 0) {
        name = imageName;
    }
    store.setInstrumentID(MetadataTools.createLSID("Instrument", 0), 0);
    int indexLength = String.valueOf(getSeriesCount()).length();
    for (int i = 0; i < getSeriesCount(); i++) {
        store.setImageInstrumentRef(MetadataTools.createLSID("Instrument", 0), i);
        if (acquiredDate != null) {
            store.setImageAcquisitionDate(new Timestamp(acquiredDate), i);
        } else if (planes.get(0).timestamp != null) {
            long timestamp = (long) (planes.get(0).timestamp * 1000);
            String date = DateTools.convertDate(timestamp, DateTools.UNIX);
            store.setImageAcquisitionDate(new Timestamp(date), i);
        }
        if (experimenterID != null) {
            store.setImageExperimenterRef(experimenterID, i);
        }
        if (timeIncrement != null) {
            store.setPixelsTimeIncrement(timeIncrement, i);
        }
        String imageIndex = String.valueOf(i + 1);
        while (imageIndex.length() < indexLength) {
            imageIndex = "0" + imageIndex;
        }
        int extraIndex = i - (getSeriesCount() - extraImages.size());
        if (extraIndex < 0) {
            if (hasFlattenedResolutions()) {
                store.setImageName(name + " #" + imageIndex, i);
            } else if (positions == 1) {
                store.setImageName("", i);
            } else {
                store.setImageName("Scene #" + i, i);
            }
        } else if (extraIndex == 0) {
            store.setImageName("label image", i);
        } else if (extraIndex == 1) {
            store.setImageName("macro image", i);
        } else {
            store.setImageName("thumbnail image", i);
        }
        // label and macro images
        if (extraIndex >= 0) {
            continue;
        }
        if (description != null && description.length() > 0) {
            store.setImageDescription(description, i);
        }
        if (airPressure != null) {
            store.setImagingEnvironmentAirPressure(new Pressure(new Double(airPressure), UNITS.MILLIBAR), i);
        }
        if (co2Percent != null) {
            store.setImagingEnvironmentCO2Percent(PercentFraction.valueOf(co2Percent), i);
        }
        if (humidity != null) {
            store.setImagingEnvironmentHumidity(PercentFraction.valueOf(humidity), i);
        }
        if (temperature != null) {
            store.setImagingEnvironmentTemperature(new Temperature(new Double(temperature), UNITS.CELSIUS), i);
        }
        if (objectiveSettingsID != null) {
            store.setObjectiveSettingsID(objectiveSettingsID, i);
            if (correctionCollar != null) {
                store.setObjectiveSettingsCorrectionCollar(new Double(correctionCollar), i);
            }
            if (medium != null) {
                store.setObjectiveSettingsMedium(getMedium(medium), i);
            }
            if (refractiveIndex != null) {
                store.setObjectiveSettingsRefractiveIndex(new Double(refractiveIndex), i);
            }
        }
        Double startTime = null;
        if (acquiredDate != null) {
            Timestamp t = Timestamp.valueOf(acquiredDate);
            if (t != null)
                startTime = t.asInstant().getMillis() / 1000d;
        }
        for (int plane = 0; plane < getImageCount(); plane++) {
            Coordinate coordinate = new Coordinate(i, plane, getImageCount());
            ArrayList<Integer> index = indexIntoPlanes.get(coordinate);
            if (index == null) {
                continue;
            }
            SubBlock p = planes.get(index.get(0));
            if (startTime == null) {
                startTime = p.timestamp;
            }
            if (p.stageX != null) {
                store.setPlanePositionX(p.stageX, i, plane);
            } else if (positionsX != null && i < positionsX.length && positionsX[i] != null) {
                store.setPlanePositionX(positionsX[i], i, plane);
            } else {
                store.setPlanePositionX(new Length(p.col, UNITS.REFERENCEFRAME), i, plane);
            }
            if (p.stageY != null) {
                store.setPlanePositionY(p.stageY, i, plane);
            } else if (positionsY != null && i < positionsY.length && positionsY[i] != null) {
                store.setPlanePositionY(positionsY[i], i, plane);
            } else {
                store.setPlanePositionY(new Length(p.row, UNITS.REFERENCEFRAME), i, plane);
            }
            if (p.stageZ != null) {
                store.setPlanePositionZ(p.stageZ, i, plane);
            } else if (positionsZ != null && i < positionsZ.length) {
                int zIndex = getZCTCoords(plane)[0];
                if (positionsZ[i] != null) {
                    if (zStep != null) {
                        double value = positionsZ[i].value(zStep.unit()).doubleValue();
                        if (zStep != null) {
                            value += zIndex * zStep.value().doubleValue();
                        }
                        Length pos = new Length(value, zStep.unit());
                        store.setPlanePositionZ(pos, i, plane);
                    } else {
                        store.setPlanePositionZ(positionsZ[i], i, plane);
                    }
                }
            }
            if (p.timestamp != null) {
                store.setPlaneDeltaT(new Time(p.timestamp - startTime, UNITS.SECOND), i, plane);
            } else if (plane < timestamps.size() && timestamps.size() == getImageCount()) {
                // only use the plane index if there is one timestamp per plane
                if (timestamps.get(plane) != null) {
                    store.setPlaneDeltaT(new Time(timestamps.get(plane), UNITS.SECOND), i, plane);
                }
            } else if (getZCTCoords(plane)[2] < timestamps.size()) {
                // otherwise use the timepoint index, to prevent incorrect timestamping of channels
                int t = getZCTCoords(plane)[2];
                if (timestamps.get(t) != null) {
                    store.setPlaneDeltaT(new Time(timestamps.get(t), UNITS.S), i, plane);
                }
            }
            if (p.exposureTime != null) {
                store.setPlaneExposureTime(new Time(p.exposureTime, UNITS.SECOND), i, plane);
            } else {
                int channel = getZCTCoords(plane)[1];
                if (channel < channels.size() && channels.get(channel).exposure != null) {
                    store.setPlaneExposureTime(new Time(channels.get(channel).exposure, UNITS.SECOND), i, plane);
                }
            }
        }
        for (int c = 0; c < getEffectiveSizeC(); c++) {
            if (c < channels.size()) {
                if (isPALM && i < channels.size()) {
                    store.setChannelName(channels.get(i).name, i, c);
                } else {
                    store.setChannelName(channels.get(c).name, i, c);
                }
                store.setChannelFluor(channels.get(c).fluor, i, c);
                if (channels.get(c).filterSetRef != null) {
                    store.setChannelFilterSetRef(channels.get(c).filterSetRef, i, c);
                }
                String color = channels.get(c).color;
                if (color != null && !isRGB()) {
                    color = color.replaceAll("#", "");
                    if (color.length() > 6) {
                        color = color.substring(2, color.length());
                    }
                    try {
                        // shift by 8 to allow alpha in the final byte
                        store.setChannelColor(new Color((Integer.parseInt(color, 16) << 8) | 0xff), i, c);
                    } catch (NumberFormatException e) {
                        LOGGER.warn("", e);
                    }
                }
                String emWave = channels.get(c).emission;
                if (emWave != null) {
                    Double wave = new Double(emWave);
                    Length em = FormatTools.getEmissionWavelength(wave);
                    if (em != null) {
                        store.setChannelEmissionWavelength(em, i, c);
                    }
                }
                String exWave = channels.get(c).excitation;
                if (exWave != null) {
                    Double wave = new Double(exWave);
                    Length ex = FormatTools.getExcitationWavelength(wave);
                    if (ex != null) {
                        store.setChannelExcitationWavelength(ex, i, c);
                    }
                }
                if (channels.get(c).illumination != null) {
                    store.setChannelIlluminationType(channels.get(c).illumination, i, c);
                }
                if (channels.get(c).pinhole != null) {
                    store.setChannelPinholeSize(new Length(new Double(channels.get(c).pinhole), UNITS.MICROMETER), i, c);
                }
                if (channels.get(c).acquisitionMode != null) {
                    store.setChannelAcquisitionMode(channels.get(c).acquisitionMode, i, c);
                }
            }
            if (c < detectorRefs.size()) {
                String detector = detectorRefs.get(c);
                store.setDetectorSettingsID(detector, i, c);
                if (c < binnings.size()) {
                    store.setDetectorSettingsBinning(getBinning(binnings.get(c)), i, c);
                }
                if (c < channels.size()) {
                    store.setDetectorSettingsGain(channels.get(c).gain, i, c);
                }
            }
            if (c < channels.size()) {
                if (hasDetectorSettings) {
                    store.setDetectorSettingsGain(channels.get(c).gain, i, c);
                }
            }
        }
    }
    // not needed by further calls on the reader
    segments = null;
}
Also used : Temperature(ome.units.quantity.Temperature) ArrayList(java.util.ArrayList) CoreMetadata(loci.formats.CoreMetadata) Time(ome.units.quantity.Time) Timestamp(ome.xml.model.primitives.Timestamp) Color(ome.xml.model.primitives.Color) CoreMetadata(loci.formats.CoreMetadata) Pressure(ome.units.quantity.Pressure) FormatException(loci.formats.FormatException) Length(ome.units.quantity.Length) RandomAccessInputStream(loci.common.RandomAccessInputStream) Location(loci.common.Location)

Example 14 with Color

use of ome.xml.model.primitives.Color in project bioformats by openmicroscopy.

the class ZeissLSMReader method initMetadata.

protected void initMetadata(int series) throws FormatException, IOException {
    setSeries(series);
    IFDList ifds = ifdsList.get(series);
    IFD ifd = ifds.get(0);
    in.close();
    in = new RandomAccessInputStream(getLSMFileFromSeries(series), 16);
    in.order(isLittleEndian());
    tiffParser = new TiffParser(in);
    PhotoInterp photo = ifd.getPhotometricInterpretation();
    int samples = ifd.getSamplesPerPixel();
    CoreMetadata ms = core.get(series);
    ms.sizeX = (int) ifd.getImageWidth();
    ms.sizeY = (int) ifd.getImageLength();
    ms.rgb = samples > 1 || photo == PhotoInterp.RGB;
    ms.interleaved = false;
    ms.sizeC = isRGB() ? samples : 1;
    ms.pixelType = ifd.getPixelType();
    ms.imageCount = ifds.size();
    ms.sizeZ = getImageCount();
    ms.sizeT = 1;
    LOGGER.info("Reading LSM metadata for series #{}", series);
    MetadataStore store = makeFilterMetadata();
    int instrument = getEffectiveSeries(series);
    String imageName = getLSMFileFromSeries(series);
    if (imageName.indexOf('.') != -1) {
        imageName = imageName.substring(0, imageName.lastIndexOf("."));
    }
    if (imageName.indexOf(File.separator) != -1) {
        imageName = imageName.substring(imageName.lastIndexOf(File.separator) + 1);
    }
    if (lsmFilenames.length != getSeriesCount()) {
        imageName += " #" + (getPosition(series) + 1);
    }
    // link Instrument and Image
    store.setImageID(MetadataTools.createLSID("Image", series), series);
    String instrumentID = MetadataTools.createLSID("Instrument", instrument);
    store.setInstrumentID(instrumentID, instrument);
    store.setImageInstrumentRef(instrumentID, series);
    RandomAccessInputStream ras = getCZTag(ifd);
    if (ras == null) {
        imageNames.add(imageName);
        return;
    }
    ras.seek(16);
    ms.sizeZ = ras.readInt();
    ras.skipBytes(4);
    ms.sizeT = ras.readInt();
    int dataType = ras.readInt();
    switch(dataType) {
        case 2:
            addSeriesMeta("DataType", "12 bit unsigned integer");
            break;
        case 5:
            addSeriesMeta("DataType", "32 bit float");
            break;
        case 0:
            addSeriesMeta("DataType", "varying data types");
            break;
        default:
            addSeriesMeta("DataType", "8 bit unsigned integer");
    }
    if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
        ras.seek(0);
        addSeriesMeta("MagicNumber ", ras.readInt());
        addSeriesMeta("StructureSize", ras.readInt());
        addSeriesMeta("DimensionX", ras.readInt());
        addSeriesMeta("DimensionY", ras.readInt());
        ras.seek(32);
        addSeriesMeta("ThumbnailX", ras.readInt());
        addSeriesMeta("ThumbnailY", ras.readInt());
        // pixel sizes are stored in meters, we need them in microns
        pixelSizeX = ras.readDouble() * 1000000;
        pixelSizeY = ras.readDouble() * 1000000;
        pixelSizeZ = ras.readDouble() * 1000000;
        addSeriesMeta("VoxelSizeX", pixelSizeX);
        addSeriesMeta("VoxelSizeY", pixelSizeY);
        addSeriesMeta("VoxelSizeZ", pixelSizeZ);
        originX = ras.readDouble() * 1000000;
        originY = ras.readDouble() * 1000000;
        originZ = ras.readDouble() * 1000000;
        addSeriesMeta("OriginX", originX);
        addSeriesMeta("OriginY", originY);
        addSeriesMeta("OriginZ", originZ);
    } else
        ras.seek(88);
    int scanType = ras.readShort();
    switch(scanType) {
        case 0:
            addSeriesMeta("ScanType", "x-y-z scan");
            ms.dimensionOrder = "XYZCT";
            break;
        case 1:
            addSeriesMeta("ScanType", "z scan (x-z plane)");
            ms.dimensionOrder = "XYZCT";
            break;
        case 2:
            addSeriesMeta("ScanType", "line scan");
            ms.dimensionOrder = "XYZCT";
            break;
        case 3:
            addSeriesMeta("ScanType", "time series x-y");
            ms.dimensionOrder = "XYTCZ";
            break;
        case 4:
            addSeriesMeta("ScanType", "time series x-z");
            ms.dimensionOrder = "XYZTC";
            break;
        case 5:
            addSeriesMeta("ScanType", "time series 'Mean of ROIs'");
            ms.dimensionOrder = "XYTCZ";
            break;
        case 6:
            addSeriesMeta("ScanType", "time series x-y-z");
            ms.dimensionOrder = "XYZTC";
            break;
        case 7:
            addSeriesMeta("ScanType", "spline scan");
            ms.dimensionOrder = "XYCTZ";
            break;
        case 8:
            addSeriesMeta("ScanType", "spline scan x-z");
            ms.dimensionOrder = "XYCZT";
            break;
        case 9:
            addSeriesMeta("ScanType", "time series spline plane x-z");
            ms.dimensionOrder = "XYTCZ";
            break;
        case 10:
            addSeriesMeta("ScanType", "point mode");
            ms.dimensionOrder = "XYZCT";
            break;
        default:
            addSeriesMeta("ScanType", "x-y-z scan");
            ms.dimensionOrder = "XYZCT";
    }
    ms.indexed = lut != null && lut[series] != null;
    if (isIndexed()) {
        ms.rgb = false;
    }
    if (getSizeC() == 0)
        ms.sizeC = 1;
    if (isRGB()) {
        // shuffle C to front of order string
        ms.dimensionOrder = getDimensionOrder().replaceAll("C", "");
        ms.dimensionOrder = getDimensionOrder().replaceAll("XY", "XYC");
    }
    if (getEffectiveSizeC() == 0) {
        ms.imageCount = getSizeZ() * getSizeT();
    } else {
        ms.imageCount = getSizeZ() * getSizeT() * getEffectiveSizeC();
    }
    if (getImageCount() != ifds.size()) {
        int diff = getImageCount() - ifds.size();
        ms.imageCount = ifds.size();
        if (diff % getSizeZ() == 0) {
            ms.sizeT -= (diff / getSizeZ());
        } else if (diff % getSizeT() == 0) {
            ms.sizeZ -= (diff / getSizeT());
        } else if (getSizeZ() > 1) {
            ms.sizeZ = ifds.size();
            ms.sizeT = 1;
        } else if (getSizeT() > 1) {
            ms.sizeT = ifds.size();
            ms.sizeZ = 1;
        }
    }
    if (getSizeZ() == 0)
        ms.sizeZ = getImageCount();
    if (getSizeT() == 0)
        ms.sizeT = getImageCount() / getSizeZ();
    long channelColorsOffset = 0;
    long timeStampOffset = 0;
    long eventListOffset = 0;
    long scanInformationOffset = 0;
    long channelWavelengthOffset = 0;
    long applicationTagOffset = 0;
    channelColor = new Color[getSizeC()];
    if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
        int spectralScan = ras.readShort();
        if (spectralScan != 1) {
            addSeriesMeta("SpectralScan", "no spectral scan");
        } else
            addSeriesMeta("SpectralScan", "acquired with spectral scan");
        int type = ras.readInt();
        switch(type) {
            case 1:
                addSeriesMeta("DataType2", "calculated data");
                break;
            case 2:
                addSeriesMeta("DataType2", "animation");
                break;
            default:
                addSeriesMeta("DataType2", "original scan data");
        }
        long[] overlayOffsets = new long[9];
        String[] overlayKeys = new String[] { "VectorOverlay", "InputLut", "OutputLut", "ROI", "BleachROI", "MeanOfRoisOverlay", "TopoIsolineOverlay", "TopoProfileOverlay", "LinescanOverlay" };
        overlayOffsets[0] = ras.readInt();
        overlayOffsets[1] = ras.readInt();
        overlayOffsets[2] = ras.readInt();
        channelColorsOffset = ras.readInt();
        addSeriesMeta("TimeInterval", ras.readDouble());
        ras.skipBytes(4);
        scanInformationOffset = ras.readInt();
        applicationTagOffset = ras.readInt();
        timeStampOffset = ras.readInt();
        eventListOffset = ras.readInt();
        overlayOffsets[3] = ras.readInt();
        overlayOffsets[4] = ras.readInt();
        ras.skipBytes(4);
        addSeriesMeta("DisplayAspectX", ras.readDouble());
        addSeriesMeta("DisplayAspectY", ras.readDouble());
        addSeriesMeta("DisplayAspectZ", ras.readDouble());
        addSeriesMeta("DisplayAspectTime", ras.readDouble());
        overlayOffsets[5] = ras.readInt();
        overlayOffsets[6] = ras.readInt();
        overlayOffsets[7] = ras.readInt();
        overlayOffsets[8] = ras.readInt();
        if (getMetadataOptions().getMetadataLevel() != MetadataLevel.NO_OVERLAYS) {
            for (int i = 0; i < overlayOffsets.length; i++) {
                parseOverlays(series, overlayOffsets[i], overlayKeys[i], store);
            }
        }
        addSeriesMeta("ToolbarFlags", ras.readInt());
        channelWavelengthOffset = ras.readInt();
        ras.skipBytes(64);
    } else
        ras.skipBytes(182);
    if (getSizeC() > 1) {
        if (!splitPlanes)
            splitPlanes = isRGB();
        ms.rgb = false;
        if (splitPlanes)
            ms.imageCount *= getSizeC();
    }
    // NB: the Zeiss LSM 5.5 specification indicates that there should be
    // 15 32-bit integers here; however, there are actually 16 32-bit
    // integers before the tile position offset.
    // We have confirmed with Zeiss that this is correct, and the 6.0
    // specification was updated to contain the correct information.
    // rotations and phases may be reversed
    // we only have examples where both values are equal
    rotations = ras.readInt();
    phases = ras.readInt();
    illuminations = ras.readInt();
    if (rotations > 1) {
        ms.moduloZ.step = ms.sizeZ;
        ms.moduloZ.end = ms.sizeZ * (rotations - 1);
        ms.moduloZ.type = FormatTools.ROTATION;
        ms.sizeZ *= rotations;
    }
    if (illuminations > 1) {
        ms.moduloC.step = ms.sizeC;
        ms.moduloC.end = ms.sizeC * (illuminations - 1);
        ms.moduloC.type = FormatTools.ILLUMINATION;
        ms.moduloC.parentType = FormatTools.CHANNEL;
        ms.sizeC *= illuminations;
    }
    if (phases > 1) {
        ms.moduloT.step = ms.sizeT;
        ms.moduloT.end = ms.sizeT * (phases - 1);
        ms.moduloT.type = FormatTools.PHASE;
        ms.sizeT *= phases;
    }
    for (int c = 0; c < getEffectiveSizeC(); c++) {
        String lsid = MetadataTools.createLSID("Channel", series, c);
        store.setChannelID(lsid, series, c);
    }
    if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
        ras.skipBytes(52);
        int tilePositionOffset = ras.readInt();
        ras.skipBytes(36);
        int positionOffset = ras.readInt();
        // read referenced structures
        addSeriesMeta("DimensionZ", getSizeZ());
        addSeriesMeta("DimensionChannels", getSizeC());
        addSeriesMeta("DimensionM", dimensionM);
        addSeriesMeta("DimensionP", dimensionP);
        if (lsmFilenames.length == 1) {
            xCoordinates.clear();
            yCoordinates.clear();
            zCoordinates.clear();
        }
        if (positionOffset != 0) {
            in.seek(positionOffset);
            int nPositions = in.readInt();
            for (int i = 0; i < nPositions; i++) {
                double xPos = originX + in.readDouble() * 1000000;
                double yPos = originY + in.readDouble() * 1000000;
                double zPos = originZ + in.readDouble() * 1000000;
                xCoordinates.add(xPos);
                yCoordinates.add(yPos);
                zCoordinates.add(zPos);
                addGlobalMetaList("X position for position", xPos);
                addGlobalMetaList("Y position for position", yPos);
                addGlobalMetaList("Z position for position", zPos);
            }
        }
        if (tilePositionOffset != 0) {
            in.seek(tilePositionOffset);
            int nTiles = in.readInt();
            for (int i = 0; i < nTiles; i++) {
                double xPos = originX + in.readDouble() * 1000000;
                double yPos = originY + in.readDouble() * 1000000;
                double zPos = originZ + in.readDouble() * 1000000;
                if (xCoordinates.size() > i) {
                    xPos += xCoordinates.get(i);
                    xCoordinates.set(i, xPos);
                } else if (xCoordinates.size() == i) {
                    xCoordinates.add(xPos);
                }
                if (yCoordinates.size() > i) {
                    yPos += yCoordinates.get(i);
                    yCoordinates.set(i, yPos);
                } else if (yCoordinates.size() == i) {
                    yCoordinates.add(yPos);
                }
                if (zCoordinates.size() > i) {
                    zPos += zCoordinates.get(i);
                    zCoordinates.set(i, zPos);
                } else if (zCoordinates.size() == i) {
                    zCoordinates.add(zPos);
                }
                addGlobalMetaList("X position for position", xPos);
                addGlobalMetaList("Y position for position", yPos);
                addGlobalMetaList("Z position for position", zPos);
            }
        }
        if (channelColorsOffset != 0) {
            in.seek(channelColorsOffset + 12);
            int colorsOffset = in.readInt();
            int namesOffset = in.readInt();
            if (colorsOffset > 0) {
                in.seek(channelColorsOffset + colorsOffset);
                lut[getSeries()] = new byte[getSizeC() * 3][256];
                core.get(getSeries()).indexed = true;
                for (int i = 0; i < getSizeC(); i++) {
                    if (i >= channelColor.length) {
                        continue;
                    }
                    int color = in.readInt();
                    int red = color & 0xff;
                    int green = (color & 0xff00) >> 8;
                    int blue = (color & 0xff0000) >> 16;
                    // otherwise set the color to white, as this will display better
                    if (red == 0 && green == 0 & blue == 0) {
                        if (i > 0) {
                            red = channelColor[i - 1].getRed();
                            green = channelColor[i - 1].getGreen();
                            blue = channelColor[i - 1].getBlue();
                        } else {
                            red = 255;
                            green = 255;
                            blue = 255;
                        }
                    }
                    channelColor[i] = new Color(red, green, blue, 255);
                    for (int j = 0; j < 256; j++) {
                        lut[getSeries()][i * 3][j] = (byte) ((red / 255.0) * j);
                        lut[getSeries()][i * 3 + 1][j] = (byte) ((green / 255.0) * j);
                        lut[getSeries()][i * 3 + 2][j] = (byte) ((blue / 255.0) * j);
                    }
                }
            }
            if (namesOffset > 0) {
                in.seek(channelColorsOffset + namesOffset);
                channelNames[series] = new String[getSizeC()];
                for (int i = 0; i < getSizeC(); i++) {
                    if (in.getFilePointer() >= in.length() - 1)
                        break;
                    // we want to read until we find a null char
                    int length = in.readInt();
                    String name = in.readString(length);
                    while ((name.length() > 0) && (name.codePointAt(name.length() - 1) == 0)) {
                        name = name.substring(0, name.length() - 1);
                    }
                    if (name.length() <= 128) {
                        addSeriesMetaList("ChannelName", name);
                    }
                    channelNames[series][i] = name;
                }
            }
        }
        if (timeStampOffset != 0) {
            in.seek(timeStampOffset + 4);
            int nStamps = in.readInt();
            for (int i = 0; i < nStamps; i++) {
                double stamp = in.readDouble();
                addSeriesMetaList("TimeStamp", stamp);
                timestamps.add(stamp);
            }
        }
        if (eventListOffset != 0) {
            in.seek(eventListOffset + 4);
            int numEvents = in.readInt();
            in.seek(in.getFilePointer() - 4);
            in.order(!in.isLittleEndian());
            int tmpEvents = in.readInt();
            if (numEvents < 0)
                numEvents = tmpEvents;
            else
                numEvents = (int) Math.min(numEvents, tmpEvents);
            in.order(!in.isLittleEndian());
            if (numEvents > 65535)
                numEvents = 0;
            for (int i = 0; i < numEvents; i++) {
                if (in.getFilePointer() + 16 <= in.length()) {
                    int size = in.readInt();
                    double eventTime = in.readDouble();
                    int eventType = in.readInt();
                    addSeriesMetaList("Event Time", eventTime);
                    addSeriesMetaList("Event Type", eventType);
                    long fp = in.getFilePointer();
                    int len = size - 16;
                    if (len > 65536)
                        len = 65536;
                    if (len < 0)
                        len = 0;
                    addSeriesMetaList("Event Description", in.readString(len));
                    in.seek(fp + size - 16);
                    if (in.getFilePointer() < 0)
                        break;
                }
            }
        }
        if (scanInformationOffset != 0) {
            in.seek(scanInformationOffset);
            nextLaser = nextDetector = 0;
            nextFilter = nextDichroicChannel = nextDichroic = 0;
            nextDetectChannel = nextIllumChannel = 0;
            final List<SubBlock> blocks = new ArrayList<SubBlock>();
            while (in.getFilePointer() < in.length() - 12) {
                if (in.getFilePointer() < 0)
                    break;
                int entry = in.readInt();
                int blockType = in.readInt();
                int dataSize = in.readInt();
                if (blockType == TYPE_SUBBLOCK) {
                    SubBlock block = null;
                    switch(entry) {
                        case SUBBLOCK_RECORDING:
                            block = new Recording();
                            break;
                        case SUBBLOCK_LASER:
                            block = new Laser();
                            break;
                        case SUBBLOCK_TRACK:
                            block = new Track();
                            break;
                        case SUBBLOCK_DETECTION_CHANNEL:
                            block = new DetectionChannel();
                            break;
                        case SUBBLOCK_ILLUMINATION_CHANNEL:
                            block = new IlluminationChannel();
                            break;
                        case SUBBLOCK_BEAM_SPLITTER:
                            block = new BeamSplitter();
                            break;
                        case SUBBLOCK_DATA_CHANNEL:
                            block = new DataChannel();
                            break;
                        case SUBBLOCK_TIMER:
                            block = new Timer();
                            break;
                        case SUBBLOCK_MARKER:
                            block = new Marker();
                            break;
                    }
                    if (block != null) {
                        blocks.add(block);
                    }
                } else if (dataSize + in.getFilePointer() <= in.length() && dataSize > 0) {
                    in.skipBytes(dataSize);
                } else
                    break;
            }
            final List<SubBlock> nonAcquiredBlocks = new ArrayList<SubBlock>();
            SubBlock[] metadataBlocks = blocks.toArray(new SubBlock[0]);
            for (SubBlock block : metadataBlocks) {
                block.addToHashtable();
                if (!block.acquire) {
                    nonAcquiredBlocks.add(block);
                    blocks.remove(block);
                }
            }
            for (int i = 0; i < blocks.size(); i++) {
                SubBlock block = blocks.get(i);
                // a valid DataChannel or IlluminationChannel
                if ((block instanceof IlluminationChannel) && i < blocks.size() - 1) {
                    SubBlock nextBlock = blocks.get(i + 1);
                    if (!(nextBlock instanceof DataChannel) && !(nextBlock instanceof IlluminationChannel)) {
                        ((IlluminationChannel) block).wavelength = null;
                    }
                } else // a valid Track or DetectionChannel
                if ((block instanceof DetectionChannel) && i > 0) {
                    SubBlock prevBlock = blocks.get(i - 1);
                    if (!(prevBlock instanceof Track) && !(prevBlock instanceof DetectionChannel)) {
                        block.acquire = false;
                        nonAcquiredBlocks.add(block);
                    }
                }
                if (block.acquire)
                    populateMetadataStore(block, store, series);
            }
            for (SubBlock block : nonAcquiredBlocks) {
                populateMetadataStore(block, store, series);
            }
        }
        if (applicationTagOffset != 0) {
            in.seek(applicationTagOffset);
            parseApplicationTags();
        }
    }
    imageNames.add(imageName);
    if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
        if (userName != null) {
            String experimenterID = MetadataTools.createLSID("Experimenter", 0);
            store.setExperimenterID(experimenterID, 0);
            store.setExperimenterUserName(userName, 0);
        }
        Length pixX = FormatTools.getPhysicalSizeX(pixelSizeX);
        Length pixY = FormatTools.getPhysicalSizeY(pixelSizeY);
        Length pixZ = FormatTools.getPhysicalSizeZ(pixelSizeZ);
        if (pixX != null) {
            store.setPixelsPhysicalSizeX(pixX, series);
        }
        if (pixY != null) {
            store.setPixelsPhysicalSizeY(pixY, series);
        }
        if (pixZ != null) {
            store.setPixelsPhysicalSizeZ(pixZ, series);
        }
        for (int i = 0; i < getSizeC(); i++) {
            store.setChannelColor(channelColor[i], series, i);
            if (channelNames[series] != null) {
                store.setChannelName(channelNames[series][i], series, i);
            }
        }
        int stampIndex = 0;
        for (int i = 0; i < series; i++) {
            stampIndex += core.get(i).sizeT;
        }
        double firstStamp = 0;
        if (timestamps.size() > 0 && stampIndex < timestamps.size()) {
            firstStamp = timestamps.get(stampIndex).doubleValue();
        }
        for (int i = 0; i < getImageCount(); i++) {
            int[] zct = FormatTools.getZCTCoords(this, i);
            if (getSizeT() > 1 && zct[2] < timestamps.size() - stampIndex) {
                double thisStamp = timestamps.get(stampIndex + zct[2]).doubleValue();
                store.setPlaneDeltaT(new Time(thisStamp - firstStamp, UNITS.SECOND), series, i);
            }
            if (xCoordinates.size() > series) {
                final Double xCoord = xCoordinates.get(series);
                final Double yCoord = yCoordinates.get(series);
                final Double zCoord = zCoordinates.get(series);
                if (xCoord == null) {
                    store.setPlanePositionX(null, series, i);
                } else {
                    final Length x = new Length(xCoord, UNITS.REFERENCEFRAME);
                    store.setPlanePositionX(x, series, i);
                }
                if (yCoord == null) {
                    store.setPlanePositionY(null, series, i);
                } else {
                    final Length y = new Length(yCoord, UNITS.REFERENCEFRAME);
                    store.setPlanePositionY(y, series, i);
                }
                if (zCoord == null) {
                    store.setPlanePositionZ(null, series, i);
                } else {
                    final Length z = new Length(zCoord, UNITS.REFERENCEFRAME);
                    store.setPlanePositionZ(z, series, i);
                }
            }
        }
    }
    ras.close();
}
Also used : IFD(loci.formats.tiff.IFD) ArrayList(java.util.ArrayList) Time(ome.units.quantity.Time) Color(ome.xml.model.primitives.Color) PhotoInterp(loci.formats.tiff.PhotoInterp) CoreMetadata(loci.formats.CoreMetadata) MetadataStore(loci.formats.meta.MetadataStore) Length(ome.units.quantity.Length) IFDList(loci.formats.tiff.IFDList) TiffParser(loci.formats.tiff.TiffParser) RandomAccessInputStream(loci.common.RandomAccessInputStream)

Example 15 with Color

use of ome.xml.model.primitives.Color in project bioformats by openmicroscopy.

the class ZeissLSMReader method get16BitLookupTable.

/* @see loci.formats.IFormatReader#get16BitLookupTable() */
@Override
public short[][] get16BitLookupTable() throws FormatException, IOException {
    FormatTools.assertId(currentId, true, 1);
    if (lut == null || lut[getSeries()] == null || getPixelType() != FormatTools.UINT16 || channelColor == null) {
        return null;
    }
    short[][] s = new short[3][65536];
    Color color = channelColor[prevChannel];
    for (int j = 0; j < s[0].length; j++) {
        s[0][j] = (short) ((color.getRed() / 255.0) * j);
        s[1][j] = (short) ((color.getGreen() / 255.0) * j);
        s[2][j] = (short) ((color.getBlue() / 255.0) * j);
    }
    return s;
}
Also used : Color(ome.xml.model.primitives.Color)

Aggregations

Color (ome.xml.model.primitives.Color)19 ArrayList (java.util.ArrayList)8 CoreMetadata (loci.formats.CoreMetadata)8 MetadataStore (loci.formats.meta.MetadataStore)8 Length (ome.units.quantity.Length)8 FormatException (loci.formats.FormatException)7 Time (ome.units.quantity.Time)7 Location (loci.common.Location)6 RandomAccessInputStream (loci.common.RandomAccessInputStream)4 NonNegativeInteger (ome.xml.model.primitives.NonNegativeInteger)4 IFD (loci.formats.tiff.IFD)3 Timestamp (ome.xml.model.primitives.Timestamp)3 Element (org.w3c.dom.Element)3 IOException (java.io.IOException)2 Map (java.util.Map)2 DependencyException (loci.common.services.DependencyException)2 ServiceFactory (loci.common.services.ServiceFactory)2 TiffParser (loci.formats.tiff.TiffParser)2 Temperature (ome.units.quantity.Temperature)2 HDF5CompoundDataMap (ch.systemsx.cisd.hdf5.HDF5CompoundDataMap)1