Search in sources :

Example 66 with IFD

use of loci.formats.tiff.IFD in project bioformats by openmicroscopy.

the class FV1000Reader method getOptimalTileHeight.

/* @see loci.formats.IFormatReader#getOptimalTileHeight() */
@Override
public int getOptimalTileHeight() {
    FormatTools.assertId(currentId, true, 1);
    RandomAccessInputStream plane = getPlane(getSeries(), 0);
    if (plane == null)
        return super.getOptimalTileHeight();
    try {
        TiffParser tp = new TiffParser(plane);
        IFD ifd = tp.getFirstIFD();
        plane.close();
        return (int) ifd.getTileLength();
    } catch (FormatException e) {
        LOGGER.debug("Could not retrieve tile height", e);
    } catch (IOException e) {
        LOGGER.debug("Could not retrieve tile height", e);
    }
    return super.getOptimalTileHeight();
}
Also used : IFD(loci.formats.tiff.IFD) TiffParser(loci.formats.tiff.TiffParser) RandomAccessInputStream(loci.common.RandomAccessInputStream) IOException(java.io.IOException) FormatException(loci.formats.FormatException)

Example 67 with IFD

use of loci.formats.tiff.IFD in project bioformats by openmicroscopy.

the class DNGReader method openBytes.

/**
 * @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
 */
@Override
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException {
    FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h);
    IFD ifd = ifds.get(no);
    int[] bps = ifd.getBitsPerSample();
    int dataSize = bps[0];
    long[] byteCounts = ifd.getStripByteCounts();
    long totalBytes = 0;
    for (long b : byteCounts) {
        totalBytes += b;
    }
    if (totalBytes == FormatTools.getPlaneSize(this) || bps.length > 1) {
        if (tiffParser == null) {
            initTiffParser();
        }
        byte[] b = new byte[buf.length / 2];
        tiffParser.getSamples(ifds.get(0), b, x, y, w, h);
        for (int i = 0; i < b.length; i++) {
            int c = isInterleaved() ? i % 3 : i / (b.length / 3);
            short v = (short) (b[i] & 0xff);
            v = adjustForWhiteBalance(v, c);
            DataTools.unpackBytes(v, buf, i * 2, 2, isLittleEndian());
        }
        return buf;
    }
    if (lastPlane == null || lastIndex != no) {
        long[] offsets = ifd.getStripOffsets();
        ByteArrayOutputStream src = new ByteArrayOutputStream();
        for (int i = 0; i < byteCounts.length; i++) {
            byte[] t = new byte[(int) byteCounts[i]];
            in.seek(offsets[i]);
            in.read(t);
            src.write(t);
        }
        // default color map
        int[] colorMap = { 1, 0, 2, 1 };
        short[] ifdColors = (short[]) ifd.get(COLOR_MAP);
        if (ifdColors != null && ifdColors.length >= colorMap.length) {
            boolean colorsValid = true;
            for (int q = 0; q < colorMap.length; q++) {
                if (ifdColors[q] < 0 || ifdColors[q] > 2) {
                    // found invalid channel index, use default color map instead
                    colorsValid = false;
                    break;
                }
            }
            if (colorsValid) {
                for (int q = 0; q < colorMap.length; q++) {
                    colorMap[q] = ifdColors[q];
                }
            }
        }
        lastPlane = new byte[FormatTools.getPlaneSize(this)];
        RandomAccessInputStream bb = new RandomAccessInputStream(new ByteArrayHandle(src.toByteArray()));
        src.close();
        short[] pix = new short[getSizeX() * getSizeY() * 3];
        for (int row = 0; row < getSizeY(); row++) {
            int realRow = row;
            for (int col = 0; col < getSizeX(); col++) {
                short val = (short) (bb.readBits(dataSize) & 0xffff);
                int mapIndex = (realRow % 2) * 2 + (col % 2);
                int redOffset = realRow * getSizeX() + col;
                int greenOffset = (getSizeY() + realRow) * getSizeX() + col;
                int blueOffset = (2 * getSizeY() + realRow) * getSizeX() + col;
                if (colorMap[mapIndex] == 0) {
                    pix[redOffset] = adjustForWhiteBalance(val, 0);
                } else if (colorMap[mapIndex] == 1) {
                    pix[greenOffset] = adjustForWhiteBalance(val, 1);
                } else if (colorMap[mapIndex] == 2) {
                    pix[blueOffset] = adjustForWhiteBalance(val, 2);
                }
            }
        }
        bb.close();
        ImageTools.interpolate(pix, buf, colorMap, getSizeX(), getSizeY(), isLittleEndian());
        lastIndex = no;
    }
    int bpp = FormatTools.getBytesPerPixel(getPixelType()) * 3;
    int rowLen = w * bpp;
    int width = getSizeX() * bpp;
    for (int row = 0; row < h; row++) {
        System.arraycopy(lastPlane, (row + y) * width + x * bpp, buf, row * rowLen, rowLen);
    }
    return buf;
}
Also used : IFD(loci.formats.tiff.IFD) ByteArrayOutputStream(java.io.ByteArrayOutputStream) RandomAccessInputStream(loci.common.RandomAccessInputStream) ByteArrayHandle(loci.common.ByteArrayHandle)

Example 68 with IFD

use of loci.formats.tiff.IFD in project bioformats by openmicroscopy.

the class CellSensReader method initFile.

// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
    super.initFile(id);
    if (!checkSuffix(id, "vsi")) {
        Location current = new Location(id).getAbsoluteFile();
        Location parent = current.getParentFile();
        parent = parent.getParentFile();
        Location grandparent = parent.getParentFile();
        String vsi = parent.getName();
        vsi = vsi.substring(1, vsi.length() - 1) + ".vsi";
        Location vsiFile = new Location(grandparent, vsi);
        if (!vsiFile.exists()) {
            throw new FormatException("Could not find .vsi file.");
        } else {
            id = vsiFile.getAbsolutePath();
        }
    }
    parser = new TiffParser(id);
    ifds = parser.getIFDs();
    RandomAccessInputStream vsi = new RandomAccessInputStream(id);
    vsi.order(parser.getStream().isLittleEndian());
    vsi.seek(8);
    readTags(vsi, false, "");
    vsi.close();
    ArrayList<String> files = new ArrayList<String>();
    Location file = new Location(id).getAbsoluteFile();
    Location dir = file.getParentFile();
    String name = file.getName();
    name = name.substring(0, name.lastIndexOf("."));
    Location pixelsDir = new Location(dir, "_" + name + "_");
    String[] stackDirs = pixelsDir.list(true);
    if (stackDirs != null) {
        Arrays.sort(stackDirs);
        for (String f : stackDirs) {
            Location stackDir = new Location(pixelsDir, f);
            String[] pixelsFiles = stackDir.list(true);
            if (pixelsFiles != null) {
                Arrays.sort(pixelsFiles);
                for (String pixelsFile : pixelsFiles) {
                    if (checkSuffix(pixelsFile, "ets")) {
                        files.add(new Location(stackDir, pixelsFile).getAbsolutePath());
                    }
                }
            }
        }
    }
    files.add(file.getAbsolutePath());
    usedFiles = files.toArray(new String[files.size()]);
    if (expectETS && files.size() == 1) {
        String message = "Missing expected .ets files in " + pixelsDir.getAbsolutePath();
        if (failOnMissingETS()) {
            throw new FormatException(message);
        } else {
            LOGGER.warn(message);
        }
    } else if (!expectETS && files.size() > 1) {
        LOGGER.warn(".ets files present but not expected");
    }
    int seriesCount = files.size();
    core.clear();
    IFDList exifs = parser.getExifIFDs();
    int index = 0;
    for (int s = 0; s < seriesCount; s++) {
        CoreMetadata ms = new CoreMetadata();
        core.add(ms);
        if (s < files.size() - 1) {
            setCoreIndex(index);
            parseETSFile(files.get(s), s);
            ms.littleEndian = compressionType.get(index) == RAW;
            ms.interleaved = ms.rgb;
            for (int q = 1; q < ms.resolutionCount; q++) {
                int res = core.size() - ms.resolutionCount + q;
                core.get(res).littleEndian = ms.littleEndian;
                core.get(res).interleaved = ms.interleaved;
            }
            if (s == 0 && exifs.size() > 0) {
                IFD exif = exifs.get(0);
                int newX = exif.getIFDIntValue(IFD.PIXEL_X_DIMENSION);
                int newY = exif.getIFDIntValue(IFD.PIXEL_Y_DIMENSION);
                if (getSizeX() > newX || getSizeY() > newY) {
                    ms.sizeX = newX;
                    ms.sizeY = newY;
                }
            }
            index += ms.resolutionCount;
            if (s < pyramids.size()) {
                ms.seriesMetadata = pyramids.get(s).originalMetadata;
            }
            setCoreIndex(0);
        } else {
            IFD ifd = ifds.get(s - files.size() + 1);
            PhotoInterp p = ifd.getPhotometricInterpretation();
            int samples = ifd.getSamplesPerPixel();
            ms.rgb = samples > 1 || p == PhotoInterp.RGB;
            ms.sizeX = (int) ifd.getImageWidth();
            ms.sizeY = (int) ifd.getImageLength();
            ms.sizeZ = 1;
            ms.sizeT = 1;
            ms.sizeC = ms.rgb ? samples : 1;
            ms.littleEndian = ifd.isLittleEndian();
            ms.indexed = p == PhotoInterp.RGB_PALETTE && (get8BitLookupTable() != null || get16BitLookupTable() != null);
            ms.imageCount = 1;
            ms.pixelType = ifd.getPixelType();
            ms.interleaved = false;
            ms.falseColor = false;
            ms.thumbnail = s != 0;
            index++;
        }
        ms.metadataComplete = true;
        ms.dimensionOrder = "XYCZT";
    }
    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this, true);
    String instrument = MetadataTools.createLSID("Instrument", 0);
    store.setInstrumentID(instrument, 0);
    for (int i = 0; i < pyramids.size(); i++) {
        Pyramid pyramid = pyramids.get(i);
        store.setObjectiveID(MetadataTools.createLSID("Objective", 0, i), 0, i);
        store.setObjectiveNominalMagnification(pyramid.magnification, 0, i);
        store.setObjectiveWorkingDistance(FormatTools.createLength(pyramid.workingDistance, UNITS.MICROMETER), 0, i);
        for (int q = 0; q < pyramid.objectiveTypes.size(); q++) {
            if (pyramid.objectiveTypes.get(q) == 1) {
                store.setObjectiveModel(pyramid.objectiveNames.get(q), 0, i);
                break;
            }
        }
        store.setObjectiveLensNA(pyramid.numericalAperture, 0, i);
        store.setDetectorID(MetadataTools.createLSID("Detector", 0, i), 0, i);
        store.setDetectorOffset(pyramid.offset, 0, i);
        store.setDetectorGain(pyramid.gain, 0, i);
        for (int q = 0; q < pyramid.deviceTypes.size(); q++) {
            if (pyramid.deviceTypes.get(q).equals("Camera")) {
                if (q < pyramid.deviceNames.size()) {
                    store.setDetectorModel(pyramid.deviceNames.get(q), 0, i);
                }
                if (q < pyramid.deviceIDs.size()) {
                    store.setDetectorSerialNumber(pyramid.deviceIDs.get(q), 0, i);
                }
                if (q < pyramid.deviceManufacturers.size()) {
                    store.setDetectorManufacturer(pyramid.deviceManufacturers.get(q), 0, i);
                }
                store.setDetectorType(getDetectorType("CCD"), 0, i);
                break;
            }
        }
    }
    int nextPyramid = 0;
    for (int i = 0; i < core.size(); ) {
        setCoreIndex(i);
        Pyramid pyramid = null;
        if (nextPyramid < pyramids.size()) {
            pyramid = pyramids.get(nextPyramid++);
        }
        int ii = coreIndexToSeries(i);
        if (pyramid != null) {
            int nextPlane = 0;
            int effectiveSizeC = core.get(i).rgb ? 1 : core.get(i).sizeC;
            for (int c = 0; c < effectiveSizeC; c++) {
                store.setDetectorSettingsID(MetadataTools.createLSID("Detector", 0, nextPyramid - 1), ii, c);
                store.setDetectorSettingsBinning(getBinning(pyramid.binningX + "x" + pyramid.binningY), ii, c);
                if (c == 0) {
                    store.setDetectorSettingsGain(pyramid.redGain, ii, c);
                    store.setDetectorSettingsOffset(pyramid.redOffset, ii, c);
                } else if (c == 1) {
                    store.setDetectorSettingsGain(pyramid.greenGain, ii, c);
                    store.setDetectorSettingsOffset(pyramid.greenOffset, ii, c);
                } else if (c == 2) {
                    store.setDetectorSettingsGain(pyramid.blueGain, ii, c);
                    store.setDetectorSettingsOffset(pyramid.blueOffset, ii, c);
                }
                if (c < pyramid.channelNames.size()) {
                    store.setChannelName(pyramid.channelNames.get(c), ii, c);
                }
                if (c < pyramid.channelWavelengths.size()) {
                    int wave = pyramid.channelWavelengths.get(c).intValue();
                    if (wave > 0) {
                        store.setChannelEmissionWavelength(FormatTools.getEmissionWavelength((double) wave), ii, c);
                    }
                }
                for (int z = 0; z < core.get(i).sizeZ; z++) {
                    for (int t = 0; t < core.get(i).sizeT; t++) {
                        nextPlane = getIndex(z, c, t);
                        Long exp = pyramid.defaultExposureTime;
                        if (c < pyramid.exposureTimes.size()) {
                            exp = pyramid.exposureTimes.get(c);
                        }
                        if (exp != null) {
                            store.setPlaneExposureTime(FormatTools.createTime(exp / 1000000.0, UNITS.SECOND), ii, nextPlane);
                        }
                        store.setPlanePositionX(FormatTools.createLength(pyramid.originX, UNITS.MICROMETER), ii, nextPlane);
                        store.setPlanePositionY(FormatTools.createLength(pyramid.originY, UNITS.MICROMETER), ii, nextPlane);
                    }
                }
            }
        }
        store.setImageInstrumentRef(instrument, ii);
        if (pyramid != null) {
            String imageName = pyramid.name;
            boolean duplicate = false;
            for (int q = 0; q < pyramids.size(); q++) {
                if (q != (nextPyramid - 1) && imageName.equals(pyramids.get(q).name)) {
                    duplicate = true;
                    break;
                }
            }
            if (!imageName.equals("Overview") && !imageName.equals("Label") && duplicate) {
                imageName += " #" + ii;
            }
            if (imageName.equals("Overview") || imageName.equals("Label")) {
                imageName = imageName.toLowerCase();
            }
            store.setImageName(imageName, ii);
            store.setObjectiveSettingsID(MetadataTools.createLSID("Objective", 0, nextPyramid - 1), ii);
            store.setObjectiveSettingsRefractiveIndex(pyramid.refractiveIndex, ii);
            if (pyramid.physicalSizeX > 0) {
                store.setPixelsPhysicalSizeX(FormatTools.getPhysicalSizeX(pyramid.physicalSizeX), ii);
            }
            if (pyramid.physicalSizeY > 0) {
                store.setPixelsPhysicalSizeY(FormatTools.getPhysicalSizeY(pyramid.physicalSizeY), ii);
            }
            if (pyramid.acquisitionTime != null) {
                // acquisition time is stored in seconds
                store.setImageAcquisitionDate(new Timestamp(DateTools.convertDate(pyramid.acquisitionTime * 1000, DateTools.UNIX)), ii);
            }
        } else {
            store.setImageName("macro image", ii);
        }
        i += core.get(i).resolutionCount;
    }
    setCoreIndex(0);
}
Also used : IFD(loci.formats.tiff.IFD) ArrayList(java.util.ArrayList) PhotoInterp(loci.formats.tiff.PhotoInterp) CoreMetadata(loci.formats.CoreMetadata) Timestamp(ome.xml.model.primitives.Timestamp) FormatException(loci.formats.FormatException) MetadataStore(loci.formats.meta.MetadataStore) IFDList(loci.formats.tiff.IFDList) TiffParser(loci.formats.tiff.TiffParser) RandomAccessInputStream(loci.common.RandomAccessInputStream) Location(loci.common.Location)

Example 69 with IFD

use of loci.formats.tiff.IFD in project bioformats by openmicroscopy.

the class OMETiffWriterTest method testSaveBytesTiling.

@Test(dataProvider = "tiling")
public void testSaveBytesTiling(int tileSize, boolean littleEndian, boolean interleaved, int rgbChannels, int seriesCount, int sizeT, String compression, int pixelType, boolean bigTiff) throws Exception {
    if (percentageOfTilingTests == 0)
        return;
    File tmp = File.createTempFile("OMETiffWriterTest_Tiling", ".ome.tiff");
    tmp.deleteOnExit();
    Plane originalPlane = WriterUtilities.writeImage(tmp, tileSize, littleEndian, interleaved, rgbChannels, seriesCount, sizeT, compression, pixelType, bigTiff);
    TiffReader reader = new TiffReader();
    reader.setId(tmp.getAbsolutePath());
    int expectedTileSize = tileSize;
    if (tileSize < TILE_GRANULARITY) {
        expectedTileSize = TILE_GRANULARITY;
    } else {
        expectedTileSize = Math.round((float) tileSize / TILE_GRANULARITY) * TILE_GRANULARITY;
    }
    IFD tileIFd = reader.getIFDs().get(0);
    assertEquals(tileIFd.getIFDIntValue(IFD.TILE_LENGTH), expectedTileSize);
    assertEquals(tileIFd.getIFDIntValue(IFD.TILE_WIDTH), expectedTileSize);
    WriterUtilities.checkImage(reader, originalPlane, interleaved, rgbChannels, seriesCount, sizeT, compression);
    tmp.delete();
    reader.close();
}
Also used : TiffReader(loci.formats.in.TiffReader) OMETiffReader(loci.formats.in.OMETiffReader) IFD(loci.formats.tiff.IFD) File(java.io.File) Test(org.testng.annotations.Test)

Example 70 with IFD

use of loci.formats.tiff.IFD in project bioformats by openmicroscopy.

the class TiffWriterTest method setUp.

@BeforeMethod
public void setUp() throws Exception {
    ifd = new IFD();
    writer = new TiffWriterMock();
    metadata = WriterUtilities.createMetadata();
    for (int i = 0; i < 1024 * 1024; i++) {
        buf[i] = (byte) (i % 255);
    }
}
Also used : IFD(loci.formats.tiff.IFD) TiffWriterMock(loci.formats.utests.tiff.TiffWriterMock) BeforeMethod(org.testng.annotations.BeforeMethod)

Aggregations

IFD (loci.formats.tiff.IFD)121 TiffParser (loci.formats.tiff.TiffParser)74 RandomAccessInputStream (loci.common.RandomAccessInputStream)51 CoreMetadata (loci.formats.CoreMetadata)33 FormatException (loci.formats.FormatException)32 MetadataStore (loci.formats.meta.MetadataStore)21 IFDList (loci.formats.tiff.IFDList)21 PhotoInterp (loci.formats.tiff.PhotoInterp)18 IOException (java.io.IOException)17 Location (loci.common.Location)15 ArrayList (java.util.ArrayList)14 Timestamp (ome.xml.model.primitives.Timestamp)11 Length (ome.units.quantity.Length)10 Time (ome.units.quantity.Time)8 TiffIFDEntry (loci.formats.tiff.TiffIFDEntry)7 TiffRational (loci.formats.tiff.TiffRational)6 File (java.io.File)5 TiffReader (loci.formats.in.TiffReader)5 NonNegativeInteger (ome.xml.model.primitives.NonNegativeInteger)5 PositiveInteger (ome.xml.model.primitives.PositiveInteger)5