Search in sources :

Example 16 with Color

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

the class FakeReader method initFile.

@Override
protected void initFile(String id) throws FormatException, IOException {
    if (!checkSuffix(id, "fake")) {
        if (checkSuffix(id, "fake.ini")) {
            id = id.substring(0, id.lastIndexOf("."));
        }
        Location file = new Location(id).getAbsoluteFile();
        if (!file.exists()) {
            Location dir = file.getParentFile();
            String[] list = dir.list(true);
            String name = file.getName();
            name = name.substring(0, name.lastIndexOf("."));
            for (String f : list) {
                if (checkSuffix(f, "fake") && f.startsWith(name)) {
                    id = new Location(dir, f).getAbsolutePath();
                    break;
                }
            }
        }
    }
    // Logic copied from deltavision. This should probably be refactored into
    // a helper method "replaceBySuffix" or something.
    super.initFile(id);
    findLogFiles();
    String path = id;
    Location location = new Location(id);
    String[] tokens = null;
    if (location.exists()) {
        path = location.getAbsoluteFile().getName();
        if (path.startsWith("Field")) {
            Location root = location.getAbsoluteFile().getParentFile();
            if (root != null) {
                root = root.getParentFile();
                if (root != null) {
                    root = root.getParentFile();
                    if (root != null) {
                        root = root.getParentFile();
                        if (isSPWStructure(root.getAbsolutePath())) {
                            tokens = extractTokensFromFakeSeries(root.getAbsolutePath());
                            // makes sure that getSeriesUsedFiles returns correctly
                            currentId = root.getAbsolutePath();
                        }
                    }
                }
            }
        }
    }
    if (location.isDirectory() && isSPWStructure(location.getAbsolutePath())) {
        tokens = extractTokensFromFakeSeries(location.getAbsolutePath());
    } else if (tokens == null) {
        String noExt = path.substring(0, path.lastIndexOf("."));
        tokens = noExt.split(TOKEN_SEPARATOR);
    }
    String name = null;
    // default
    int thumbSizeX = 0;
    // default
    int thumbSizeY = 0;
    int pixelType = DEFAULT_PIXEL_TYPE;
    // default
    int bitsPerPixel = 0;
    int rgb = DEFAULT_RGB_CHANNEL_COUNT;
    String dimOrder = DEFAULT_DIMENSION_ORDER;
    boolean orderCertain = true;
    boolean little = true;
    boolean interleaved = false;
    boolean indexed = false;
    boolean falseColor = false;
    boolean metadataComplete = true;
    boolean thumbnail = false;
    boolean withMicrobeam = false;
    int seriesCount = 1;
    int lutLength = 3;
    String acquisitionDate = null;
    int screens = 0;
    int plates = 0;
    int plateRows = 0;
    int plateCols = 0;
    int fields = 0;
    int plateAcqs = 0;
    Integer defaultColor = null;
    ArrayList<Integer> color = new ArrayList<Integer>();
    ArrayList<IniTable> seriesTables = new ArrayList<IniTable>();
    // add properties file values to list of tokens.
    if (iniFile != null) {
        IniParser parser = new IniParser();
        IniList list = parser.parseINI(new File(iniFile));
        List<String> newTokens = new ArrayList<String>();
        // Unclear what to do with other headers...
        IniTable table = list.getTable(IniTable.DEFAULT_HEADER);
        if (table != null) {
            for (Map.Entry<String, String> entry : table.entrySet()) {
                newTokens.add(entry.getKey() + "=" + entry.getValue());
            }
        }
        table = list.getTable("GlobalMetadata");
        if (table != null) {
            for (Map.Entry<String, String> entry : table.entrySet()) {
                addGlobalMeta(entry.getKey(), entry.getValue());
            }
        }
        String[] newTokArr = newTokens.toArray(new String[0]);
        String[] oldTokArr = tokens;
        tokens = new String[newTokArr.length + oldTokArr.length];
        System.arraycopy(oldTokArr, 0, tokens, 0, oldTokArr.length);
        System.arraycopy(newTokArr, 0, tokens, oldTokArr.length, newTokArr.length);
        // Properties overrides file name values
        int seriesIndex = 0;
        while (list.getTable("series_" + seriesIndex) != null) {
            seriesTables.add(list.getTable("series_" + seriesIndex));
            seriesIndex++;
        }
    }
    // parse tokens from filename
    for (String token : tokens) {
        if (name == null) {
            // first token is the image name
            name = token;
            continue;
        }
        int equals = token.indexOf('=');
        if (equals < 0) {
            LOGGER.warn("ignoring token: {}", token);
            continue;
        }
        String key = token.substring(0, equals);
        String value = token.substring(equals + 1);
        boolean boolValue = value.equals("true");
        double doubleValue;
        try {
            doubleValue = Double.parseDouble(value);
        } catch (NumberFormatException exc) {
            doubleValue = Double.NaN;
        }
        int intValue = Double.isNaN(doubleValue) ? -1 : (int) doubleValue;
        if (key.equals("sizeX"))
            sizeX = intValue;
        else if (key.equals("sizeY"))
            sizeY = intValue;
        else if (key.equals("sizeZ"))
            sizeZ = intValue;
        else if (key.equals("sizeC"))
            sizeC = intValue;
        else if (key.equals("sizeT"))
            sizeT = intValue;
        else if (key.equals("thumbSizeX"))
            thumbSizeX = intValue;
        else if (key.equals("thumbSizeY"))
            thumbSizeY = intValue;
        else if (key.equals("pixelType")) {
            pixelType = FormatTools.pixelTypeFromString(value);
        } else if (key.equals("bitsPerPixel"))
            bitsPerPixel = intValue;
        else if (key.equals("rgb"))
            rgb = intValue;
        else if (key.equals("dimOrder"))
            dimOrder = value.toUpperCase();
        else if (key.equals("orderCertain"))
            orderCertain = boolValue;
        else if (key.equals("little"))
            little = boolValue;
        else if (key.equals("interleaved"))
            interleaved = boolValue;
        else if (key.equals("indexed"))
            indexed = boolValue;
        else if (key.equals("falseColor"))
            falseColor = boolValue;
        else if (key.equals("metadataComplete"))
            metadataComplete = boolValue;
        else if (key.equals("thumbnail"))
            thumbnail = boolValue;
        else if (key.equals("series"))
            seriesCount = intValue;
        else if (key.equals("lutLength"))
            lutLength = intValue;
        else if (key.equals("scaleFactor"))
            scaleFactor = doubleValue;
        else if (key.equals("exposureTime"))
            exposureTime = new Time((float) doubleValue, UNITS.SECOND);
        else if (key.equals("acquisitionDate"))
            acquisitionDate = value;
        else if (key.equals("screens"))
            screens = intValue;
        else if (key.equals("plates"))
            plates = intValue;
        else if (key.equals("plateRows"))
            plateRows = intValue;
        else if (key.equals("plateCols"))
            plateCols = intValue;
        else if (key.equals("fields"))
            fields = intValue;
        else if (key.equals("plateAcqs"))
            plateAcqs = intValue;
        else if (key.equals("withMicrobeam"))
            withMicrobeam = boolValue;
        else if (key.equals("annLong"))
            annLong = intValue;
        else if (key.equals("annDouble"))
            annDouble = intValue;
        else if (key.equals("annMap"))
            annMap = intValue;
        else if (key.equals("annComment"))
            annComment = intValue;
        else if (key.equals("annBool"))
            annBool = intValue;
        else if (key.equals("annTime"))
            annTime = intValue;
        else if (key.equals("annTag"))
            annTag = intValue;
        else if (key.equals("annTerm"))
            annTerm = intValue;
        else if (key.equals("annXml"))
            annXml = intValue;
        else if (key.equals("ellipses"))
            ellipses = intValue;
        else if (key.equals("labels"))
            labels = intValue;
        else if (key.equals("lines"))
            lines = intValue;
        else if (key.equals("masks"))
            masks = intValue;
        else if (key.equals("points"))
            points = intValue;
        else if (key.equals("polygons"))
            polygons = intValue;
        else if (key.equals("polylines"))
            polylines = intValue;
        else if (key.equals("rectangles"))
            rectangles = intValue;
        else if (key.equals("physicalSizeX"))
            physicalSizeX = parseLength(value, getPhysicalSizeXUnitXsdDefault());
        else if (key.equals("physicalSizeY"))
            physicalSizeY = parseLength(value, getPhysicalSizeYUnitXsdDefault());
        else if (key.equals("physicalSizeZ"))
            physicalSizeZ = parseLength(value, getPhysicalSizeZUnitXsdDefault());
        else if (key.equals("color")) {
            defaultColor = parseColor(value);
        } else if (key.startsWith("color_")) {
            // 'color' and 'color_x' can be used together, but 'color_x' takes
            // precedence.  'color' will in that case be used for any missing
            // or invalid 'color_x' values.
            int index = Integer.parseInt(key.substring(key.indexOf('_') + 1));
            while (index >= color.size()) {
                color.add(null);
            }
            color.set(index, parseColor(value));
        }
    }
    // do some sanity checks
    if (sizeX < 1)
        throw new FormatException("Invalid sizeX: " + sizeX);
    if (sizeY < 1)
        throw new FormatException("Invalid sizeY: " + sizeY);
    if (sizeZ < 1)
        throw new FormatException("Invalid sizeZ: " + sizeZ);
    if (sizeC < 1)
        throw new FormatException("Invalid sizeC: " + sizeC);
    if (sizeT < 1)
        throw new FormatException("Invalid sizeT: " + sizeT);
    if (thumbSizeX < 0) {
        throw new FormatException("Invalid thumbSizeX: " + thumbSizeX);
    }
    if (thumbSizeY < 0) {
        throw new FormatException("Invalid thumbSizeY: " + thumbSizeY);
    }
    if (rgb < 1 || rgb > sizeC || sizeC % rgb != 0) {
        throw new FormatException("Invalid sizeC/rgb combination: " + sizeC + "/" + rgb);
    }
    getDimensionOrder(dimOrder);
    if (falseColor && !indexed) {
        throw new FormatException("False color images must be indexed");
    }
    if (seriesCount < 1) {
        throw new FormatException("Invalid seriesCount: " + seriesCount);
    }
    if (lutLength < 1) {
        throw new FormatException("Invalid lutLength: " + lutLength);
    }
    // populate SPW metadata
    MetadataStore store = makeFilterMetadata();
    boolean hasSPW = screens > 0 || plates > 0 || plateRows > 0 || plateCols > 0 || fields > 0 || plateAcqs > 0;
    if (hasSPW) {
        if (screens < 0)
            screens = 0;
        if (plates <= 0)
            plates = 1;
        if (plateRows <= 0)
            plateRows = 1;
        if (plateCols <= 0)
            plateCols = 1;
        if (fields <= 0)
            fields = 1;
        if (plateAcqs <= 0)
            plateAcqs = 1;
        // generate SPW metadata and override series count to match
        int imageCount = populateSPW(store, screens, plates, plateRows, plateCols, fields, plateAcqs, withMicrobeam);
        if (imageCount > 0)
            seriesCount = imageCount;
        else
            // failed to generate SPW metadata
            hasSPW = false;
    }
    // populate core metadata
    int effSizeC = sizeC / rgb;
    core.clear();
    for (int s = 0; s < seriesCount; s++) {
        CoreMetadata ms = new CoreMetadata();
        core.add(ms);
        ms.sizeX = sizeX;
        ms.sizeY = sizeY;
        ms.sizeZ = sizeZ;
        ms.sizeC = sizeC;
        ms.sizeT = sizeT;
        ms.thumbSizeX = thumbSizeX;
        ms.thumbSizeY = thumbSizeY;
        ms.pixelType = pixelType;
        ms.bitsPerPixel = bitsPerPixel;
        ms.imageCount = sizeZ * effSizeC * sizeT;
        ms.rgb = rgb > 1;
        ms.dimensionOrder = dimOrder;
        ms.orderCertain = orderCertain;
        ms.littleEndian = little;
        ms.interleaved = interleaved;
        ms.indexed = indexed;
        ms.falseColor = falseColor;
        ms.metadataComplete = metadataComplete;
        ms.thumbnail = thumbnail;
    }
    // populate OME metadata
    boolean planeInfo = (exposureTime != null) || seriesTables.size() > 0;
    MetadataTools.populatePixels(store, this, planeInfo);
    fillExposureTime(store);
    fillPhysicalSizes(store);
    for (int currentImageIndex = 0; currentImageIndex < seriesCount; currentImageIndex++) {
        if (currentImageIndex < seriesTables.size()) {
            parseSeriesTable(seriesTables.get(currentImageIndex), store, currentImageIndex);
        }
        String imageName = currentImageIndex > 0 ? name + " " + (currentImageIndex + 1) : name;
        store.setImageName(imageName, currentImageIndex);
        fillAcquisitionDate(store, acquisitionDate, currentImageIndex);
        for (int c = 0; c < getEffectiveSizeC(); c++) {
            Color channel = defaultColor == null ? null : new Color(defaultColor);
            if (c < color.size() && color.get(c) != null) {
                channel = new Color(color.get(c));
            }
            if (channel != null) {
                store.setChannelColor(channel, currentImageIndex, c);
            }
        }
        fillAnnotations(store, currentImageIndex);
        fillRegions(store, currentImageIndex);
    }
    // for indexed color images, create lookup tables
    if (indexed) {
        if (pixelType == FormatTools.UINT8) {
            // create 8-bit LUTs
            final int num = 256;
            createIndexMap(num);
            lut8 = new byte[sizeC][lutLength][num];
            // linear ramp
            for (int c = 0; c < sizeC; c++) {
                for (int i = 0; i < lutLength; i++) {
                    for (int index = 0; index < num; index++) {
                        lut8[c][i][index] = (byte) indexToValue[c][index];
                    }
                }
            }
        } else if (pixelType == FormatTools.UINT16) {
            // create 16-bit LUTs
            final int num = 65536;
            createIndexMap(num);
            lut16 = new short[sizeC][lutLength][num];
            // linear ramp
            for (int c = 0; c < sizeC; c++) {
                for (int i = 0; i < lutLength; i++) {
                    for (int index = 0; index < num; index++) {
                        lut16[c][i][index] = (short) indexToValue[c][index];
                    }
                }
            }
        }
    // NB: Other pixel types will have null LUTs.
    }
}
Also used : IniParser(loci.common.IniParser) IniList(loci.common.IniList) Color(ome.xml.model.primitives.Color) ArrayList(java.util.ArrayList) Time(ome.units.quantity.Time) CoreMetadata(loci.formats.CoreMetadata) FormatException(loci.formats.FormatException) MetadataStore(loci.formats.meta.MetadataStore) IniTable(loci.common.IniTable) File(java.io.File) Map(java.util.Map) Location(loci.common.Location)

Example 17 with Color

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

the class LIFReader method initMetadata.

// -- Helper methods --
/**
 * Parses a string of XML and puts the values in a Hashtable.
 */
private void initMetadata(String xml) throws FormatException, IOException {
    try {
        ServiceFactory factory = new ServiceFactory();
        OMEXMLService service = factory.getInstance(OMEXMLService.class);
        service.createOMEXMLMetadata();
    } catch (DependencyException exc) {
        throw new FormatException("Could not create OME-XML store.", exc);
    } catch (ServiceException exc) {
        throw new FormatException("Could not create OME-XML store.", exc);
    }
    MetadataStore store = makeFilterMetadata();
    // the XML blocks stored in a LIF file are invalid,
    // because they don't have a root node
    xml = "<?xml version=\"1.0\" encoding=\"" + ENCODING + "\"?><LEICA>" + xml + "</LEICA>";
    xml = XMLTools.sanitizeXML(xml);
    LOGGER.trace(xml);
    translateMetadata(getMetadataRoot(xml));
    for (int i = 0; i < imageNames.length; i++) {
        setSeries(i);
        addSeriesMeta("Image name", imageNames[i]);
    }
    setSeries(0);
    // set up mapping to rearrange channels
    // for instance, the green channel may be #0, and the red channel may be #1
    realChannel = new int[tileCount.length][];
    int nextLut = 0;
    for (int i = 0; i < core.size(); i++) {
        int index = getTileIndex(i);
        if (realChannel[index] != null) {
            continue;
        }
        CoreMetadata ms = core.get(i);
        realChannel[index] = new int[ms.sizeC];
        for (int q = 0; q < ms.sizeC; q++) {
            String lut = "";
            if (nextLut < lutNames.size()) {
                lut = lutNames.get(nextLut++).toLowerCase();
            }
            if (!CHANNEL_PRIORITIES.containsKey(lut))
                lut = "";
            realChannel[index][q] = CHANNEL_PRIORITIES.get(lut).intValue();
        }
        int[] sorted = new int[ms.sizeC];
        Arrays.fill(sorted, -1);
        for (int q = 0; q < sorted.length; q++) {
            int min = Integer.MAX_VALUE;
            int minIndex = -1;
            for (int n = 0; n < ms.sizeC; n++) {
                if (realChannel[index][n] < min && !DataTools.containsValue(sorted, n)) {
                    min = realChannel[index][n];
                    minIndex = n;
                }
            }
            sorted[q] = minIndex;
        }
    }
    MetadataTools.populatePixels(store, this, true, false);
    int roiCount = 0;
    for (int i = 0; i < getSeriesCount(); i++) {
        setSeries(i);
        String instrumentID = MetadataTools.createLSID("Instrument", i);
        store.setInstrumentID(instrumentID, i);
        int index = getTileIndex(i);
        store.setMicroscopeModel(microscopeModels[index], i);
        store.setMicroscopeType(getMicroscopeType("Other"), i);
        String objectiveID = MetadataTools.createLSID("Objective", i, 0);
        store.setObjectiveID(objectiveID, i, 0);
        store.setObjectiveLensNA(lensNA[index], i, 0);
        store.setObjectiveSerialNumber(serialNumber[index], i, 0);
        if (magnification[index] != null) {
            store.setObjectiveNominalMagnification(magnification[index], i, 0);
        }
        store.setObjectiveImmersion(getImmersion(immersions[index]), i, 0);
        store.setObjectiveCorrection(getCorrection(corrections[index]), i, 0);
        store.setObjectiveModel(objectiveModels[index], i, 0);
        if (cutIns[index] != null && filterModels[index] != null) {
            int channel = 0;
            if (cutIns[index].size() >= filterModels[index].size() * 2) {
                int diff = cutIns[index].size() - filterModels[index].size();
                for (int q = 0; q < diff; q++) {
                    cutIns[index].remove(filterModels[index].size());
                }
            }
            for (int filter = 0; filter < cutIns[index].size(); filter++) {
                String filterID = MetadataTools.createLSID("Filter", i, filter);
                store.setFilterID(filterID, i, filter);
                if (filterModels[index] != null && filter < filterModels[index].size()) {
                    store.setFilterModel((String) filterModels[index].get(filter), i, filter);
                }
                store.setTransmittanceRangeCutIn((Length) cutIns[index].get(filter), i, filter);
                store.setTransmittanceRangeCutOut((Length) cutOuts[index].get(filter), i, filter);
            }
        }
        final List<Double> lasers = laserWavelength[index];
        final List<Double> laserIntensities = laserIntensity[index];
        final List<Boolean> active = laserActive[index];
        final List<Boolean> frap = laserFrap[index];
        int nextChannel = 0;
        if (lasers != null) {
            int laserIndex = 0;
            while (laserIndex < lasers.size()) {
                if ((Double) lasers.get(laserIndex) == 0) {
                    lasers.remove(laserIndex);
                } else {
                    laserIndex++;
                }
            }
            for (int laser = 0; laser < lasers.size(); laser++) {
                String id = MetadataTools.createLSID("LightSource", i, laser);
                store.setLaserID(id, i, laser);
                store.setLaserType(LaserType.OTHER, i, laser);
                store.setLaserLaserMedium(LaserMedium.OTHER, i, laser);
                Double wavelength = (Double) lasers.get(laser);
                Length wave = FormatTools.getWavelength(wavelength);
                if (wave != null) {
                    store.setLaserWavelength(wave, i, laser);
                }
            }
            Set<Integer> ignoredChannels = new HashSet<Integer>();
            final List<Integer> validIntensities = new ArrayList<Integer>();
            int size = lasers.size();
            int channel = 0;
            Set<Integer> channels = new HashSet<Integer>();
            for (int laser = 0; laser < laserIntensities.size(); laser++) {
                double intensity = (Double) laserIntensities.get(laser);
                channel = laser / size;
                if (intensity < 100) {
                    validIntensities.add(laser);
                    channels.add(channel);
                }
                ignoredChannels.add(channel);
            }
            // remove channels w/o valid intensities
            ignoredChannels.removeAll(channels);
            // remove entries if channel has 2 wavelengths
            // e.g. 30% 458 70% 633
            int s = validIntensities.size();
            int jj;
            Set<Integer> toRemove = new HashSet<Integer>();
            int as = active.size();
            for (int j = 0; j < s; j++) {
                if (j < as && !(Boolean) active.get(j)) {
                    toRemove.add(validIntensities.get(j));
                }
                jj = j + 1;
                if (jj < s) {
                    int v = validIntensities.get(j) / size;
                    int vv = validIntensities.get(jj) / size;
                    if (vv == v) {
                        // do not consider that channel.
                        toRemove.add(validIntensities.get(j));
                        toRemove.add(validIntensities.get(jj));
                        ignoredChannels.add(j);
                    }
                }
            }
            if (toRemove.size() > 0) {
                validIntensities.removeAll(toRemove);
            }
            boolean noNames = true;
            if (channelNames[index] != null) {
                for (String name : channelNames[index]) {
                    if (name != null && !name.equals("")) {
                        noNames = false;
                        break;
                    }
                }
            }
            if (!noNames && frap != null) {
                // only use name for frap.
                for (int k = 0; k < frap.size(); k++) {
                    if (!frap.get(k)) {
                        noNames = true;
                        break;
                    }
                }
            }
            int nextFilter = 0;
            // int nextFilter = cutIns[i].size() - getEffectiveSizeC();
            for (int k = 0; k < validIntensities.size(); k++, nextChannel++) {
                int laserArrayIndex = validIntensities.get(k);
                double intensity = (Double) laserIntensities.get(laserArrayIndex);
                int laser = laserArrayIndex % lasers.size();
                Double wavelength = (Double) lasers.get(laser);
                if (wavelength != 0) {
                    while (ignoredChannels.contains(nextChannel)) {
                        nextChannel++;
                    }
                    while (channelNames != null && nextChannel < getEffectiveSizeC() && channelNames[index] != null && ((channelNames[index][nextChannel] == null || channelNames[index][nextChannel].equals("")) && !noNames)) {
                        nextChannel++;
                    }
                    if (nextChannel < getEffectiveSizeC()) {
                        String id = MetadataTools.createLSID("LightSource", i, laser);
                        store.setChannelLightSourceSettingsID(id, i, nextChannel);
                        store.setChannelLightSourceSettingsAttenuation(new PercentFraction((float) intensity / 100f), i, nextChannel);
                        Length ex = FormatTools.getExcitationWavelength(wavelength);
                        if (ex != null) {
                            store.setChannelExcitationWavelength(ex, i, nextChannel);
                        }
                        if (wavelength > 0) {
                            if (cutIns[index] == null || nextFilter >= cutIns[index].size()) {
                                continue;
                            }
                            Double cutIn = ((Length) cutIns[index].get(nextFilter)).value(UNITS.NANOMETER).doubleValue();
                            while (cutIn - wavelength > 20) {
                                nextFilter++;
                                if (nextFilter < cutIns[index].size()) {
                                    cutIn = ((Length) cutIns[index].get(nextFilter)).value(UNITS.NANOMETER).doubleValue();
                                } else {
                                    break;
                                }
                            }
                            if (nextFilter < cutIns[index].size()) {
                                String fid = MetadataTools.createLSID("Filter", i, nextFilter);
                                // store.setLightPathEmissionFilterRef(fid, i, nextChannel, 0);
                                nextFilter++;
                            }
                        }
                    }
                }
            }
        }
        store.setImageInstrumentRef(instrumentID, i);
        store.setObjectiveSettingsID(objectiveID, i);
        store.setObjectiveSettingsRefractiveIndex(refractiveIndex[index], i);
        store.setImageDescription(descriptions[index], i);
        if (acquiredDate[index] > 0) {
            store.setImageAcquisitionDate(new Timestamp(DateTools.convertDate((long) (acquiredDate[index] * 1000), DateTools.COBOL, DateTools.ISO8601_FORMAT, false)), i);
        }
        store.setImageName(imageNames[index].trim(), i);
        Length sizeX = FormatTools.getPhysicalSizeX(physicalSizeXs.get(index));
        Length sizeY = FormatTools.getPhysicalSizeY(physicalSizeYs.get(index));
        Length sizeZ = FormatTools.getPhysicalSizeZ(zSteps[index]);
        if (sizeX != null) {
            store.setPixelsPhysicalSizeX(sizeX, i);
        }
        if (sizeY != null) {
            store.setPixelsPhysicalSizeY(sizeY, i);
        }
        if (sizeZ != null) {
            store.setPixelsPhysicalSizeZ(sizeZ, i);
        }
        if (tSteps[index] != null) {
            store.setPixelsTimeIncrement(new Time(tSteps[index], UNITS.SECOND), i);
        }
        final List<String> detectors = detectorModels[index];
        if (detectors != null) {
            nextChannel = 0;
            int start = detectors.size() - getEffectiveSizeC();
            if (start < 0) {
                start = 0;
            }
            for (int detector = start; detector < detectors.size(); detector++) {
                int dIndex = detector - start;
                String detectorID = MetadataTools.createLSID("Detector", i, dIndex);
                store.setDetectorID(detectorID, i, dIndex);
                store.setDetectorModel((String) detectors.get(detector), i, dIndex);
                store.setDetectorZoom(zooms[index], i, dIndex);
                store.setDetectorType(DetectorType.PMT, i, dIndex);
                if (activeDetector[index] != null) {
                    int detectorIndex = activeDetector[index].size() - getEffectiveSizeC() + dIndex;
                    if (detectorIndex >= 0 && detectorIndex < activeDetector[index].size() && (Boolean) activeDetector[index].get(detectorIndex) && detectorOffsets[index] != null && nextChannel < detectorOffsets[index].length) {
                        store.setDetectorOffset(detectorOffsets[index][nextChannel++], i, dIndex);
                    }
                }
            }
        }
        final List<Boolean> activeDetectors = activeDetector[index];
        int firstDetector = activeDetectors == null ? 0 : activeDetectors.size() - getEffectiveSizeC();
        int nextDetector = firstDetector;
        int nextFilter = 0;
        int nextFilterDetector = 0;
        if (activeDetectors != null && activeDetectors.size() > cutIns[index].size() && (Boolean) activeDetectors.get(activeDetectors.size() - 1) && (Boolean) activeDetectors.get(activeDetectors.size() - 2)) {
            nextFilterDetector = activeDetectors.size() - cutIns[index].size();
            if (cutIns[index].size() > filterModels[index].size()) {
                nextFilterDetector += filterModels[index].size();
                nextFilter += filterModels[index].size();
            }
        }
        for (int c = 0; c < getEffectiveSizeC(); c++) {
            if (activeDetectors != null) {
                while (nextDetector >= 0 && nextDetector < activeDetectors.size() && !(Boolean) activeDetectors.get(nextDetector)) {
                    nextDetector++;
                }
                if (nextDetector < activeDetectors.size() && detectors != null && nextDetector - firstDetector < detectors.size()) {
                    String detectorID = MetadataTools.createLSID("Detector", i, nextDetector - firstDetector);
                    store.setDetectorSettingsID(detectorID, i, c);
                    nextDetector++;
                    if (detectorOffsets[index] != null && c < detectorOffsets[index].length) {
                        store.setDetectorSettingsOffset(detectorOffsets[index][c], i, c);
                    }
                    if (gains[index] != null) {
                        store.setDetectorSettingsGain(gains[index][c], i, c);
                    }
                }
            }
            if (channelNames[index] != null) {
                store.setChannelName(channelNames[index][c], i, c);
            }
            if (pinholes[index] != null) {
                store.setChannelPinholeSize(new Length(pinholes[index], UNITS.MICROMETER), i, c);
            }
            if (exWaves[index] != null) {
                if (exWaves[index][c] != null && exWaves[index][c] > 1) {
                    Length ex = FormatTools.getExcitationWavelength(exWaves[index][c]);
                    if (ex != null) {
                        store.setChannelExcitationWavelength(ex, i, c);
                    }
                }
            }
            // channel coloring is implicit if the image is stored as RGB
            Color channelColor = getChannelColor(realChannel[index][c]);
            if (!isRGB()) {
                store.setChannelColor(channelColor, i, c);
            }
            if (channelColor.getValue() != -1 && nextFilter >= 0) {
                if (nextDetector - firstDetector != getSizeC() && cutIns[index] != null && nextDetector >= cutIns[index].size()) {
                    while (nextFilterDetector < firstDetector) {
                        String filterID = MetadataTools.createLSID("Filter", i, nextFilter);
                        store.setFilterID(filterID, i, nextFilter);
                        nextFilterDetector++;
                        nextFilter++;
                    }
                }
                while (activeDetectors != null && nextFilterDetector < activeDetectors.size() && !(Boolean) activeDetectors.get(nextFilterDetector)) {
                    String filterID = MetadataTools.createLSID("Filter", i, nextFilter);
                    store.setFilterID(filterID, i, nextFilter);
                    nextFilterDetector++;
                    nextFilter++;
                }
                String filterID = MetadataTools.createLSID("Filter", i, nextFilter);
                store.setFilterID(filterID, i, nextFilter);
                store.setLightPathEmissionFilterRef(filterID, i, c, 0);
                nextFilterDetector++;
                nextFilter++;
            }
        }
        for (int image = 0; image < getImageCount(); image++) {
            Length xPos = posX[index];
            Length yPos = posY[index];
            if (i < fieldPosX.size() && fieldPosX.get(i) != null) {
                xPos = fieldPosX.get(i);
            }
            if (i < fieldPosY.size() && fieldPosY.get(i) != null) {
                yPos = fieldPosY.get(i);
            }
            if (xPos != null) {
                store.setPlanePositionX(xPos, i, image);
            }
            if (yPos != null) {
                store.setPlanePositionY(yPos, i, image);
            }
            store.setPlanePositionZ(posZ[index], i, image);
            if (timestamps[index] != null) {
                if (timestamps[index][image] != null) {
                    double timestamp = timestamps[index][image];
                    if (timestamps[index][0] == acquiredDate[index]) {
                        timestamp -= acquiredDate[index];
                    } else if (timestamp == acquiredDate[index] && image > 0) {
                        timestamp = timestamps[index][0];
                    }
                    store.setPlaneDeltaT(new Time(timestamp, UNITS.SECOND), i, image);
                }
            }
            if (expTimes[index] != null) {
                int c = getZCTCoords(image)[1];
                if (expTimes[index][c] != null) {
                    store.setPlaneExposureTime(new Time(expTimes[index][c], UNITS.SECOND), i, image);
                }
            }
        }
        if (imageROIs[index] != null) {
            for (int roi = 0; roi < imageROIs[index].length; roi++) {
                if (imageROIs[index][roi] != null) {
                    imageROIs[index][roi].storeROI(store, i, roiCount++, roi);
                }
            }
        }
    }
}
Also used : ServiceFactory(loci.common.services.ServiceFactory) ArrayList(java.util.ArrayList) Time(ome.units.quantity.Time) Timestamp(ome.xml.model.primitives.Timestamp) OMEXMLService(loci.formats.services.OMEXMLService) HashSet(java.util.HashSet) Color(ome.xml.model.primitives.Color) 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) PercentFraction(ome.xml.model.primitives.PercentFraction)

Example 18 with Color

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

the class IMODReader 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);
    String check = in.readString(8);
    if (!check.equals(MAGIC_STRING)) {
        throw new FormatException("Invalid file ID: " + check);
    }
    CoreMetadata m = core.get(0);
    String filename = in.readString(128);
    m.sizeX = in.readInt();
    m.sizeY = in.readInt();
    m.sizeZ = in.readInt();
    int nObjects = in.readInt();
    points = new float[nObjects][][][];
    colors = new byte[nObjects][3];
    int flags = in.readInt();
    int drawMode = in.readInt();
    int mouseMode = in.readInt();
    int blackLevel = in.readInt();
    int whiteLevel = in.readInt();
    float xOffset = in.readFloat();
    float yOffset = in.readFloat();
    float zOffset = in.readFloat();
    float xScale = in.readFloat();
    float yScale = in.readFloat();
    float zScale = in.readFloat();
    int currentObject = in.readInt();
    int currentContour = in.readInt();
    int currentPoint = in.readInt();
    int res = in.readInt();
    int thresh = in.readInt();
    float pixSize = in.readFloat();
    int pixSizeUnits = in.readInt();
    int checksum = in.readInt();
    float alpha = in.readFloat();
    float beta = in.readFloat();
    float gamma = in.readFloat();
    addGlobalMeta("Model name", filename);
    addGlobalMeta("Model flags", flags);
    addGlobalMeta("Model drawing mode", drawMode);
    addGlobalMeta("Mouse mode", mouseMode);
    addGlobalMeta("Black level", blackLevel);
    addGlobalMeta("White level", whiteLevel);
    addGlobalMeta("X offset", xOffset);
    addGlobalMeta("Y offset", yOffset);
    addGlobalMeta("Z offset", zOffset);
    addGlobalMeta("X scale", xScale);
    addGlobalMeta("Y scale", yScale);
    addGlobalMeta("Z scale", zScale);
    addGlobalMeta("Alpha", alpha);
    addGlobalMeta("Beta", beta);
    addGlobalMeta("Gamma", gamma);
    MetadataStore store = makeFilterMetadata();
    ArrayList<String> roiIDs = new ArrayList<String>();
    for (int obj = 0; obj < nObjects; obj++) {
        String objt = in.readString(4);
        while (!objt.equals("OBJT") && in.getFilePointer() < in.length()) {
            String prefix = "Object #" + obj + " ";
            if (objt.equals("IMAT")) {
                addGlobalMeta(prefix + "ambient", in.read());
                addGlobalMeta(prefix + "diffuse", in.read());
                addGlobalMeta(prefix + "specular", in.read());
                addGlobalMeta(prefix + "shininess", in.read());
                addGlobalMeta(prefix + "fill red", in.read());
                addGlobalMeta(prefix + "fill green", in.read());
                addGlobalMeta(prefix + "fill blue", in.read());
                addGlobalMeta(prefix + "sphere quality", in.read());
                in.skipBytes(4);
                addGlobalMeta(prefix + "black level", in.read());
                addGlobalMeta(prefix + "white level", in.read());
                in.skipBytes(2);
            }
            objt = in.readString(4);
        }
        if (!objt.equals("OBJT")) {
            break;
        }
        String objName = in.readString(64);
        // unused
        in.skipBytes(64);
        int nContours = in.readInt();
        points[obj] = new float[nContours][][];
        int objFlags = in.readInt();
        int axis = in.readInt();
        int objDrawMode = in.readInt();
        float red = in.readFloat();
        float green = in.readFloat();
        float blue = in.readFloat();
        colors[obj][0] = (byte) (red * 255);
        colors[obj][1] = (byte) (green * 255);
        colors[obj][2] = (byte) (blue * 255);
        int pixelRadius = in.readInt();
        int pixelSymbol = in.read();
        int symbolSize = in.read();
        int lineWidth2D = in.read();
        int lineWidth3D = in.read();
        int lineStyle = in.read();
        int symbolFlags = in.read();
        int symbolPadding = in.read();
        int transparency = in.read();
        int nMeshes = in.readInt();
        int nSurfaces = in.readInt();
        if (getMetadataOptions().getMetadataLevel() == MetadataLevel.ALL) {
            String roiID = MetadataTools.createLSID("ROI", obj);
            store.setROIID(roiID, obj);
            store.setROIName(objName, obj);
            roiIDs.add(roiID);
        }
        int nextShape = 0;
        for (int contour = 0; contour < nContours; contour++) {
            // CONT
            in.skipBytes(4);
            int nPoints = in.readInt();
            int contourFlags = in.readInt();
            int timeIndex = in.readInt();
            int surface = in.readInt();
            if (nPoints > in.length() || nPoints < 0) {
                while (!"CONT".equals(in.readString(4))) {
                    in.seek(in.getFilePointer() - 8);
                }
                nPoints = in.readInt();
                contourFlags = in.readInt();
                timeIndex = in.readInt();
                surface = in.readInt();
            }
            points[obj][contour] = new float[nPoints][3];
            for (int p = 0; p < nPoints; p++) {
                for (int i = 0; i < points[obj][contour][p].length; i++) {
                    points[obj][contour][p][i] = in.readFloat();
                }
            }
            if (getMetadataOptions().getMetadataLevel() == MetadataLevel.ALL) {
                boolean wild = (contourFlags & 0x10) == 0x10;
                Length l;
                if (wild) {
                    int r = colors[obj][0] & 0xff;
                    int g = colors[obj][1] & 0xff;
                    int b = colors[obj][2] & 0xff;
                    for (int i = 0; i < nPoints; i++) {
                        String shapeID = MetadataTools.createLSID("Shape", obj, nextShape);
                        store.setPointID(shapeID, obj, nextShape);
                        store.setPointStrokeColor(new Color(r, g, b, 0xff), obj, nextShape);
                        l = new Length(new Double(lineWidth2D), UNITS.PIXEL);
                        store.setPointStrokeWidth(l, obj, nextShape);
                        if (lineStyle == 1) {
                            store.setPointStrokeDashArray("5", obj, nextShape);
                        }
                        store.setPointX(new Double(points[obj][contour][i][0]), obj, nextShape);
                        store.setPointY(new Double(points[obj][contour][i][1]), obj, nextShape);
                        if (points[obj][contour][i][2] >= 0) {
                            store.setPointTheZ(new NonNegativeInteger((int) points[obj][contour][i][2]), obj, nextShape);
                        }
                        nextShape++;
                    }
                } else {
                    String shapeID = MetadataTools.createLSID("Shape", obj, nextShape);
                    boolean closed = (contourFlags & 0x8) == 0;
                    int r = colors[obj][0] & 0xff;
                    int g = colors[obj][1] & 0xff;
                    int b = colors[obj][2] & 0xff;
                    final StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < nPoints; i++) {
                        sb.append(points[obj][contour][i][0]);
                        sb.append(",");
                        sb.append(points[obj][contour][i][1]);
                        if (i < nPoints - 1) {
                            sb.append(" ");
                        }
                    }
                    if (closed) {
                        store.setPolygonID(shapeID, obj, nextShape);
                        store.setPolygonStrokeColor(new Color(r, g, b, 0xff), obj, nextShape);
                        l = new Length(new Double(lineWidth2D), UNITS.PIXEL);
                        store.setPolygonStrokeWidth(l, obj, nextShape);
                        if (lineStyle == 1) {
                            store.setPolygonStrokeDashArray("5", obj, nextShape);
                        }
                        if (nPoints > 0 && points[obj][contour][0][2] >= 0) {
                            store.setPolygonTheZ(new NonNegativeInteger((int) points[obj][contour][0][2]), obj, nextShape);
                        }
                        store.setPolygonPoints(sb.toString(), obj, nextShape);
                    } else {
                        store.setPolylineID(shapeID, obj, nextShape);
                        store.setPolylineStrokeColor(new Color(r, g, b, 0xff), obj, nextShape);
                        l = new Length(new Double(lineWidth2D), UNITS.PIXEL);
                        store.setPolylineStrokeWidth(l, obj, nextShape);
                        if (lineStyle == 1) {
                            store.setPolylineStrokeDashArray("5", obj, nextShape);
                        }
                        if (nPoints > 0 && points[obj][contour][0][2] >= 0) {
                            store.setPolylineTheZ(new NonNegativeInteger((int) points[obj][contour][0][2]), obj, nextShape);
                        }
                        store.setPolylinePoints(sb.toString(), obj, nextShape);
                    }
                    nextShape++;
                }
            }
        }
        for (int mesh = 0; mesh < nMeshes; mesh++) {
            // MESH
            in.skipBytes(4);
            int vsize = in.readInt();
            int lsize = in.readInt();
            int meshFlags = in.readInt();
            int timeIndex = in.readShort();
            int surface = in.readShort();
            // TODO
            in.skipBytes(12 * vsize + 4 * lsize);
        }
    }
    double physicalX = 0d, physicalY = 0d, physicalZ = 0d;
    while (in.getFilePointer() + 4 < in.length()) {
        // check if there is any extra metadata at the end of the file
        String chunkType = in.readString(4);
        if (chunkType.equals("IMAT")) {
            in.skipBytes(20);
        } else if (chunkType.equals("VIEW")) {
            in.skipBytes(4);
            if (in.readInt() != 1) {
                in.skipBytes(176);
                int bytesPerView = in.readInt();
                in.skipBytes(bytesPerView);
            }
        } else if (chunkType.equals("MINX")) {
            // skip old transformation values
            in.skipBytes(40);
            physicalX = in.readFloat();
            physicalY = in.readFloat();
            physicalZ = in.readFloat();
        }
    }
    m.sizeT = 1;
    m.sizeC = 3;
    m.rgb = true;
    m.interleaved = true;
    m.imageCount = getSizeT() * getSizeZ();
    m.littleEndian = false;
    m.dimensionOrder = "XYCZT";
    m.pixelType = FormatTools.UINT8;
    MetadataTools.populatePixels(store, this);
    if (getMetadataOptions().getMetadataLevel() == MetadataLevel.ALL) {
        for (int i = 0; i < roiIDs.size(); i++) {
            store.setROIID(roiIDs.get(i), i);
            store.setImageROIRef(roiIDs.get(i), 0, i);
        }
    }
    if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
        Unit<Length> physicalSizeUnit = convertUnits(pixSizeUnits);
        if (physicalX > 0) {
            Length x = FormatTools.getPhysicalSizeX(physicalX, physicalSizeUnit);
            if (x != null) {
                store.setPixelsPhysicalSizeX(x, 0);
            }
        }
        if (physicalY > 0) {
            Length y = FormatTools.getPhysicalSizeY(physicalY, physicalSizeUnit);
            if (y != null) {
                store.setPixelsPhysicalSizeY(y, 0);
            }
        }
        if (physicalZ > 0) {
            Length z = FormatTools.getPhysicalSizeZ(physicalZ, physicalSizeUnit);
            if (z != null) {
                store.setPixelsPhysicalSizeZ(z, 0);
            }
        }
    }
}
Also used : NonNegativeInteger(ome.xml.model.primitives.NonNegativeInteger) Color(ome.xml.model.primitives.Color) ArrayList(java.util.ArrayList) CoreMetadata(loci.formats.CoreMetadata) FormatException(loci.formats.FormatException) MetadataStore(loci.formats.meta.MetadataStore) Length(ome.units.quantity.Length) RandomAccessInputStream(loci.common.RandomAccessInputStream)

Example 19 with Color

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

the class MIASReader method getChannelColorFromFile.

// -- Helper methods --
/**
 * Get the color associated with the given file's channel.
 * The file must be one of the
 * Well<nnnn>_mode<n>_z<nnn>_t<nnn>_AllModesOverlay.tif
 * files in <experiment>/<plate>/results/
 */
private Color getChannelColorFromFile(String file) throws FormatException, IOException {
    RandomAccessInputStream s = new RandomAccessInputStream(file, 16);
    TiffParser tp = new TiffParser(s);
    IFD ifd = tp.getFirstIFD();
    s.close();
    if (ifd == null)
        return null;
    int[] colorMap = tp.getColorMap(ifd);
    if (colorMap == null)
        return null;
    int nEntries = colorMap.length / 3;
    int max = Integer.MIN_VALUE;
    int maxIndex = -1;
    for (int c = 0; c < 3; c++) {
        int v = (colorMap[c * nEntries] >> 8) & 0xff;
        if (v > max) {
            max = v;
            maxIndex = c;
        } else if (v == max) {
            return new Color(0, 0, 0, 255);
        }
    }
    switch(maxIndex) {
        case // red
        0:
            return new Color(255, 0, 0, 255);
        case // green
        1:
            return new Color(0, 255, 0, 255);
        case // blue
        2:
            return new Color(0, 0, 255, 255);
    }
    return null;
}
Also used : IFD(loci.formats.tiff.IFD) Color(ome.xml.model.primitives.Color) TiffParser(loci.formats.tiff.TiffParser) RandomAccessInputStream(loci.common.RandomAccessInputStream)

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