diff --git a/components/bio-formats-plugins/pom.xml b/components/bio-formats-plugins/pom.xml index db8e47910ca..0f273084a31 100644 --- a/components/bio-formats-plugins/pom.xml +++ b/components/bio-formats-plugins/pom.xml @@ -8,7 +8,7 @@ ome pom-bio-formats - 8.0.0-SNAPSHOT + 8.1.0-SNAPSHOT ../.. diff --git a/components/bio-formats-plugins/src/loci/plugins/config/ConfigWindow.java b/components/bio-formats-plugins/src/loci/plugins/config/ConfigWindow.java index 6155c86f472..0c3b9d0704b 100644 --- a/components/bio-formats-plugins/src/loci/plugins/config/ConfigWindow.java +++ b/components/bio-formats-plugins/src/loci/plugins/config/ConfigWindow.java @@ -349,7 +349,7 @@ public void run() { log.println("-- Formats --"); try { Class irClass = Class.forName("loci.formats.ImageReader"); - Object ir = irClass.newInstance(); + Object ir = irClass.getDeclaredConstructor().newInstance(); Method getClasses = irClass.getMethod("getReaders"); Object[] readers = (Object[]) getClasses.invoke(ir); for (int i=0; i matlabClass = Class.forName("com.mathworks.jmi.Matlab"); - Object matlab = matlabClass.newInstance(); + Object matlab = matlabClass.getDeclaredConstructor().newInstance(); Method eval = matlabClass.getMethod("eval", new Class[] {String.class}); String ans = (String) eval.invoke(matlab, new Object[] {"version"}); diff --git a/components/bio-formats-plugins/src/loci/plugins/config/FormatEntry.java b/components/bio-formats-plugins/src/loci/plugins/config/FormatEntry.java index 2a6ac20c0da..c77cb7ffe77 100644 --- a/components/bio-formats-plugins/src/loci/plugins/config/FormatEntry.java +++ b/components/bio-formats-plugins/src/loci/plugins/config/FormatEntry.java @@ -72,7 +72,7 @@ public FormatEntry(PrintWriter log, Object reader) { String fwClassName = "loci.plugins.config." + readerName + "Widgets"; try { Class fwClass = Class.forName(fwClassName); - fw = (IFormatWidgets) fwClass.newInstance(); + fw = (IFormatWidgets) fwClass.getDeclaredConstructor().newInstance(); log.println("Initialized extra widgets for " + readerName + " reader."); } catch (Throwable t) { diff --git a/components/bio-formats-plugins/src/loci/plugins/in/IdDialog.java b/components/bio-formats-plugins/src/loci/plugins/in/IdDialog.java index 58a51f71b04..13a56ba47a7 100644 --- a/components/bio-formats-plugins/src/loci/plugins/in/IdDialog.java +++ b/components/bio-formats-plugins/src/loci/plugins/in/IdDialog.java @@ -167,7 +167,7 @@ else if (options.isOMERO()) { String group = gd.getNextString(); Long groupID = null; try { - groupID = new Long(group); + groupID = Long.parseLong(group); } catch (NumberFormatException e) { } diff --git a/components/bio-formats-plugins/src/loci/plugins/in/ImporterMetadata.java b/components/bio-formats-plugins/src/loci/plugins/in/ImporterMetadata.java index 55c894707b7..ffd0569d01d 100644 --- a/components/bio-formats-plugins/src/loci/plugins/in/ImporterMetadata.java +++ b/components/bio-formats-plugins/src/loci/plugins/in/ImporterMetadata.java @@ -82,18 +82,18 @@ public ImporterMetadata(IFormatReader r, ImportProcess process, // merge core values final String pad = " "; // puts core values first when alphabetizing - put(pad + s + "SizeX", new Integer(r.getSizeX())); - put(pad + s + "SizeY", new Integer(r.getSizeY())); - put(pad + s + "SizeZ", new Integer(r.getSizeZ())); - put(pad + s + "SizeT", new Integer(r.getSizeT())); - put(pad + s + "SizeC", new Integer(r.getSizeC())); - put(pad + s + "IsRGB", new Boolean(r.isRGB())); + put(pad + s + "SizeX", Integer.valueOf(r.getSizeX())); + put(pad + s + "SizeY", Integer.valueOf(r.getSizeY())); + put(pad + s + "SizeZ", Integer.valueOf(r.getSizeZ())); + put(pad + s + "SizeT", Integer.valueOf(r.getSizeT())); + put(pad + s + "SizeC", Integer.valueOf(r.getSizeC())); + put(pad + s + "IsRGB", Boolean.valueOf(r.isRGB())); put(pad + s + "PixelType", FormatTools.getPixelTypeString(r.getPixelType())); - put(pad + s + "LittleEndian", new Boolean(r.isLittleEndian())); + put(pad + s + "LittleEndian", Boolean.valueOf(r.isLittleEndian())); put(pad + s + "DimensionOrder", r.getDimensionOrder()); - put(pad + s + "IsInterleaved", new Boolean(r.isInterleaved())); - put(pad + s + "BitsPerPixel", new Integer(r.getBitsPerPixel())); + put(pad + s + "IsInterleaved", Boolean.valueOf(r.isInterleaved())); + put(pad + s + "BitsPerPixel", Integer.valueOf(r.getBitsPerPixel())); String seriesName = process.getOMEMetadata().getImageName(i); put(pad + "Series " + i + " Name", seriesName); diff --git a/components/bio-formats-plugins/src/loci/plugins/macro/LociFunctions.java b/components/bio-formats-plugins/src/loci/plugins/macro/LociFunctions.java index 4c6ed49cf1e..27936464a45 100644 --- a/components/bio-formats-plugins/src/loci/plugins/macro/LociFunctions.java +++ b/components/bio-formats-plugins/src/loci/plugins/macro/LociFunctions.java @@ -127,25 +127,25 @@ public void getVersionNumber(String[] version) { // -- LociFunctions API methods - loci.formats.IFormatReader -- public void getImageCount(Double[] imageCount) { - imageCount[0] = new Double(r.getImageCount()); + imageCount[0] = Double.valueOf(r.getImageCount()); } - public void getSizeX(Double[] sizeX) { sizeX[0] = new Double(r.getSizeX()); } - public void getSizeY(Double[] sizeY) { sizeY[0] = new Double(r.getSizeY()); } - public void getSizeZ(Double[] sizeZ) { sizeZ[0] = new Double(r.getSizeZ()); } - public void getSizeC(Double[] sizeC) { sizeC[0] = new Double(r.getSizeC()); } - public void getSizeT(Double[] sizeT) { sizeT[0] = new Double(r.getSizeT()); } + public void getSizeX(Double[] sizeX) { sizeX[0] = Double.valueOf(r.getSizeX()); } + public void getSizeY(Double[] sizeY) { sizeY[0] = Double.valueOf(r.getSizeY()); } + public void getSizeZ(Double[] sizeZ) { sizeZ[0] = Double.valueOf(r.getSizeZ()); } + public void getSizeC(Double[] sizeC) { sizeC[0] = Double.valueOf(r.getSizeC()); } + public void getSizeT(Double[] sizeT) { sizeT[0] = Double.valueOf(r.getSizeT()); } public void getPixelType(String[] pixelType) { pixelType[0] = FormatTools.getPixelTypeString(r.getPixelType()); } public void getEffectiveSizeC(Double[] effectiveSizeC) { - effectiveSizeC[0] = new Double(r.getEffectiveSizeC()); + effectiveSizeC[0] = Double.valueOf(r.getEffectiveSizeC()); } public void getRGBChannelCount(Double[] rgbChannelCount) { - rgbChannelCount[0] = new Double(r.getRGBChannelCount()); + rgbChannelCount[0] = Double.valueOf(r.getRGBChannelCount()); } public void isIndexed(String[] indexed) { @@ -154,33 +154,33 @@ public void isIndexed(String[] indexed) { public void getChannelDimCount(Double[] channelDimCount) { Modulo moduloC = r.getModuloC(); - channelDimCount[0] = new Double(moduloC.length() > 1 ? 2 : 1); + channelDimCount[0] = Double.valueOf(moduloC.length() > 1 ? 2 : 1); } public void getChannelDimLength(Double i, Double[] channelDimLength) { Modulo moduloC = r.getModuloC(); if (i.intValue() == 0) { // index 0 - channelDimLength[0] = new Double(moduloC.length() > 1 ? r.getSizeC() / moduloC.length() : r.getSizeC()); + channelDimLength[0] = Double.valueOf(moduloC.length() > 1 ? r.getSizeC() / moduloC.length() : r.getSizeC()); } else { // index 1 - channelDimLength[0] = new Double(moduloC.length()); + channelDimLength[0] = Double.valueOf(moduloC.length()); } } public void getChannelDimType(Double i, Double[] channelDimType) { Modulo moduloC = r.getModuloC(); if (i.intValue() == 0) { // index 0 - channelDimType[0] = new Double(moduloC.length() > 1 ? moduloC.parentType : FormatTools.CHANNEL); + channelDimType[0] = Double.valueOf(moduloC.length() > 1 ? moduloC.parentType : FormatTools.CHANNEL); } else { // index 1 - channelDimType[0] = new Double(moduloC.type); + channelDimType[0] = Double.valueOf(moduloC.type); } } // public void getThumbSizeX(Double[] thumbSizeX) { -// thumbSizeX[0] = new Double(r.getThumbSizeX()); +// thumbSizeX[0] = Double.valueOf(r.getThumbSizeX()); // } // public void getThumbSizeY(Double[] thumbSizeY) { -// thumbSizeY[0] = new Double(r.getThumbSizeY()); +// thumbSizeY[0] = Double.valueOf(r.getThumbSizeY()); // } public void isLittleEndian(String[] littleEndian) { @@ -270,7 +270,7 @@ public void openImage(String title, Double no) throws FormatException, IOException { openSubImage(title, no, 0d, 0d, - new Double(r.getSizeX()), new Double(r.getSizeY())); + Double.valueOf(r.getSizeX()), Double.valueOf(r.getSizeY())); } public void openSubImage(String title, Double no, Double x, Double y, @@ -310,7 +310,7 @@ public void openSubImage(String title, Double no, Double x, Double y, public void closeFileOnly() throws IOException { r.close(true); } public void getSeriesCount(Double[] seriesCount) { - seriesCount[0] = new Double(r.getSeriesCount()); + seriesCount[0] = Double.valueOf(r.getSeriesCount()); } public void setSeries(Double seriesNum) { @@ -323,7 +323,7 @@ public void setSeries(Double seriesNum) { } public void getSeries(Double[] seriesNum) { - seriesNum[0] = new Double(r.getSeries()); + seriesNum[0] = Double.valueOf(r.getSeries()); } public void setNormalized(Boolean normalize) { @@ -331,7 +331,7 @@ public void setNormalized(Boolean normalize) { } public void isNormalized(Boolean[] normalize) { - normalize[0] = new Boolean(r.isNormalized()); + normalize[0] = Boolean.valueOf(r.isNormalized()); } public void setOriginalMetadataPopulated(Boolean populate) { @@ -339,7 +339,7 @@ public void setOriginalMetadataPopulated(Boolean populate) { } public void isOriginalMetadataPopulated(Boolean[] populate) { - populate[0] = new Boolean(r.isOriginalMetadataPopulated()); + populate[0] = Boolean.valueOf(r.isOriginalMetadataPopulated()); } public void setGroupFiles(String groupFiles) { @@ -373,7 +373,7 @@ public void fileGroupOption(String id, String[] fileGroupOption) } public void getUsedFileCount(Double[] count) { - count[0] = new Double(r.getUsedFiles().length); + count[0] = Double.valueOf(r.getUsedFiles().length); } public void getUsedFile(Double i, String[] used) { @@ -385,14 +385,14 @@ public void getCurrentFile(String[] file) { } public void getIndex(Double z, Double c, Double t, Double[] index) { - index[0] = new Double(r.getIndex(z.intValue(), c.intValue(), t.intValue())); + index[0] = Double.valueOf(r.getIndex(z.intValue(), c.intValue(), t.intValue())); } public void getZCTCoords(Double index, Double[] z, Double[] c, Double[] t) { int[] zct = r.getZCTCoords(index.intValue()); - z[0] = new Double(zct[0]); - c[0] = new Double(zct[1]); - t[0] = new Double(zct[2]); + z[0] = Double.valueOf(zct[0]); + c[0] = Double.valueOf(zct[1]); + t[0] = Double.valueOf(zct[2]); } public void getMetadataValue(String field, String[] value) { @@ -472,7 +472,7 @@ public void getPlaneTimingExposureTime(Double[] exposureTime, Double no) { val = valTime.value(UNITS.SECOND).doubleValue(); } } - exposureTime[0] = val == null ? new Double(Double.NaN) : val; + exposureTime[0] = val == null ? Double.NaN : val; } public void getPlanePositionX(Double[] positionX, Double no) { @@ -524,7 +524,7 @@ public void getPixelsPhysicalSizeX(Double[] sizeX) { if (x != null) { sizeX[0] = x.value(UNITS.MICROMETER).doubleValue(); } - if (sizeX[0] == null) sizeX[0] = new Double(Double.NaN); + if (sizeX[0] == null) sizeX[0] = Double.NaN; } public void getPixelsPhysicalSizeY(Double[] sizeY) { @@ -534,7 +534,7 @@ public void getPixelsPhysicalSizeY(Double[] sizeY) { if (y != null) { sizeY[0] = y.value(UNITS.MICROMETER).doubleValue(); } - if (sizeY[0] == null) sizeY[0] = new Double(Double.NaN); + if (sizeY[0] == null) sizeY[0] = Double.NaN; } public void getPixelsPhysicalSizeZ(Double[] sizeZ) { @@ -544,14 +544,14 @@ public void getPixelsPhysicalSizeZ(Double[] sizeZ) { if (z != null) { sizeZ[0] = z.value(UNITS.MICROMETER).doubleValue(); } - if (sizeZ[0] == null) sizeZ[0] = new Double(Double.NaN); + if (sizeZ[0] == null) sizeZ[0] = Double.NaN; } public void getPixelsTimeIncrement(Double[] sizeT) { int imageIndex = r.getSeries(); MetadataRetrieve retrieve = (MetadataRetrieve) r.getMetadataStore(); sizeT[0] = retrieve.getPixelsTimeIncrement(imageIndex).value(UNITS.SECOND).doubleValue(); - if (sizeT[0] == null) sizeT[0] = new Double(Double.NaN); + if (sizeT[0] == null) sizeT[0] = Double.NaN; } // -- PlugIn API methods -- diff --git a/components/bio-formats-plugins/src/loci/plugins/out/Exporter.java b/components/bio-formats-plugins/src/loci/plugins/out/Exporter.java index 0e614bf58e2..7395b38fcfd 100644 --- a/components/bio-formats-plugins/src/loci/plugins/out/Exporter.java +++ b/components/bio-formats-plugins/src/loci/plugins/out/Exporter.java @@ -505,7 +505,7 @@ else if (FormatTools.isSigned(originalType)) { String lsid = MetadataTools.createLSID("Channel", 0, c); store.setChannelID(lsid, 0, c); } - store.setChannelSamplesPerPixel(new PositiveInteger(channels), 0, 0); + store.setChannelSamplesPerPixel(new PositiveInteger(channels), 0, c); if (imp instanceof CompositeImage) { luts[c] = ((CompositeImage) imp).getChannelLut(c + 1); @@ -517,7 +517,7 @@ else if (FormatTools.isSigned(originalType)) { store.setPixelsPhysicalSizeX(FormatTools.getPhysicalSizeX(cal.pixelWidth, cal.getXUnit()), 0); store.setPixelsPhysicalSizeY(FormatTools.getPhysicalSizeY(cal.pixelHeight, cal.getYUnit()), 0); store.setPixelsPhysicalSizeZ(FormatTools.getPhysicalSizeZ(cal.pixelDepth, cal.getZUnit()), 0); - store.setPixelsTimeIncrement(FormatTools.getTime(new Double(cal.frameInterval), cal.getTimeUnit()), 0); + store.setPixelsTimeIncrement(FormatTools.getTime(Double.valueOf(cal.frameInterval), cal.getTimeUnit()), 0); if (imp.getImageStackSize() != imp.getNChannels() * imp.getNSlices() * imp.getNFrames()) diff --git a/components/bio-formats-plugins/src/loci/plugins/util/ROIHandler.java b/components/bio-formats-plugins/src/loci/plugins/util/ROIHandler.java index b395f993bc4..ee90c5e1013 100644 --- a/components/bio-formats-plugins/src/loci/plugins/util/ROIHandler.java +++ b/components/bio-formats-plugins/src/loci/plugins/util/ROIHandler.java @@ -745,10 +745,10 @@ private static void storePoint(PointRoi roi, MetadataStore store, private static void storeLine(Line roi, MetadataStore store, int roiNum, int shape, int c, int z, int t) { - store.setLineX1(new Double(roi.x1), roiNum, shape); - store.setLineX2(new Double(roi.x2), roiNum, shape); - store.setLineY1(new Double(roi.y1), roiNum, shape); - store.setLineY2(new Double(roi.y2), roiNum, shape); + store.setLineX1(Double.valueOf(roi.x1), roiNum, shape); + store.setLineX2(Double.valueOf(roi.x2), roiNum, shape); + store.setLineY1(Double.valueOf(roi.y1), roiNum, shape); + store.setLineY2(Double.valueOf(roi.y2), roiNum, shape); if (c >= 0) { store.setLineTheC(unwrap(c), roiNum, shape); } @@ -787,10 +787,10 @@ private static void storeRectangle(Roi roi, MetadataStore store, int roiNum, int shape, int c, int z, int t) { Rectangle bounds = roi.getBounds(); - store.setRectangleX(new Double(bounds.x), roiNum, shape); - store.setRectangleY(new Double(bounds.y), roiNum, shape); - store.setRectangleWidth(new Double(bounds.width), roiNum, shape); - store.setRectangleHeight(new Double(bounds.height), roiNum, shape); + store.setRectangleX(Double.valueOf(bounds.x), roiNum, shape); + store.setRectangleY(Double.valueOf(bounds.y), roiNum, shape); + store.setRectangleWidth(Double.valueOf(bounds.width), roiNum, shape); + store.setRectangleHeight(Double.valueOf(bounds.height), roiNum, shape); if (c >= 0) { store.setRectangleTheC(unwrap(c), roiNum, shape); } diff --git a/components/bio-formats-plugins/src/loci/plugins/util/RecordedImageProcessor.java b/components/bio-formats-plugins/src/loci/plugins/util/RecordedImageProcessor.java index feefa9a5119..b103465aedd 100644 --- a/components/bio-formats-plugins/src/loci/plugins/util/RecordedImageProcessor.java +++ b/components/bio-formats-plugins/src/loci/plugins/util/RecordedImageProcessor.java @@ -124,19 +124,19 @@ public void abs() { @Override public void add(double value) { - record("add", new Double(value), double.class); + record("add", Double.valueOf(value), double.class); proc.add(value); } @Override public void add(int value) { - record("add", new Integer(value), int.class); + record("add", Integer.valueOf(value), int.class); proc.add(value); } @Override public void and(int value) { - record("and", new Integer(value), int.class); + record("and", Integer.valueOf(value), int.class); proc.and(value); } @@ -154,7 +154,7 @@ public void autoThreshold() { @Override public ImageProcessor convertToByte(boolean doScaling) { - record("convertToByte", new Boolean(doScaling), boolean.class); + record("convertToByte", Boolean.valueOf(doScaling), boolean.class); return proc.convertToByte(doScaling); } @@ -172,14 +172,14 @@ public ImageProcessor convertToRGB() { @Override public ImageProcessor convertToShort(boolean doScaling) { - record("convertToShort", new Boolean(doScaling), boolean.class); + record("convertToShort", Boolean.valueOf(doScaling), boolean.class); return proc.convertToShort(doScaling); } @Override public void convolve(float[] kernel, int kernelWidth, int kernelHeight) { - record("convolve", new Object[] {kernel, new Integer(kernelWidth), - new Integer(kernelHeight)}, new Class[] {float[].class, + record("convolve", new Object[] {kernel, Integer.valueOf(kernelWidth), + Integer.valueOf(kernelHeight)}, new Class[] {float[].class, int.class, int.class}); proc.convolve(kernel, kernelWidth, kernelHeight); } @@ -192,8 +192,8 @@ public void convolve3x3(int[] kernel) { @Override public void copyBits(ImageProcessor ip, int xloc, int yloc, int mode) { - record("copyBits", new Object[] {ip, new Integer(xloc), new Integer(yloc), - new Integer(mode)}, new Class[] {ImageProcessor.class, int.class, + record("copyBits", new Object[] {ip, Integer.valueOf(xloc), Integer.valueOf(yloc), + Integer.valueOf(mode)}, new Class[] {ImageProcessor.class, int.class, int.class, int.class}); proc.copyBits(ip, xloc, yloc, mode); } @@ -316,8 +316,8 @@ else if (activeProcessor instanceof FloatProcessor) { @Override public ImageProcessor createProcessor(int width, int height) { - record("createProcessor", new Object[] {new Integer(width), - new Integer(height)}, new Class[] {int.class, int.class}); + record("createProcessor", new Object[] {Integer.valueOf(width), + Integer.valueOf(height)}, new Class[] {int.class, int.class}); return proc.createProcessor(width, height); } @@ -335,30 +335,30 @@ public void dilate() { @Override public void drawDot(int xcenter, int ycenter) { - record("drawDot", new Object[] {new Integer(xcenter), - new Integer(ycenter)}, new Class[] {int.class, int.class}); + record("drawDot", new Object[] {Integer.valueOf(xcenter), + Integer.valueOf(ycenter)}, new Class[] {int.class, int.class}); proc.drawDot(xcenter, ycenter); } @Override public void drawLine(int x1, int y1, int x2, int y2) { - record("drawLine", new Object[] {new Integer(x1), new Integer(y1), - new Integer(x2), new Integer(y2)}, new Class[] {int.class, int.class, + record("drawLine", new Object[] {Integer.valueOf(x1), Integer.valueOf(y1), + Integer.valueOf(x2), Integer.valueOf(y2)}, new Class[] {int.class, int.class, int.class, int.class}); proc.drawLine(x1, y1, x2, y2); } @Override public void drawOval(int x, int y, int width, int height) { - record("drawOval", new Object[] {new Integer(x), new Integer(y), - new Integer(width), new Integer(height)}, new Class[] {int.class, + record("drawOval", new Object[] {Integer.valueOf(x), Integer.valueOf(y), + Integer.valueOf(width), Integer.valueOf(height)}, new Class[] {int.class, int.class, int.class, int.class}); proc.drawOval(x, y, width, height); } @Override public void drawPixel(int x, int y) { - record("drawPixel", new Object[] {new Integer(x), new Integer(y)}, + record("drawPixel", new Object[] {Integer.valueOf(x), Integer.valueOf(y)}, new Class[] {int.class, int.class}); proc.drawPixel(x, y); } @@ -371,8 +371,8 @@ public void drawPolygon(Polygon p) { @Override public void drawRect(int x, int y, int width, int height) { - record("drawRect", new Object[] {new Integer(x), new Integer(y), - new Integer(width), new Integer(height)}, new Class[] {int.class, + record("drawRect", new Object[] {Integer.valueOf(x), Integer.valueOf(y), + Integer.valueOf(width), Integer.valueOf(height)}, new Class[] {int.class, int.class, int.class, int.class}); proc.drawRect(x, y, width, height); } @@ -385,7 +385,7 @@ public void drawString(String s) { @Override public void drawString(String s, int x, int y) { - record("drawString", new Object[] {s, new Integer(x), new Integer(y)}, + record("drawString", new Object[] {s, Integer.valueOf(x), Integer.valueOf(y)}, new Class[] {String.class, int.class, int.class}); proc.drawString(s, x, y); } @@ -422,8 +422,8 @@ public void fill(ImageProcessor mask) { @Override public void fillOval(int x, int y, int width, int height) { - record("fillOval", new Object[] {new Integer(x), new Integer(y), - new Integer(width), new Integer(height)}, new Class[] {int.class, + record("fillOval", new Object[] {Integer.valueOf(x), Integer.valueOf(y), + Integer.valueOf(width), Integer.valueOf(height)}, new Class[] {int.class, int.class, int.class, int.class}); proc.fillOval(x, y, width, height); } @@ -436,7 +436,7 @@ public void fillPolygon(Polygon p) { @Override public void filter(int type) { - record("filter", new Integer(type), int.class); + record("filter", Integer.valueOf(type), int.class); proc.filter(type); } @@ -460,19 +460,19 @@ public void flipVertical() { @Override public void gamma(double value) { - record("gamma", new Double(value), double.class); + record("gamma", Double.valueOf(value), double.class); proc.gamma(value); } @Override public int get(int index) { - record("get", new Integer(index), int.class); + record("get", Integer.valueOf(index), int.class); return proc.get(index); } @Override public int get(int x, int y) { - record("get", new Object[] {new Integer(x), new Integer(y)}, + record("get", new Object[] {Integer.valueOf(x), Integer.valueOf(y)}, new Class[] {int.class, int.class}); return proc.get(x, y); } @@ -527,8 +527,8 @@ public ColorModel getColorModel() { @Override public void getColumn(int x, int y, int[] data, int length) { - record("getColumn", new Object[] {new Integer(x), new Integer(y), data, - new Integer(length)}, new Class[] {int.class, int.class, int[].class, + record("getColumn", new Object[] {Integer.valueOf(x), Integer.valueOf(y), data, + Integer.valueOf(length)}, new Class[] {int.class, int.class, int[].class, int.class}); proc.getColumn(x, y, data, length); } @@ -547,13 +547,13 @@ public IndexColorModel getDefaultColorModel() { @Override public float getf(int index) { - record("getf", new Integer(index), int.class); + record("getf", Integer.valueOf(index), int.class); return proc.getf(index); } @Override public float getf(int x, int y) { - record("getf", new Object[] {new Integer(x), new Integer(y)}, + record("getf", new Object[] {Integer.valueOf(x), Integer.valueOf(y)}, new Class[] {int.class, int.class}); return proc.getf(x, y); } @@ -614,15 +614,15 @@ public boolean getInterpolate() { @Override public double getInterpolatedPixel(double x, double y) { - record("getInterpolatedPixel", new Object[] {new Double(x), new Double(y)}, + record("getInterpolatedPixel", new Object[] {Double.valueOf(x), Double.valueOf(y)}, new Class[] {double.class, double.class}); return proc.getInterpolatedPixel(x, y); } @Override public double[] getLine(double x1, double y1, double x2, double y2) { - record("getLine", new Object[] {new Double(x1), new Double(y1), - new Double(x2), new Double(y2)}, new Class[] {double.class, double.class, + record("getLine", new Object[] {Double.valueOf(x1), Double.valueOf(y1), + Double.valueOf(x2), Double.valueOf(y2)}, new Class[] {double.class, double.class, double.class, double.class}); return proc.getLine(x1, y1, x2, y2); } @@ -677,21 +677,21 @@ public int getNChannels() { @Override public int getPixel(int x, int y) { - record("getPixel", new Object[] {new Integer(x), new Integer(y)}, + record("getPixel", new Object[] {Integer.valueOf(x), Integer.valueOf(y)}, new Class[] {int.class, int.class}); return proc.getPixel(x, y); } @Override public int[] getPixel(int x, int y, int[] iArray) { - record("getPixel", new Object[] {new Integer(x), new Integer(y), iArray}, + record("getPixel", new Object[] {Integer.valueOf(x), Integer.valueOf(y), iArray}, new Class[] {int.class, int.class, int[].class}); return proc.getPixel(x, y, iArray); } @Override public int getPixelInterpolated(double x, double y) { - record("getPixelInterpolated", new Object[] {new Double(x), new Double(y)}, + record("getPixelInterpolated", new Object[] {Double.valueOf(x), Double.valueOf(y)}, new Class[] {double.class, double.class}); return proc.getPixelInterpolated(x, y); } @@ -716,7 +716,7 @@ public Object getPixelsCopy() { @Override public float getPixelValue(int x, int y) { - record("getPixelValue", new Object[] {new Integer(x), new Integer(y)}, + record("getPixelValue", new Object[] {Integer.valueOf(x), Integer.valueOf(y)}, new Class[] {int.class, int.class}); return proc.getPixelValue(x, y); } @@ -729,8 +729,8 @@ public Rectangle getRoi() { @Override public void getRow(int x, int y, int[] data, int length) { - record("getRow", new Object[] {new Integer(x), new Integer(y), data, - new Integer(length)}, new Class[] {int.class, int.class, int[].class, + record("getRow", new Object[] {Integer.valueOf(x), Integer.valueOf(y), data, + Integer.valueOf(length)}, new Class[] {int.class, int.class, int[].class, int.class}); proc.getRow(x, y, data, length); } @@ -755,7 +755,7 @@ public int getWidth() { @Override public void insert(ImageProcessor ip, int xloc, int yloc) { - record("insert", new Object[] {ip, new Integer(xloc), new Integer(yloc)}, + record("insert", new Object[] {ip, Integer.valueOf(xloc), Integer.valueOf(yloc)}, new Class[] {ImageProcessor.class, int.class, int.class}); proc.insert(ip, xloc, yloc); } @@ -792,7 +792,7 @@ public boolean isPseudoColorLut() { @Override public void lineTo(int x2, int y2) { - record("lineTo", new Object[] {new Integer(x2), new Integer(y2)}, + record("lineTo", new Object[] {Integer.valueOf(x2), Integer.valueOf(y2)}, new Class[] {int.class, int.class}); proc.lineTo(x2, y2); } @@ -803,7 +803,7 @@ public void log() { } public void max(double value) { - record("max", new Double(value), double.class); + record("max", Double.valueOf(value), double.class); proc.max(value); } @@ -818,7 +818,7 @@ public void medianFilter() { } public void min(double value) { - record("min", new Double(value), double.class); + record("min", Double.valueOf(value), double.class); proc.min(value); } @@ -828,54 +828,54 @@ public double minValue() { } public void moveTo(int x, int y) { - record("moveTo", new Object[] {new Integer(x), new Integer(y)}, + record("moveTo", new Object[] {Integer.valueOf(x), Integer.valueOf(y)}, new Class[] {int.class, int.class}); proc.moveTo(x, y); } public void multiply(double value) { - record("multiply", new Double(value), double.class); + record("multiply", Double.valueOf(value), double.class); proc.multiply(value); } public void noise(double range) { - record("noise", new Double(range), double.class); + record("noise", Double.valueOf(range), double.class); proc.noise(range); } public void or(int value) { - record("or", new Integer(value), int.class); + record("or", Integer.valueOf(value), int.class); proc.or(value); } public void putColumn(int x, int y, int[] data, int length) { - record("putColumn", new Object[] {new Integer(x), new Integer(y), data, - new Integer(length)}, new Class[] {int.class, int.class, int[].class, + record("putColumn", new Object[] {Integer.valueOf(x), Integer.valueOf(y), data, + Integer.valueOf(length)}, new Class[] {int.class, int.class, int[].class, int.class}); proc.putColumn(x, y, data, length); } public void putPixel(int x, int y, int value) { - record("putPixel", new Object[] {new Integer(x), new Integer(y), - new Integer(value)}, new Class[] {int.class, int.class, int.class}); + record("putPixel", new Object[] {Integer.valueOf(x), Integer.valueOf(y), + Integer.valueOf(value)}, new Class[] {int.class, int.class, int.class}); proc.putPixel(x, y, value); } public void putPixel(int x, int y, int[] iArray) { - record("putPixel", new Object[] {new Integer(x), new Integer(y), iArray}, + record("putPixel", new Object[] {Integer.valueOf(x), Integer.valueOf(y), iArray}, new Class[] {int.class, int.class, int[].class}); proc.putPixel(x, y, iArray); } public void putPixelValue(int x, int y, double value) { - record("putPixelValue", new Object[] {new Integer(x), new Integer(y), - new Double(value)}, new Class[] {int.class, int.class, double.class}); + record("putPixelValue", new Object[] {Integer.valueOf(x), Integer.valueOf(y), + Double.valueOf(value)}, new Class[] {int.class, int.class, double.class}); proc.putPixelValue(x, y, value); } public void putRow(int x, int y, int[] data, int length) { - record("putRow", new Object[] {new Integer(x), new Integer(y), data, - new Integer(length)}, new Class[] {int.class, int.class, int[].class, + record("putRow", new Object[] {Integer.valueOf(x), Integer.valueOf(y), data, + Integer.valueOf(length)}, new Class[] {int.class, int.class, int[].class, int.class}); proc.putRow(x, y, data, length); } @@ -911,18 +911,18 @@ public void resetThreshold() { } public ImageProcessor resize(int dstWidth) { - record("resize", new Integer(dstWidth), int.class); + record("resize", Integer.valueOf(dstWidth), int.class); return proc.resize(dstWidth); } public ImageProcessor resize(int dstWidth, int dstHeight) { - record("resize", new Object[] {new Integer(dstWidth), - new Integer(dstHeight)}, new Class[] {int.class, int.class}); + record("resize", new Object[] {Integer.valueOf(dstWidth), + Integer.valueOf(dstHeight)}, new Class[] {int.class, int.class}); return proc.resize(dstWidth, dstHeight); } public void rotate(double angle) { - record("rotate", new Double(angle), double.class); + record("rotate", Double.valueOf(angle), double.class); proc.rotate(angle); } @@ -937,36 +937,36 @@ public ImageProcessor rotateRight() { } public void scale(double xScale, double yScale) { - record("scale", new Object[] {new Double(xScale), new Double(yScale)}, + record("scale", new Object[] {Double.valueOf(xScale), Double.valueOf(yScale)}, new Class[] {double.class, double.class}); proc.scale(xScale, yScale); } public void set(int index, int value) { - record("set", new Object[] {new Integer(index), new Integer(value)}, + record("set", new Object[] {Integer.valueOf(index), Integer.valueOf(value)}, new Class[] {int.class, int.class}); proc.set(index, value); } public void set(int x, int y, int value) { - record("set", new Object[] {new Integer(x), new Integer(y), - new Integer(value)}, new Class[] {int.class, int.class, int.class}); + record("set", new Object[] {Integer.valueOf(x), Integer.valueOf(y), + Integer.valueOf(value)}, new Class[] {int.class, int.class, int.class}); proc.set(x, y, value); } public void setAntialiasedText(boolean antialiased) { - record("setAntialiasedText", new Boolean(antialiased), boolean.class); + record("setAntialiasedText", Boolean.valueOf(antialiased), boolean.class); proc.setAntialiasedText(antialiased); } public void setAutoThreshold(int method, int lutUpdate) { - record("setAutoThreshold", new Object[] {new Integer(method), - new Integer(lutUpdate)}, new Class[] {int.class, int.class}); + record("setAutoThreshold", new Object[] {Integer.valueOf(method), + Integer.valueOf(lutUpdate)}, new Class[] {int.class, int.class}); proc.setAutoThreshold(method, lutUpdate); } public void setBackgroundValue(double value) { - record("setBackgroundValue", new Double(value), double.class); + record("setBackgroundValue", Double.valueOf(value), double.class); proc.setBackgroundValue(value); } @@ -986,7 +986,7 @@ public void setColor(Color color) { } public void setColor(int value) { - record("setColor", new Integer(value), int.class); + record("setColor", Integer.valueOf(value), int.class); proc.setColor(value); } @@ -996,14 +996,14 @@ public void setColorModel(ColorModel cm) { } public void setf(int index, float value) { - record("setf", new Object[] {new Integer(index), new Float(value)}, + record("setf", new Object[] {Integer.valueOf(index), Float.valueOf(value)}, new Class[] {int.class, float.class}); proc.setf(index, value); } public void setf(int x, int y, float value) { - record("setf", new Object[] {new Integer(x), new Integer(y), - new Float(value)}, new Class[] {int.class, int.class, float.class}); + record("setf", new Object[] {Integer.valueOf(x), Integer.valueOf(y), + Float.valueOf(value)}, new Class[] {int.class, int.class, float.class}); proc.setf(x, y, value); } @@ -1018,13 +1018,13 @@ public void setFont(Font font) { } public void setHistogramRange(double histMin, double histMax) { - record("setHistogramRange", new Object[] {new Double(histMin), - new Double(histMax)}, new Class[] {double.class, double.class}); + record("setHistogramRange", new Object[] {Double.valueOf(histMin), + Double.valueOf(histMax)}, new Class[] {double.class, double.class}); proc.setHistogramRange(histMin, histMax); } public void setHistogramSize(int size) { - record("setHistogramSize", new Integer(size), int.class); + record("setHistogramSize", Integer.valueOf(size), int.class); proc.setHistogramSize(size); } @@ -1034,22 +1034,22 @@ public void setIntArray(int[][] a) { } public void setInterpolate(boolean interpolate) { - record("setInterpolate", new Boolean(interpolate), boolean.class); + record("setInterpolate", Boolean.valueOf(interpolate), boolean.class); proc.setInterpolate(interpolate); } public void setJustification(int justification) { - record("setJustification", new Integer(justification), int.class); + record("setJustification", Integer.valueOf(justification), int.class); proc.setJustification(justification); } public void setLineWidth(int width) { - record("setLineWidth", new Integer(width), int.class); + record("setLineWidth", Integer.valueOf(width), int.class); proc.setLineWidth(width); } public void setLutAnimation(boolean lutAnimation) { - record("setLutAnimation", new Boolean(lutAnimation), boolean.class); + record("setLutAnimation", Boolean.valueOf(lutAnimation), boolean.class); proc.setLutAnimation(lutAnimation); } @@ -1059,13 +1059,13 @@ public void setMask(ImageProcessor mask) { } public void setMinAndMax(double min, double max) { - record("setMinAndMax", new Object[] {new Double(min), new Double(max)}, + record("setMinAndMax", new Object[] {Double.valueOf(min), Double.valueOf(max)}, new Class[] {double.class, double.class}); proc.setMinAndMax(min, max); } public void setPixels(int channelNumber, FloatProcessor fp) { - record("setPixels", new Object[] {new Integer(channelNumber), fp}, + record("setPixels", new Object[] {Integer.valueOf(channelNumber), fp}, new Class[] {int.class, FloatProcessor.class}); proc.setPixels(channelNumber, fp); } @@ -1081,8 +1081,8 @@ public void setProgressBar(ProgressBar pb) { } public void setRoi(int x, int y, int rwidth, int rheight) { - record("setRoi", new Object[] {new Integer(x), new Integer(y), - new Integer(rwidth), new Integer(rheight)}, new Class[] {int.class, + record("setRoi", new Object[] {Integer.valueOf(x), Integer.valueOf(y), + Integer.valueOf(rwidth), Integer.valueOf(rheight)}, new Class[] {int.class, int.class, int.class, int.class}); proc.setRoi(x, y, rwidth, rheight); } @@ -1103,7 +1103,7 @@ public void setRoi(Roi roi) { } public void setSnapshotCopyMode(boolean b) { - record("setSnapshotCopyMode", new Boolean(b), boolean.class); + record("setSnapshotCopyMode", Boolean.valueOf(b), boolean.class); proc.setSnapshotCopyMode(b); } @@ -1115,14 +1115,14 @@ public void setSnapshotPixels(Object pixels) { public void setThreshold(double minThreshold, double maxThreshold, int lutUpdate) { - record("setThreshold", new Object[] {new Double(minThreshold), - new Double(maxThreshold), new Integer(lutUpdate)}, + record("setThreshold", new Object[] {Double.valueOf(minThreshold), + Double.valueOf(maxThreshold), Integer.valueOf(lutUpdate)}, new Class[] {double.class, double.class, int.class}); proc.setThreshold(minThreshold, maxThreshold, lutUpdate); } public void setValue(double value) { - record("setValue", new Double(value), double.class); + record("setValue", Double.valueOf(value), double.class); proc.setValue(value); } @@ -1157,12 +1157,12 @@ public void swapPixelArrays() { } public void threshold(int level) { - record("threshold", new Integer(level), int.class); + record("threshold", Integer.valueOf(level), int.class); proc.threshold(level); } public FloatProcessor toFloat(int channelNumber, FloatProcessor fp) { - record("toFloat", new Object[] {new Integer(channelNumber), fp}, + record("toFloat", new Object[] {Integer.valueOf(channelNumber), fp}, new Class[] {int.class, FloatProcessor.class}); return proc.toFloat(channelNumber, fp); } @@ -1174,19 +1174,19 @@ public String toString() { public void translate(int xOffset, int yOffset) { record("translate", - new Object[] {new Integer(xOffset), new Integer(yOffset)}, + new Object[] {Integer.valueOf(xOffset), Integer.valueOf(yOffset)}, new Class[] {int.class, int.class}); proc.translate(xOffset, yOffset); } public void updateComposite(int[] rgbPixels, int channel) { - record("updateComposite", new Object[] {rgbPixels, new Integer(channel)}, + record("updateComposite", new Object[] {rgbPixels, Integer.valueOf(channel)}, new Class[] {int[].class, int.class}); proc.updateComposite(rgbPixels, channel); } public void xor(int value) { - record("xor", new Integer(value), int.class); + record("xor", Integer.valueOf(value), int.class); proc.xor(value); } diff --git a/components/bio-formats-tools/pom.xml b/components/bio-formats-tools/pom.xml index 7bf17d46f04..6f69965f018 100644 --- a/components/bio-formats-tools/pom.xml +++ b/components/bio-formats-tools/pom.xml @@ -8,7 +8,7 @@ ome pom-bio-formats - 8.0.0-SNAPSHOT + 8.1.0-SNAPSHOT ../.. diff --git a/components/bio-formats-tools/src/loci/formats/tools/ImageConverter.java b/components/bio-formats-tools/src/loci/formats/tools/ImageConverter.java index 8f1c3816929..77d0c2b316c 100644 --- a/components/bio-formats-tools/src/loci/formats/tools/ImageConverter.java +++ b/components/bio-formats-tools/src/loci/formats/tools/ImageConverter.java @@ -41,6 +41,7 @@ import java.io.IOException; import java.util.Iterator; import java.util.HashMap; +import java.util.List; import java.util.TreeMap; import java.util.SortedMap; @@ -61,6 +62,7 @@ import loci.formats.FileStitcher; import loci.formats.FormatException; import loci.formats.FormatTools; +import loci.formats.ICompressedTileReader; import loci.formats.IFormatReader; import loci.formats.IFormatWriter; import loci.formats.ImageReader; @@ -70,6 +72,10 @@ import loci.formats.MetadataTools; import loci.formats.MinMaxCalculator; import loci.formats.MissingLibraryException; +import loci.formats.codec.Codec; +import loci.formats.codec.CodecOptions; +import loci.formats.codec.CompressionType; +import loci.formats.codec.JPEG2000CodecOptions; import loci.formats.gui.Index16ColorModel; import loci.formats.in.DynamicMetadataOptions; import loci.formats.meta.IMetadata; @@ -84,6 +90,7 @@ import loci.formats.services.OMEXMLServiceImpl; import ome.xml.meta.OMEXMLMetadataRoot; +import ome.xml.model.Channel; import ome.xml.model.Image; import ome.xml.model.Pixels; import ome.xml.model.enums.PixelType; @@ -133,6 +140,8 @@ public final class ImageConverter { private boolean precompressed = false; private boolean tryPrecompressed = false; + private Double compressionQuality = null; + private String extraMetadata = null; private IFormatReader reader; @@ -273,6 +282,9 @@ else if (args[i].equals("-fill")) { else if (args[i].equals("-extra-metadata")) { extraMetadata = args[++i]; } + else if (args[i].equals("-quality")) { + compressionQuality = DataTools.parseDouble(args[++i]); + } else if (!args[i].equals(CommandLineTools.NO_UPGRADE_CHECK)) { LOGGER.error("Found unknown command flag: {}; exiting.", args[i]); return false; @@ -349,7 +361,7 @@ private void printUsage() { " [-option key value] [-novalid] [-validate] [-tilex tileSizeX]", " [-tiley tileSizeY] [-pyramid-scale scale]", " [-swap dimensionsOrderString] [-fill color]", - " [-precompressed]", + " [-precompressed] [-quality compressionQuality]", " [-pyramid-resolutions numResolutionLevels] in_file out_file", "", " -version: print the library version and exit", @@ -398,6 +410,7 @@ private void printUsage() { " Most input and output formats do not support this option.", " Do not use -crop, -fill, or -autoscale, or pyramid generation options", " with this option.", + " -quality: double quality value for JPEG compression (0-1)", "", "The extension of the output file specifies the file format to use", "for the conversion. The list of available formats and extensions is:", @@ -548,6 +561,11 @@ public boolean testConvert(IFormatWriter writer, String[] args) reader.setId(in); + if (compression == null && precompressed) { + compression = getReaderCodecName(); + LOGGER.info("Implicitly using compression = {}", compression); + } + if (swapOrder != null) { dimSwapper.swapDimensions(swapOrder); } @@ -591,11 +609,22 @@ public boolean testConvert(IFormatWriter writer, String[] args) String xml = service.getOMEXML(service.asRetrieve(store)); OMEXMLMetadataRoot root = (OMEXMLMetadataRoot) store.getRoot(); IMetadata meta = service.createOMEXMLMetadata(xml); + OMEXMLMetadataRoot newRoot = (OMEXMLMetadataRoot) meta.getRoot(); if (series >= 0) { - Image exportImage = new Image(root.getImage(series)); - Pixels exportPixels = new Pixels(root.getImage(series).getPixels()); + Image exportImage = newRoot.getImage(series); + Pixels exportPixels = newRoot.getImage(series).getPixels(); + + if (channel >= 0) { + List channels = exportPixels.copyChannelList(); + + for (int c=0; c 0) { newRoot.removeImage(newRoot.getImage(0)); } @@ -639,6 +668,17 @@ public boolean testConvert(IFormatWriter writer, String[] args) store.setPixelsType(PixelType.UINT8, i); } + if (channel >= 0) { + Pixels exportPixels = newRoot.getImage(i).getPixels(); + List channels = exportPixels.copyChannelList(); + + for (int c=0; c= 0) { meta.setPixelsSizeC(new PositiveInteger(1), i); } @@ -727,7 +767,9 @@ else if (writer instanceof ImageWriter) { int writerSeries = series == -1 ? q : 0; writer.setSeries(writerSeries); writer.setResolution(res); + writer.setInterleaved(reader.isInterleaved() && !autoscale); + writer.setValidBitsPerPixel(reader.getBitsPerPixel()); int numImages = writer.canDoStacks() ? reader.getImageCount() : 1; @@ -774,6 +816,7 @@ else if (saveTileWidth > 0 && saveTileHeight > 0) { if (!ok) { return false; } + setCodecOptions(writer); writer.setId(outputName); if (compression != null) writer.setCompression(compression); } @@ -793,11 +836,18 @@ else if (saveTileWidth > 0 && saveTileHeight > 0) { if (!ok) { return false; } + setCodecOptions(writer); writer.setId(tileName); if (compression != null) writer.setCompression(compression); } } + if (precompressed && FormatTools.canUsePrecompressedTiles(reader, writer, writer.getSeries(), writer.getResolution())) { + if (getReaderCodecName().startsWith("JPEG")) { + writer.setInterleaved(true); + } + } + int outputIndex = 0; if (nextOutputIndex.containsKey(outputName)) { outputIndex = nextOutputIndex.get(outputName); @@ -995,6 +1045,7 @@ private long convertTilePlane(IFormatWriter writer, int index, int outputIndex, writer.setMetadataRetrieve(retrieve); overwriteCheck(tileName, true); + setCodecOptions(writer); writer.setId(tileName); if (compression != null) writer.setCompression(compression); @@ -1225,11 +1276,21 @@ private boolean isTiledWriter(IFormatWriter writer, String outputFile) private boolean doTileConversion(IFormatWriter writer, String outputFile) throws FormatException { - if (writer instanceof DicomWriter || - (writer instanceof ImageWriter && ((ImageWriter) writer).getWriter(outputFile) instanceof DicomWriter)) + // if we asked to try a precompressed conversion, + // then the writer's tile sizes will have been set automatically + // according to the input data + // the conversion must then be performed tile-wise to match the tile sizes, + // even if precompression doesn't end up being possible + if (precompressed) { + return true; + } + // tile size has already been set in the writer, + // so tile-wise conversion should be performed + // independent of image size + if ((writer.getTileSizeX() > 0 && writer.getTileSizeX() < width) || + (writer.getTileSizeY() > 0 && writer.getTileSizeY() < height)) { - MetadataStore r = reader.getMetadataStore(); - return !(r instanceof IPyramidStore) || ((IPyramidStore) r).getResolutionCount(reader.getSeries()) > 1; + return true; } return DataTools.safeMultiply64(width, height) >= DataTools.safeMultiply64(4096, 4096) || saveTileWidth > 0 || saveTileHeight > 0; @@ -1267,6 +1328,26 @@ private boolean overwriteCheck(String path, boolean throwOnExist) throws IOExcep return true; } + private void setCodecOptions(IFormatWriter writer) { + if (compressionQuality != null) { + CodecOptions codecOptions = JPEG2000CodecOptions.getDefaultOptions(); + codecOptions.quality = compressionQuality; + writer.setCodecOptions(codecOptions); + } + } + + private String getReaderCodecName() throws FormatException, IOException { + if (reader instanceof ICompressedTileReader) { + ICompressedTileReader r = (ICompressedTileReader) reader; + Codec c = r.getTileCodec(0); + CompressionType type = CompressionType.get(c); + if (type != null) { + return type.getCompression(); + } + } + return null; + } + // -- Main method -- public static void main(String[] args) throws FormatException, IOException { diff --git a/components/bio-formats-tools/src/loci/formats/tools/ImageInfo.java b/components/bio-formats-tools/src/loci/formats/tools/ImageInfo.java index e52ccfcdc76..9a2e93f564b 100644 --- a/components/bio-formats-tools/src/loci/formats/tools/ImageInfo.java +++ b/components/bio-formats-tools/src/loci/formats/tools/ImageInfo.java @@ -37,6 +37,9 @@ import java.io.File; import java.util.Hashtable; import java.util.StringTokenizer; +import java.util.Scanner; +import java.util.Arrays; +import java.util.List; import loci.common.ByteArrayHandle; import loci.common.DataTools; @@ -311,6 +314,8 @@ public void printUsage() { "", " -version: print the library version and exit", " file: the image file to read", + " if - is passed, process multiple files", + " with file names read line-wise from stdin", " -nopix: read metadata only, not pixels", " -nocore: do not output core metadata", " -nometa: do not parse format-specific metadata table", @@ -367,7 +372,7 @@ public void createReader() { // create reader of a specific format type try { Class c = Class.forName("loci.formats.in." + format + "Reader"); - reader = (IFormatReader) c.newInstance(); + reader = (IFormatReader) c.getDeclaredConstructor().newInstance(); } catch (ClassNotFoundException exc) { LOGGER.warn("Unknown reader: {}", format); @@ -377,7 +382,7 @@ public void createReader() { LOGGER.warn("Cannot instantiate reader: {}", format); LOGGER.debug("", exc); } - catch (IllegalAccessException exc) { + catch (ReflectiveOperationException exc) { LOGGER.warn("Cannot access reader: {}", format); LOGGER.debug("", exc); } @@ -1126,7 +1131,34 @@ private void printDimension(String dim, int size, int effectiveSize, public static void main(String[] args) throws Exception { DebugTools.enableLogging("INFO"); - if (!new ImageInfo().testRead(args)) System.exit(1); - } + int exitCode = 0; + List argsList = Arrays.asList(args); + int idx = argsList.indexOf("-"); + + if (idx >= 0) { + Scanner scanner = new Scanner(System.in); + String[] newArgs = argsList.toArray(new String[0]); + + while (scanner.hasNext()) { + newArgs[idx] = scanner.nextLine(); + System.out.println("====% " + newArgs[idx]); + try { + new ImageInfo().testRead(newArgs); + } + catch (Exception e) { + LOGGER.error("Caught " + e.getClass().getSimpleName(), e); + exitCode = 1; + continue; + } + } + scanner.close(); + } + else { + if (!new ImageInfo().testRead(args)) System.exit(1); + } + + System.exit(exitCode); + } } + diff --git a/components/bio-formats-tools/test/loci/formats/tools/ImageConverterTest.java b/components/bio-formats-tools/test/loci/formats/tools/ImageConverterTest.java index f7a3d0ba913..29f1a4c995b 100644 --- a/components/bio-formats-tools/test/loci/formats/tools/ImageConverterTest.java +++ b/components/bio-formats-tools/test/loci/formats/tools/ImageConverterTest.java @@ -42,17 +42,21 @@ import java.util.ArrayList; import java.util.Arrays; +import loci.common.services.ServiceFactory; import loci.formats.ClassList; import loci.formats.IFormatReader; import loci.formats.ImageReader; import loci.formats.ImageWriter; import loci.formats.FormatException; +import loci.formats.meta.IMetadata; import loci.formats.tools.ImageConverter; import loci.formats.in.ICSReader; import loci.formats.in.OMETiffReader; import loci.formats.in.TiffDelegateReader; import loci.formats.in.TiffReader; import loci.formats.out.OMETiffWriter; +import loci.formats.services.OMEXMLService; +import loci.formats.tiff.TiffParser; import org.apache.commons.lang.ArrayUtils; import org.testng.annotations.AfterClass; @@ -369,6 +373,27 @@ public void testConvertResolutions() throws FormatException, IOException { assertConversion(args); } + @Test + public void testConvertSingleChannel() throws FormatException, IOException { + outFile = getOutFile("single-channel.ome.tiff"); + String[] args = { + "single-channel&sizeC=3.fake", "-channel", "1", outFile.getAbsolutePath() + }; + assertConversion(args); + + try (TiffParser parser = new TiffParser(outFile.getAbsolutePath())) { + String comment = parser.getComment(); + + final OMEXMLService service = + new ServiceFactory().getInstance(OMEXMLService.class); + IMetadata meta = service.createOMEXMLMetadata(comment); + assertEquals(meta.getChannelCount(0), 1); + } + catch (Exception e) { + throw new FormatException(e); + } + } + private Path getTempSubdir() throws IOException { Path subdir = Files.createTempDirectory(tempDir, "ImageConverterTest"); subdir.toFile().deleteOnExit(); diff --git a/components/bundles/bioformats_package/pom.xml b/components/bundles/bioformats_package/pom.xml index 74c06caa741..9f9e6a56b55 100644 --- a/components/bundles/bioformats_package/pom.xml +++ b/components/bundles/bioformats_package/pom.xml @@ -8,7 +8,7 @@ ome pom-bio-formats - 8.0.0-SNAPSHOT + 8.1.0-SNAPSHOT ../../../ diff --git a/components/forks/turbojpeg/pom.xml b/components/forks/turbojpeg/pom.xml index c7806a96dfd..d3c86cc6bb7 100644 --- a/components/forks/turbojpeg/pom.xml +++ b/components/forks/turbojpeg/pom.xml @@ -8,7 +8,7 @@ ome pom-bio-formats - 8.0.0-SNAPSHOT + 8.1.0-SNAPSHOT ../../../ diff --git a/components/formats-api/pom.xml b/components/formats-api/pom.xml index 760c677c14b..ac13b855ca9 100644 --- a/components/formats-api/pom.xml +++ b/components/formats-api/pom.xml @@ -8,7 +8,7 @@ ome pom-bio-formats - 8.0.0-SNAPSHOT + 8.1.0-SNAPSHOT ../.. diff --git a/components/formats-api/src/loci/formats/ICompressedTileReader.java b/components/formats-api/src/loci/formats/ICompressedTileReader.java index b90fc44a4d0..ad7baee3b7c 100644 --- a/components/formats-api/src/loci/formats/ICompressedTileReader.java +++ b/components/formats-api/src/loci/formats/ICompressedTileReader.java @@ -66,7 +66,7 @@ default int getTileColumns(int no) { * * @param no plane index * @param x tile X index (indexed from 0, @see getTileColumns(int)) - * @param y tile Y index (indexed frmo 0, @see getTileRows(int)) + * @param y tile Y index (indexed from 0, @see getTileRows(int)) * @return compressed tile bytes */ default byte[] openCompressedBytes(int no, int x, int y) throws FormatException, IOException { @@ -79,7 +79,7 @@ default byte[] openCompressedBytes(int no, int x, int y) throws FormatException, * @param no plane index * @param buf pre-allocated buffer in which to store compressed bytes * @param x tile X index (indexed from 0, @see getTileColumns(int)) - * @param y tile Y index (indexed frmo 0, @see getTileRows(int)) + * @param y tile Y index (indexed from 0, @see getTileRows(int)) * @return compressed tile bytes */ default byte[] openCompressedBytes(int no, byte[] buf, int x, int y) throws FormatException, IOException { @@ -102,7 +102,7 @@ default Codec getTileCodec(int no) throws FormatException, IOException { * * @param no plane index * @param x tile X index (indexed from 0, @see getTileColumns(int)) - * @param y tile Y index (indexed frmo 0, @see getTileRows(int)) + * @param y tile Y index (indexed from 0, @see getTileRows(int)) * @return codec options * @see getTileCodec(int) */ diff --git a/components/formats-api/src/loci/formats/ImageReader.java b/components/formats-api/src/loci/formats/ImageReader.java index 68e02c481fa..9a87aeec5c4 100644 --- a/components/formats-api/src/loci/formats/ImageReader.java +++ b/components/formats-api/src/loci/formats/ImageReader.java @@ -134,11 +134,10 @@ public ImageReader(ClassList classList) { for (int i=0; i classList) { for (int i=0; i ome pom-bio-formats - 8.0.0-SNAPSHOT + 8.1.0-SNAPSHOT ../.. diff --git a/components/formats-bsd/src/loci/formats/FilePattern.java b/components/formats-bsd/src/loci/formats/FilePattern.java index d831dbf9a8b..1bc9f12349e 100644 --- a/components/formats-bsd/src/loci/formats/FilePattern.java +++ b/components/formats-bsd/src/loci/formats/FilePattern.java @@ -162,13 +162,13 @@ public FilePattern(String pattern) { while (true) { left = pattern.indexOf(FilePatternBlock.BLOCK_START, left + 1); if (left < 0) break; - lt.add(new Integer(left)); + lt.add(left); } int right = -1; while (true) { right = pattern.indexOf(FilePatternBlock.BLOCK_END, right + 1); if (right < 0) break; - gt.add(new Integer(right)); + gt.add(right); } // assemble numerical block indices diff --git a/components/formats-bsd/src/loci/formats/ImageTools.java b/components/formats-bsd/src/loci/formats/ImageTools.java index 70f488f5dc9..f15bb1c70d2 100644 --- a/components/formats-bsd/src/loci/formats/ImageTools.java +++ b/components/formats-bsd/src/loci/formats/ImageTools.java @@ -118,7 +118,7 @@ public static int[] make24Bits(Object pixels, int w, int h, if (pixels instanceof byte[]) b = (byte[]) pixels; else if (pixels instanceof short[]) { - if (max == null) max = new Double(0xffff); + if (max == null) max = Double.valueOf(0xffff); double range = max.doubleValue() - min.doubleValue(); double mult = newRange / range; @@ -129,7 +129,7 @@ else if (pixels instanceof short[]) { } } else if (pixels instanceof int[]) { - if (max == null) max = new Double(0xffffffffL); + if (max == null) max = Double.valueOf(0xffffffffL); double range = max.doubleValue() - min.doubleValue(); double mult = newRange / range; @@ -140,7 +140,7 @@ else if (pixels instanceof int[]) { } } else if (pixels instanceof float[]) { - if (max == null) max = new Double(Float.MAX_VALUE); + if (max == null) max = Double.valueOf(Float.MAX_VALUE); double range = max.doubleValue() - min.doubleValue(); double mult = newRange / range; @@ -151,7 +151,7 @@ else if (pixels instanceof float[]) { } } else if (pixels instanceof double[]) { - if (max == null) max = new Double(Double.MAX_VALUE); + if (max == null) max = Double.MAX_VALUE; double range = max.doubleValue() - min.doubleValue(); double mult = newRange / range; @@ -517,8 +517,8 @@ else if (bits == 32) { } Double[] rtn = new Double[2]; - rtn[0] = new Double(min); - rtn[1] = new Double(max); + rtn[0] = Double.valueOf(min); + rtn[1] = Double.valueOf(max); return rtn; } diff --git a/components/formats-bsd/src/loci/formats/MinMaxCalculator.java b/components/formats-bsd/src/loci/formats/MinMaxCalculator.java index 6cabd84fa8a..57c88324b6c 100644 --- a/components/formats-bsd/src/loci/formats/MinMaxCalculator.java +++ b/components/formats-bsd/src/loci/formats/MinMaxCalculator.java @@ -119,7 +119,7 @@ public Double getChannelGlobalMinimum(int theC) if (minMaxDone == null || minMaxDone[series] < getImageCount()) { return null; } - return new Double(chanMin[series][theC]); + return chanMin[series][theC]; } /** @@ -141,7 +141,7 @@ public Double getChannelGlobalMaximum(int theC) if (minMaxDone == null || minMaxDone[series] < getImageCount()) { return null; } - return new Double(chanMax[series][theC]); + return chanMax[series][theC]; } /** @@ -155,7 +155,7 @@ public Double getChannelKnownMinimum(int theC) throws FormatException, IOException { FormatTools.assertId(getCurrentFile(), true, 2); - return chanMin == null ? null : new Double(chanMin[getCoreIndex()][theC]); + return chanMin == null ? null : chanMin[getCoreIndex()][theC]; } /** @@ -169,7 +169,7 @@ public Double getChannelKnownMaximum(int theC) throws FormatException, IOException { FormatTools.assertId(getCurrentFile(), true, 2); - return chanMax == null ? null : new Double(chanMax[getCoreIndex()][theC]); + return chanMax == null ? null : chanMax[getCoreIndex()][theC]; } /** @@ -192,7 +192,7 @@ public Double[] getPlaneMinimum(int no) throws FormatException, IOException { Double[] min = new Double[numRGB]; for (int c=0; c> 16) & 0xffff; + int lowWord = tag & 0xffff; + return highWord % 2 == 1 && lowWord == 0x0010; + } + @Override public String toString() { if (key == null) { diff --git a/components/formats-bsd/src/loci/formats/gui/AWTImageTools.java b/components/formats-bsd/src/loci/formats/gui/AWTImageTools.java index 791fd4a2b02..4de6cafd205 100644 --- a/components/formats-bsd/src/loci/formats/gui/AWTImageTools.java +++ b/components/formats-bsd/src/loci/formats/gui/AWTImageTools.java @@ -1655,7 +1655,7 @@ else if (pixels instanceof int[][]) { else if (ints[i][j] <= min) out[i][j] = 0; else { int diff = max - min; - float dist = (ints[i][j] - min) / diff; + float dist = (float) (ints[i][j] - min) / diff; out[i][j] = (byte) (dist * 256); } } diff --git a/components/formats-bsd/src/loci/formats/gui/CacheComponent.java b/components/formats-bsd/src/loci/formats/gui/CacheComponent.java index 7007e04bce5..beea31e84fc 100644 --- a/components/formats-bsd/src/loci/formats/gui/CacheComponent.java +++ b/components/formats-bsd/src/loci/formats/gui/CacheComponent.java @@ -314,7 +314,7 @@ public void cacheUpdated(CacheEvent e) { int[] rng = strategy.getRange(); for (int i=0; i 0 || bmpCompression != 0) { - offsets.add(new Long(in.getFilePointer())); - lengths.add(new Long(size)); + offsets.add(in.getFilePointer()); + lengths.add(Long.valueOf(size)); in.skipBytes(size); } } @@ -878,9 +878,9 @@ else if (type.length() < 4 || type.endsWith("JUN")) { offsets.add(offsets.get(offsets.size() - 1)); } else if (chunkSize > 0 || offsets.size() > 0) { - offsets.add(new Long(useSOM ? startOfMovi + offset : offset)); + offsets.add(Long.valueOf(useSOM ? startOfMovi + offset : offset)); } - lengths.add(new Long(chunkSize)); + lengths.add(Long.valueOf(chunkSize)); } } } diff --git a/components/formats-bsd/src/loci/formats/in/BaseTiffReader.java b/components/formats-bsd/src/loci/formats/in/BaseTiffReader.java index a2de3c8412d..0900e921c26 100644 --- a/components/formats-bsd/src/loci/formats/in/BaseTiffReader.java +++ b/components/formats-bsd/src/loci/formats/in/BaseTiffReader.java @@ -566,14 +566,14 @@ protected void put(String key, int value) { } protected void put(String key, boolean value) { - put(key, new Boolean(value)); + put(key, Boolean.valueOf(value)); } - protected void put(String key, byte value) { put(key, new Byte(value)); } - protected void put(String key, char value) { put(key, new Character(value)); } - protected void put(String key, double value) { put(key, new Double(value)); } - protected void put(String key, float value) { put(key, new Float(value)); } - protected void put(String key, long value) { put(key, new Long(value)); } - protected void put(String key, short value) { put(key, new Short(value)); } + protected void put(String key, byte value) { put(key, Byte.valueOf(value)); } + protected void put(String key, char value) { put(key, Character.valueOf(value)); } + protected void put(String key, double value) { put(key, Double.valueOf(value)); } + protected void put(String key, float value) { put(key, Float.valueOf(value)); } + protected void put(String key, long value) { put(key, Long.valueOf(value)); } + protected void put(String key, short value) { put(key, Short.valueOf(value)); } protected void put(String key, IFD ifd, int tag) { put(key, ifd.getIFDValue(tag)); diff --git a/components/formats-bsd/src/loci/formats/in/DicomReader.java b/components/formats-bsd/src/loci/formats/in/DicomReader.java index aba35119fd4..e3983df677c 100644 --- a/components/formats-bsd/src/loci/formats/in/DicomReader.java +++ b/components/formats-bsd/src/loci/formats/in/DicomReader.java @@ -37,9 +37,11 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; +import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Set; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap.Builder; @@ -61,10 +63,13 @@ import loci.formats.codec.JPEG2000Codec; import loci.formats.codec.JPEGCodec; import loci.formats.codec.PackbitsCodec; +import loci.formats.codec.PassthroughCodec; import loci.formats.meta.MetadataStore; import ome.xml.model.primitives.Timestamp; import ome.units.quantity.Length; import ome.units.UNITS; +import org.perf4j.StopWatch; +import org.perf4j.slf4j.Slf4JStopWatch; import loci.formats.dicom.DicomAttribute; import loci.formats.dicom.DicomFileInfo; @@ -127,6 +132,10 @@ public class DicomReader extends SubResolutionFormatReader { private List tags; + private transient String currentTileFile = null; + private transient RandomAccessInputStream currentTileStream = null; + private Set privateContentHighWords = new HashSet(); + // -- Constructor -- /** Constructs a new DICOM reader. */ @@ -141,6 +150,94 @@ public DicomReader() { hasCompanionFiles = true; } + // -- ICompressedTileReader API methods -- + + @Override + public int getTileRows(int no) { + FormatTools.assertId(currentId, true, 1); + + return (int) Math.ceil((double) getSizeY() / originalY); + } + + @Override + public int getTileColumns(int no) { + FormatTools.assertId(currentId, true, 1); + + return (int) Math.ceil((double) getSizeX() / originalY); + } + + @Override + public byte[] openCompressedBytes(int no, int x, int y) throws FormatException, IOException { + FormatTools.assertId(currentId, true, 1); + + // TODO: this will result in a lot of redundant lookups, and should be optimized + int tileWidth = getOptimalTileWidth(); + int tileHeight = getOptimalTileHeight(); + Region boundingBox = new Region(x * tileWidth, y * tileHeight, tileWidth, tileHeight); + + List tiles = getTileList(no, boundingBox, true); + if (tiles == null || tiles.size() == 0) { + throw new FormatException("Could not find valid tile; no=" + no + ", boundingBox=" + boundingBox); + } + DicomTile tile = tiles.get(0); + byte[] buf = new byte[(int) (tile.endOffset - tile.fileOffset)]; + try (RandomAccessInputStream stream = new RandomAccessInputStream(tile.file)) { + if (tile.fileOffset >= stream.length()) { + LOGGER.error("attempted to read beyond end of file ({}, {})", tile.fileOffset, tile.file); + return buf; + } + LOGGER.debug("reading from offset = {}, file = {}", tile.fileOffset, tile.file); + stream.seek(tile.fileOffset); + stream.read(buf, 0, (int) (tile.endOffset - tile.fileOffset)); + } + return buf; + } + + @Override + public byte[] openCompressedBytes(int no, byte[] buf, int x, int y) throws FormatException, IOException { + FormatTools.assertId(currentId, true, 1); + + Region boundingBox = new Region(x * originalX, y * originalY, originalX, originalY); + + List tiles = getTileList(no, boundingBox, true); + if (tiles == null || tiles.size() == 0) { + throw new FormatException("Could not find valid tile; no=" + no + ", x=" + x + ", y=" + y); + } + DicomTile tile = tiles.get(0); + try (RandomAccessInputStream stream = new RandomAccessInputStream(tile.file)) { + if (tile.fileOffset >= stream.length()) { + LOGGER.error("attempted to read beyond end of file ({}, {})", tile.fileOffset, tile.file); + return buf; + } + LOGGER.debug("reading from offset = {}, file = {}", tile.fileOffset, tile.file); + stream.seek(tile.fileOffset); + stream.read(buf, 0, (int) (tile.endOffset - tile.fileOffset)); + } + return buf; + } + + @Override + public Codec getTileCodec(int no) throws FormatException, IOException { + FormatTools.assertId(currentId, true, 1); + + List tiles = getTileList(no, null, true); + if (tiles == null || tiles.size() == 0) { + throw new FormatException("Could not find valid tile; no=" + no); + } + return getTileCodec(tiles.get(0)); + } + + @Override + public CodecOptions getTileCodecOptions(int no, int x, int y) throws FormatException, IOException { + FormatTools.assertId(currentId, true, 1); + + List tiles = getTileList(no, null, true); + if (tiles == null || tiles.size() == 0) { + throw new FormatException("Could not find valid tile; no=" + no + ", x=" + x + ", y=" + y); + } + return getTileCodecOptions(tiles.get(0)); + } + // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#isThisType(String, boolean) */ @@ -246,7 +343,10 @@ public int fileGroupOption(String id) throws FormatException, IOException { public int getOptimalTileWidth() { FormatTools.assertId(currentId, true, 1); if (tilePositions.containsKey(getCoreIndex())) { - return tilePositions.get(getCoreIndex()).get(0).region.width; + List tile = getTileList(0, null, true); + if (tile != null && tile.size() >= 1) { + return tile.get(0).region.width; + } } if (originalX < getSizeX() && originalX > 0) { return originalX; @@ -258,7 +358,10 @@ public int getOptimalTileWidth() { public int getOptimalTileHeight() { FormatTools.assertId(currentId, true, 1); if (tilePositions.containsKey(getCoreIndex())) { - return tilePositions.get(getCoreIndex()).get(0).region.height; + List tile = getTileList(0, null, true); + if (tile != null && tile.size() >= 1) { + return tile.get(0).region.height; + } } if (originalY < getSizeY() && originalY > 0) { return originalY; @@ -275,40 +378,34 @@ public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) { FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h); + StopWatch watch = stopWatch(); + int bpp = FormatTools.getBytesPerPixel(getPixelType()); int pixel = bpp * getRGBChannelCount(); Region currentRegion = new Region(x, y, w, h); - int z = getZCTCoords(no)[0]; - int c = getZCTCoords(no)[1]; - if (!tilePositions.containsKey(getCoreIndex())) { - LOGGER.warn("No tiles for core index = {}", getCoreIndex()); - return buf; - } - - // look for any tiles that match the requested tile and plane - List zs = zOffsets.get(getCoreIndex()); - List tiles = tilePositions.get(getCoreIndex()); - for (int t=0; t tiles = getTileList(no, currentRegion, false); + watch.stop("openBytes setup, w=" + w + ", h=" + h); + watch.start(); + for (DicomTile tile : tiles) { + StopWatch tileWatch = stopWatch(); + byte[] tileBuf = new byte[tile.region.width * tile.region.height * pixel]; + Region intersection = tile.region.intersection(currentRegion); + getTile(tile, tileBuf, intersection.x - tile.region.x, intersection.y - tile.region.y, + intersection.width, intersection.height); + + for (int row=0; row 0; invert the values so that // white -> 255 (or 65535) if (bpp == 1) { @@ -327,6 +424,7 @@ else if (bpp == 2) { DataTools.unpackBytes(maxPixelValue - s, buf, i, 2, little); } } + watch.stop("inverted pixel values"); } // NB: do *not* apply the rescale function @@ -368,6 +466,12 @@ public void close(boolean fileOnly) throws IOException { concatenationNumber = null; edf = false; tags = null; + currentTileFile = null; + if (currentTileStream != null) { + currentTileStream.close(); + } + currentTileStream = null; + privateContentHighWords.clear(); } } @@ -377,6 +481,9 @@ public void close(boolean fileOnly) throws IOException { @Override protected void initFile(String id) throws FormatException, IOException { super.initFile(id); + + StopWatch watch = stopWatch(); + if (in != null) { in.close(); } @@ -384,8 +491,14 @@ protected void initFile(String id) throws FormatException, IOException { in.order(true); CoreMetadata m = core.get(0, 0); + watch.stop("open selected file"); + // look for companion files + watch.start(); attachCompanionFiles(); + watch.stop("companion file scan"); + + watch.start(); m.littleEndian = true; long location = 0; @@ -432,7 +545,9 @@ protected void initFile(String id) throws FormatException, IOException { int opticalChannels = 0; List opticalPathIDs = new ArrayList(); + watch.stop("header check and variable init"); + watch.start(); while (decodingTags) { if (in.getFilePointer() + 4 >= in.length()) { break; @@ -682,9 +797,11 @@ else if (child.attribute == OPTICAL_PATH_DESCRIPTION) { decodingTags = false; } } + watch.stop("tag decoding"); if (imagesPerFile == 0) imagesPerFile = 1; if (new Location(currentId).getName().equals("DICOMDIR")) { + watch.start(); String parent = new Location(currentId).getAbsoluteFile().getParent(); Integer[] fileKeys = fileList.keySet().toArray(new Integer[0]); Arrays.sort(fileKeys); @@ -705,8 +822,10 @@ else if (child.attribute == OPTICAL_PATH_DESCRIPTION) { tilePositions = new HashMap>(); zOffsets = new HashMap>(); core.clear(); + watch.stop("DICOMDIR parsing"); } else { + watch.start(); if (m.sizeZ == 0) { m.sizeZ = 1; } @@ -787,7 +906,10 @@ else if (y + originalY < getSizeY()) { LOGGER.info("Calculating image offsets"); calculatePixelsOffsets(baseOffset); + + watch.stop("tile and dimension calculation"); } + watch.start(); makeFileList(); LOGGER.info("Populating metadata"); @@ -796,6 +918,7 @@ else if (y + originalY < getSizeY()) { Integer[] keys = fileList.keySet().toArray(new Integer[0]); Arrays.sort(keys); + watch.stop("assembled file list"); // at this point, we have a list of all files to be grouped together // and have parsed tags from the current file @@ -804,6 +927,7 @@ else if (y + originalY < getSizeY()) { if (seriesCount > 1) { for (int i=0; i currentFileList = fileList.get(keys[i]); DicomFileInfo fileInfo = createFileInfo(currentFileList.get(0)); zOffsets.put(i, fileInfo.zOffsets); @@ -827,17 +951,22 @@ else if (y + originalY < getSizeY()) { fileInfo.positionZ = z; metadataInfo.add(fileInfo); tilePositions.put(i, positions); + seriesWatch.stop("populated series #" + i); } } else { List allFiles = fileList.get(keys[0]); List infos = new ArrayList(); + StopWatch singleSeriesWatch = stopWatch(); + // parse tags for each file for (String file : allFiles) { DicomFileInfo info = createFileInfo(file); infos.add(info); } + singleSeriesWatch.stop("created " + infos.size() + " file infos"); + singleSeriesWatch.start(); if (infos.size() > 1) { infos.sort(null); @@ -931,8 +1060,11 @@ else if (info.concatenationIndex == 0) { metadataInfo.add(infos.get(0)); zOffsets.put(0, infos.get(0).zOffsets); } + singleSeriesWatch.stop("updated metadata from file infos"); } + watch.start(); + // The metadata store we're working with. MetadataStore store = makeFilterMetadata(); MetadataTools.populatePixels(store, this, true); @@ -1001,6 +1133,7 @@ else if (info.concatenationIndex == 0) { } } setSeries(0); + watch.stop("populated MetadataStore"); } // -- Helper methods -- @@ -1008,6 +1141,7 @@ else if (info.concatenationIndex == 0) { // TODO: target for refactoring, this can possibly be combined with the // tag parsing loop that calls this private void addInfo(DicomTag info) throws IOException { + StopWatch infoWatch = stopWatch(); CoreMetadata m = core.get(0, 0); m.littleEndian = in.isLittleEndian(); @@ -1152,6 +1286,7 @@ else if (infoString.startsWith("MONOCHROME")) { addOriginalMetadata(key, info); } } + infoWatch.stop("addInfo attribute = " + info.attribute); } /** @@ -1168,6 +1303,10 @@ else if (infoString.startsWith("MONOCHROME")) { * rely upon the original metadata table. */ private void addOriginalMetadata(String key, DicomTag info) { + if (info.isPrivateContentCreator()) { + privateContentHighWords.add(info.tag >> 16); + } + if (info.value != null && !(info.value instanceof byte[]) && !(info.value instanceof short[])) { @@ -1179,7 +1318,8 @@ private void addOriginalMetadata(String key, DicomTag info) { } } if (info.attribute != PER_FRAME_FUNCTIONAL_GROUPS_SEQUENCE && - info.attribute != REFERENCED_IMAGE_NAVIGATION_SEQUENCE) + info.attribute != REFERENCED_IMAGE_NAVIGATION_SEQUENCE && + !privateContentHighWords.contains(info.tag >> 16)) { for (DicomTag child : info.children) { String childKey = DicomAttribute.formatTag(child.tag); @@ -1195,6 +1335,7 @@ private void addOriginalMetadata(String key, DicomTag info) { * Build a list of files that belong with the current file. */ private void makeFileList() throws FormatException, IOException { + StopWatch fileScanWatch = stopWatch(); LOGGER.info("Building file list"); if (fileList == null && originalInstance != null && originalDate != null && @@ -1227,11 +1368,13 @@ private void makeFileList() throws FormatException, IOException { } } } + fileScanWatch.stop("finished file scanning"); } else if (fileList == null || !isGroupFiles()) { fileList = new HashMap>(); fileList.put(0, new ArrayList()); fileList.get(0).add(new Location(currentId).getAbsolutePath()); + fileScanWatch.stop("single file, no scanning needed"); } } @@ -1245,6 +1388,7 @@ private void scanDirectory(Location dir, boolean checkSeries) { String[] files = dir.list(true); if (files == null) return; + StopWatch directoryWatch = stopWatch(); Arrays.sort(files); for (String f : files) { String file = new Location(dir, f).getAbsolutePath(); @@ -1253,6 +1397,7 @@ private void scanDirectory(Location dir, boolean checkSeries) addFileToList(file, checkSeries); } } + directoryWatch.stop("scanned directory " + dir); } /** @@ -1261,6 +1406,8 @@ private void scanDirectory(Location dir, boolean checkSeries) private void addFileToList(String file, boolean checkSeries) throws FormatException, IOException { + StopWatch addFileWatch = stopWatch(); + int currentX = 0, currentY = 0; int fileSeries = -1; String thisSpecimen = null; @@ -1341,6 +1488,9 @@ private void addFileToList(String file, boolean checkSeries) } } } + finally { + addFileWatch.stop("checked tags from " + file); + } LOGGER.debug("file = {}", file); LOGGER.debug(" date = {}, originalDate = {}", date, originalDate); @@ -1486,6 +1636,88 @@ private void attachCompanionFiles() throws IOException { } } + private RandomAccessInputStream getStream(String path) throws IOException { + if (path.equals(currentTileFile)) { + return currentTileStream; + } + if (currentTileStream != null) { + currentTileStream.close(); + } + currentTileFile = path; + currentTileStream = new RandomAccessInputStream(path); + return currentTileStream; + } + + /** + * Get a Codec that can be used to decompress the given tile. + */ + private Codec getTileCodec(DicomTile tile) { + Codec codec = new PassthroughCodec(); + if (tile.isRLE) { + codec = new PackbitsCodec(); + } + else if (tile.isJPEG) { + codec = new JPEGCodec(); + } + else if (tile.isJP2K) { + codec = new JPEG2000Codec(); + } + return codec; + } + + /** + * Get a CodecOptions that can be used to decompress the given tile. + */ + private CodecOptions getTileCodecOptions(DicomTile tile) { + CodecOptions options = new CodecOptions(); + options.maxBytes = tile.region.width * tile.region.height; + options.littleEndian = isLittleEndian(); + options.interleaved = isInterleaved(); + + return options; + } + + /** + * Get a list of tiles corresponding to the given plane. + * If the bounding box is not null, then only tiles intersecting with + * the bounding box will be returned. + * If the "firstTileOnly" flag is set, then this will return as soon + * as one matching tile is found. + */ + private List getTileList(int no, Region boundingBox, boolean firstTileOnly) { + int z = getZCTCoords(no)[0]; + int c = getZCTCoords(no)[1]; + + List tileList = new ArrayList(); + if (!tilePositions.containsKey(getCoreIndex())) { + LOGGER.warn("No tiles for core index = {}", getCoreIndex()); + return tileList; + } + + // look for any tiles that match the requested tile and plane + List zs = zOffsets.get(getCoreIndex()); + List tiles = tilePositions.get(getCoreIndex()); + for (int t=0; t= stream.length()) { - LOGGER.error("attempted to read beyond end of file ({}, {})", tile.fileOffset, tile.file); - return; - } - LOGGER.debug("reading from offset = {}, file = {}", tile.fileOffset, tile.file); - stream.seek(tile.fileOffset); - if (tile.isRLE) { - // plane is compressed using run-length encoding - CodecOptions options = new CodecOptions(); - options.maxBytes = tile.region.width * tile.region.height; - for (int c=0; c 1) { - int plane = bytes / (bpp * ec); - byte[][] tmp = new byte[bpp][]; - long start = stream.getFilePointer(); - for (int i=0; i= stream.length()) { + LOGGER.error("attempted to read beyond end of file ({}, {})", tile.fileOffset, tile.file); + return; + } + LOGGER.debug("reading from offset = {}, file = {}", tile.fileOffset, tile.file); + stream.seek(tile.fileOffset); + + Codec codec = getTileCodec(tile); + CodecOptions options = getTileCodecOptions(tile); + + if (tile.isRLE) { + // plane is compressed using run-length encoding + for (int c=0; c 1) { + int plane = bytes / (bpp * ec); + byte[][] tmp = new byte[bpp][]; + long start = stream.getFilePointer(); + for (int i=0; i 0 && tmp[i].length > options.maxBytes) { + stream.seek(start); tmp[i] = codec.decompress(stream, options); - if (i > 0 && tmp[i].length > options.maxBytes) { - stream.seek(start); - tmp[i] = codec.decompress(stream, options); - } - if (!tile.last || i < bpp - 1) { - start = stream.getFilePointer(); - while (stream.read() == 0); - long end = stream.getFilePointer(); - stream.seek(end - 1); - } - } - t = new byte[bytes / ec]; - for (int i=0; i= 0 && (b[pt] != (byte) 0xff || b[pt + 1] != (byte) 0xd9)) { - pt--; - } - if (pt < 0) { - byte[] tmp = b; - b = new byte[tmp.length + 2]; - System.arraycopy(tmp, 0, b, 0, tmp.length); - b[b.length - 2] = (byte) 0xff; - b[b.length - 1] = (byte) 0xd9; - } - else if (pt < b.length - 2) { - byte[] tmp = b; - b = new byte[pt + 2]; - System.arraycopy(tmp, 0, b, 0, b.length); + for (int row=0; row= 0 && (b[pt] != (byte) 0xff || b[pt + 1] != (byte) 0xd9)) { + pt--; + } + if (pt < 0) { + byte[] tmp = b; + b = new byte[tmp.length + 2]; + System.arraycopy(tmp, 0, b, 0, tmp.length); + b[b.length - 2] = (byte) 0xff; + b[b.length - 1] = (byte) 0xd9; + } + else if (pt < b.length - 2) { + byte[] tmp = b; + b = new byte[pt + 2]; + System.arraycopy(tmp, 0, b, 0, b.length); + } - try { - b = codec.decompress(b, options); - } - catch (NullPointerException e) { - LOGGER.debug("Could not read empty or invalid tile", e); - return; - } + try { + b = codec.decompress(b, options); + } + catch (NullPointerException e) { + LOGGER.debug("Could not read empty or invalid tile", e); + return; + } + finally { + jpegWatch.stop("decompressed (jpeg = " + tile.isJPEG + ")"); + } + jpegWatch.start(); - int rowLen = w * bpp; - int srcRowLen = tile.region.width * bpp; + int rowLen = w * bpp; + int srcRowLen = tile.region.width * bpp; - if (isInterleaved()) { - rowLen *= ec; - srcRowLen *= ec; - for (int row=0; row currentTilePositions = tilePositions.get(getCoreIndex()); + long offset = baseOffset; + int bufferSize = 4096; for (int i=0; i 0) { - tilePositions.get(getCoreIndex()).get(i - 1).endOffset = tilePositions.get(getCoreIndex()).get(i).fileOffset; + currentTilePositions.get(i - 1).endOffset = currentTile.fileOffset; } if (i == imagesPerFile - 1) { - tilePositions.get(getCoreIndex()).get(i).endOffset = in.length(); + currentTile.endOffset = in.length(); } if (!zOffsets.containsKey(getCoreIndex())) { zOffsets.put(getCoreIndex(), new ArrayList()); } - Double z = tilePositions.get(getCoreIndex()).get(i).zOffset; + Double z = currentTile.zOffset; if (!zOffsets.get(getCoreIndex()).contains(z)) { zOffsets.get(getCoreIndex()).add(z); } @@ -1823,6 +2063,10 @@ private DicomFileInfo createFileInfo(String file) throws FormatException, IOExce return new DicomFileInfo(new Location(file).getAbsolutePath()); } + private boolean encloses(Region a, Region b) { + return a.intersection(b).equals(b); + } + private void updateCoreMetadata(CoreMetadata ms) { if (ms.sizeC == 0) ms.sizeC = 1; ms.sizeT = 1; @@ -1927,4 +2171,8 @@ public List getTags() { return tags; } + protected Slf4JStopWatch stopWatch() { + return new Slf4JStopWatch(LOGGER, Slf4JStopWatch.DEBUG_LEVEL); + } + } diff --git a/components/formats-bsd/src/loci/formats/in/FakeReader.java b/components/formats-bsd/src/loci/formats/in/FakeReader.java index 75cb10d3eb4..3bb0b95af11 100644 --- a/components/formats-bsd/src/loci/formats/in/FakeReader.java +++ b/components/formats-bsd/src/loci/formats/in/FakeReader.java @@ -1079,11 +1079,11 @@ private void fillAnnotations(MetadataStore store, int imageIndex) { } private Double getX(int i) { - return new Double(ROI_SPACING * i % sizeX); + return (double) (ROI_SPACING * i % sizeX); } private Double getY(int i) { - return new Double(ROI_SPACING * ((int) ROI_SPACING * i / sizeX) % sizeY); + return (double) (ROI_SPACING * ((int) ROI_SPACING * i / sizeX) % sizeY); } private String getPoints(int i) { @@ -1111,8 +1111,8 @@ private void fillRegions(MetadataStore store, int imageIndex) { store.setEllipseID(SHAPE_PREFIX + roiCount, roiCount, 0); store.setEllipseX(getX(i) + ROI_SPACING / 2, roiCount, 0); store.setEllipseY(getY(i) + ROI_SPACING / 2, roiCount, 0); - store.setEllipseRadiusX(new Double(ROI_SPACING / 2), roiCount, 0); - store.setEllipseRadiusY(new Double(ROI_SPACING / 2), roiCount, 0); + store.setEllipseRadiusX(Double.valueOf(ROI_SPACING / 2), roiCount, 0); + store.setEllipseRadiusY(Double.valueOf(ROI_SPACING / 2), roiCount, 0); store.setImageROIRef(roiID, imageIndex, roiRefCount); roiCount++; roiRefCount++; @@ -1198,8 +1198,8 @@ private void fillRegions(MetadataStore store, int imageIndex) { store.setRectangleID(SHAPE_PREFIX + roiCount, roiCount, 0); store.setRectangleX(getX(i) + ROI_SPACING / 4, roiCount, 0); store.setRectangleY(getY(i) + ROI_SPACING / 4, roiCount, 0); - store.setRectangleWidth(new Double(ROI_SPACING / 2), roiCount, 0); - store.setRectangleHeight(new Double(ROI_SPACING / 2), roiCount, 0); + store.setRectangleWidth(Double.valueOf(ROI_SPACING / 2), roiCount, 0); + store.setRectangleHeight(Double.valueOf(ROI_SPACING / 2), roiCount, 0); store.setImageROIRef(roiID, imageIndex, roiRefCount); roiCount++; roiRefCount++; diff --git a/components/formats-bsd/src/loci/formats/in/ICSReader.java b/components/formats-bsd/src/loci/formats/in/ICSReader.java index 0513eac024e..8f9f9981c1c 100644 --- a/components/formats-bsd/src/loci/formats/in/ICSReader.java +++ b/components/formats-bsd/src/loci/formats/in/ICSReader.java @@ -43,6 +43,7 @@ import java.util.Vector; import java.util.zip.GZIPInputStream; +import loci.common.DataTools; import loci.common.DateTools; import loci.common.Location; import loci.common.RandomAccessInputStream; @@ -950,7 +951,7 @@ else if (key.equalsIgnoreCase("parameter units")) { if (key.equalsIgnoreCase("parameter ch")) { String[] names = value.split(" "); for (int n=0; n 1; if (getDimensionOrder().indexOf('C') == -1) { @@ -1478,10 +1479,12 @@ else if (labels.equalsIgnoreCase("x y t")) { MetadataTools.populatePixels(store, this, true); // populate Image data - imageName = imageName.replace('/', File.separatorChar); - imageName = imageName.replace('\\', File.separatorChar); - imageName = imageName.substring(imageName.lastIndexOf(File.separator) + 1); - store.setImageName(imageName, 0); + if (imageName != null) { + imageName = imageName.replace('/', File.separatorChar); + imageName = imageName.replace('\\', File.separatorChar); + imageName = imageName.substring(imageName.lastIndexOf(File.separator) + 1); + store.setImageName(imageName, 0); + } if (date != null) store.setImageAcquisitionDate(new Timestamp(date), 0); @@ -1919,7 +1922,7 @@ private Double[] splitDoubles(String v) { for (int n=0; n 0) { - major = new Integer(version[0]); + major = Integer.parseInt(version[0]); } } catch (NumberFormatException e) { diff --git a/components/formats-bsd/src/loci/formats/in/MinimalTiffReader.java b/components/formats-bsd/src/loci/formats/in/MinimalTiffReader.java index 75eb93e728f..7e3907efe0f 100644 --- a/components/formats-bsd/src/loci/formats/in/MinimalTiffReader.java +++ b/components/formats-bsd/src/loci/formats/in/MinimalTiffReader.java @@ -705,4 +705,73 @@ protected void initTiffParser() { tiffParser.setUse64BitOffsets(use64Bit); } + /** + * Get the index of the tile corresponding to given IFD (plane) + * and tile XY indexes. + * + * @param ifd IFD for the requested tile's plane + * @param x tile X index + * @param y tile Y index + * @return corresponding tile index + */ + protected int getTileIndex(IFD ifd, int x, int y) throws FormatException { + int rows = (int) ifd.getTilesPerColumn(); + int cols = (int) ifd.getTilesPerRow(); + + if (x < 0 || x >= cols) { + throw new IllegalArgumentException("X index " + x + " not in range [0, " + cols + ")"); + } + if (y < 0 || y >= rows) { + throw new IllegalArgumentException("Y index " + y + " not in range [0, " + rows + ")"); + } + + return (cols * y) + x; + } + + protected long getCompressedByteCount(IFD ifd, int x, int y) throws FormatException, IOException { + long[] byteCounts = ifd.getStripByteCounts(); + int tileIndex = getTileIndex(ifd, x, y); + byte[] jpegTable = (byte[]) ifd.getIFDValue(IFD.JPEG_TABLES); + int jpegTableBytes = jpegTable == null ? 0 : jpegTable.length - 2; + long expectedBytes = byteCounts[tileIndex]; + if (expectedBytes > 0) { + expectedBytes += jpegTableBytes; + } + if (expectedBytes < 0 || expectedBytes > Integer.MAX_VALUE) { + throw new IOException("Invalid compressed tile size: " + expectedBytes); + } + return expectedBytes; + } + + protected byte[] copyTile(IFD ifd, byte[] buf, int x, int y) throws FormatException, IOException { + long[] offsets = ifd.getStripOffsets(); + long[] byteCounts = ifd.getStripByteCounts(); + + int tileIndex = getTileIndex(ifd, x, y); + + byte[] jpegTable = (byte[]) ifd.getIFDValue(IFD.JPEG_TABLES); + int jpegTableBytes = jpegTable == null ? 0 : jpegTable.length - 2; + long expectedBytes = getCompressedByteCount(ifd, x, y); + + if (buf.length < expectedBytes) { + throw new IllegalArgumentException("Tile buffer too small: expected >=" + + expectedBytes + ", got " + buf.length); + } + else if (expectedBytes < 0 || expectedBytes > Integer.MAX_VALUE) { + throw new IOException("Invalid compressed tile size: " + expectedBytes); + } + + if (jpegTable != null && expectedBytes > 0) { + System.arraycopy(jpegTable, 0, buf, 0, jpegTable.length - 2); + // skip over the duplicate SOI marker + tiffParser.getStream().seek(offsets[tileIndex] + 2); + tiffParser.getStream().readFully(buf, jpegTable.length - 2, (int) byteCounts[tileIndex]); + } + else if (byteCounts[tileIndex] > 0) { + tiffParser.getStream().seek(offsets[tileIndex]); + tiffParser.getStream().readFully(buf, 0, (int) byteCounts[tileIndex]); + } + return buf; + } + } diff --git a/components/formats-bsd/src/loci/formats/in/OBFReader.java b/components/formats-bsd/src/loci/formats/in/OBFReader.java index a5d4ec6447c..4b03f354174 100644 --- a/components/formats-bsd/src/loci/formats/in/OBFReader.java +++ b/components/formats-bsd/src/loci/formats/in/OBFReader.java @@ -357,7 +357,7 @@ private long initStack(long current) throws FormatException, IOException { for (int dimension = 0; dimension != MAXIMAL_NUMBER_OF_DIMENSIONS; ++ dimension) { final double length = in.readDouble(); if (dimension < numberOfDimensions) { - lengths.add(new Double(length)); + lengths.add(length); } } meta_data.seriesMetadata.put("Lengths", lengths); @@ -366,7 +366,7 @@ private long initStack(long current) throws FormatException, IOException { for (int dimension = 0; dimension != MAXIMAL_NUMBER_OF_DIMENSIONS; ++ dimension) { final double offset = in.readDouble(); if (dimension < numberOfDimensions) { - offsets.add(new Double(offset)); + offsets.add(offset); } } meta_data.seriesMetadata.put("Offsets", offsets); @@ -462,14 +462,14 @@ private long initStack(long current) throws FormatException, IOException { for (int dimension = 0; dimension != MAXIMAL_NUMBER_OF_DIMENSIONS; ++ dimension) { final int present = in.readInt(); if (dimension < numberOfDimensions) { - stepsPresent.add(new Boolean(present != 0)); + stepsPresent.add(present != 0); } } List stepLabelsPresent = new ArrayList(); for (int dimension = 0; dimension != MAXIMAL_NUMBER_OF_DIMENSIONS; ++ dimension) { final int present = in.readInt(); if (dimension < numberOfDimensions) { - stepLabelsPresent.add(new Boolean(present != 0)); + stepLabelsPresent.add(present != 0); } } @@ -536,7 +536,7 @@ else if (isFLIMLabel(label)) { if (stepsPresent.get(dimension)) { for (int position = 0; position != sizes[dimension]; ++ position) { final double step = in.readDouble(); - list.add(new Double(step)); + list.add(step); } } steps.add(list); diff --git a/components/formats-bsd/src/loci/formats/in/OMEXMLReader.java b/components/formats-bsd/src/loci/formats/in/OMEXMLReader.java index 6ce56250894..617ccdca02b 100644 --- a/components/formats-bsd/src/loci/formats/in/OMEXMLReader.java +++ b/components/formats-bsd/src/loci/formats/in/OMEXMLReader.java @@ -290,7 +290,7 @@ protected void initFile(String id) throws FormatException, IOException { Integer t = omexmlMeta.getPixelsSizeT(i).getValue(); Integer z = omexmlMeta.getPixelsSizeZ(i).getValue(); Integer c = omexmlMeta.getPixelsSizeC(i).getValue(); - if (w == null || h == null || t == null || z == null | c == null) { + if (w == null || h == null || t == null || z == null || c == null) { throw new FormatException("Image dimensions not found"); } diff --git a/components/formats-bsd/src/loci/formats/in/QTReader.java b/components/formats-bsd/src/loci/formats/in/QTReader.java index d9ebb83f485..81d4ccbe95f 100644 --- a/components/formats-bsd/src/loci/formats/in/QTReader.java +++ b/components/formats-bsd/src/loci/formats/in/QTReader.java @@ -513,19 +513,19 @@ else if (atomType.equals("stco")) { if (numPlanes != getImageCount()) { in.seek(in.getFilePointer() - 4); int off = in.readInt(); - offsets.add(new Integer(off)); + offsets.add(off); for (int i=1; i 0) && (i < chunkSizes.size())) { rawSize = chunkSizes.get(i).intValue(); } else i = getImageCount(); off += rawSize; - offsets.add(new Integer(off)); + offsets.add(off); } } else { for (int i=0; i> 16)); - out.writeShort((short) (tagCode & 0xffff)); + output.writeShort((short) ((tagCode & 0xffff0000) >> 16)); + output.writeShort((short) (tagCode & 0xffff)); if (tag.vr == IMPLICIT) { - out.writeInt(getStoredLength(tag)); + output.writeInt(getStoredLength(tag)); } else { - boolean order = out.isLittleEndian(); - out.order(false); - out.writeShort(tag.vr.getCode()); - out.order(order); + boolean order = output.isLittleEndian(); + output.order(false); + output.writeShort(tag.vr.getCode()); + output.order(order); if (tag.vr == OB || tag.vr == OW || tag.vr == SQ || tag.vr == UN || tag.vr == UT || tag.vr == UC) { - out.writeShort((short) 0); - out.writeInt(getStoredLength(tag)); + output.writeShort((short) 0); + output.writeInt(getStoredLength(tag)); } else { - out.writeShort((short) getStoredLength(tag)); + output.writeShort((short) getStoredLength(tag)); } + int resolutionIndex = getIndex(series, resolution); if (tag.attribute == TRANSFER_SYNTAX_UID) { - transferSyntaxPointer[getIndex(series, resolution)] = out.getFilePointer(); + transferSyntaxPointer[resolutionIndex] = output.getFilePointer(); } else if (tag.attribute == LOSSY_IMAGE_COMPRESSION_METHOD) { - compressionMethodPointer[getIndex(series, resolution)] = out.getFilePointer(); + compressionMethodPointer[resolutionIndex] = output.getFilePointer(); } else if (tag.attribute == FILE_META_INFO_GROUP_LENGTH) { - fileMetaLengthPointer = out.getFilePointer(); + fileMetaLengthPointer = output.getFilePointer(); + } + else if (tag.attribute == ROWS) { + tileHeightPointer[resolutionIndex] = out.getFilePointer(); + } + else if (tag.attribute == COLUMNS) { + tileWidthPointer[resolutionIndex] = out.getFilePointer(); + } + else if (tag.attribute == NUMBER_OF_FRAMES) { + tileCountPointer[resolutionIndex] = out.getFilePointer(); } // sequences with no items still need to write a SequenceDelimitationItem below if (tag.children.size() == 0 && tag.value == null && tag.vr != SQ) { if (tag.attribute != PIXEL_DATA) { - out.skipBytes(tag.elementLength); + output.skipBytes(tag.elementLength); } return; } @@ -1532,27 +1658,27 @@ else if (tag.value != null) { } switch (tag.attribute) { case OPTICAL_PATH_ID: - planeOffsets[resolutionIndex][currentPlane].cOffset = out.getFilePointer(); + planeOffsets[resolutionIndex][currentPlane].cOffset = output.getFilePointer(); break; case ROW_POSITION_IN_MATRIX: - planeOffsets[resolutionIndex][currentPlane].yOffset = out.getFilePointer(); + planeOffsets[resolutionIndex][currentPlane].yOffset = output.getFilePointer(); break; case COLUMN_POSITION_IN_MATRIX: - planeOffsets[resolutionIndex][currentPlane].xOffset = out.getFilePointer(); + planeOffsets[resolutionIndex][currentPlane].xOffset = output.getFilePointer(); break; case DIMENSION_INDEX_VALUES: - planeOffsets[resolutionIndex][currentPlane].dimensionIndex = out.getFilePointer(); + planeOffsets[resolutionIndex][currentPlane].dimensionIndex = output.getFilePointer(); break; case X_OFFSET_IN_SLIDE: - planeOffsets[resolutionIndex][currentPlane].xOffsetReal = out.getFilePointer(); + planeOffsets[resolutionIndex][currentPlane].xOffsetReal = output.getFilePointer(); planeOffsets[resolutionIndex][currentPlane].xOffsetSize = tag.elementLength; break; case Y_OFFSET_IN_SLIDE: - planeOffsets[resolutionIndex][currentPlane].yOffsetReal = out.getFilePointer(); + planeOffsets[resolutionIndex][currentPlane].yOffsetReal = output.getFilePointer(); planeOffsets[resolutionIndex][currentPlane].yOffsetSize = tag.elementLength; break; case Z_OFFSET_IN_SLIDE: - planeOffsets[resolutionIndex][currentPlane].zOffset = out.getFilePointer(); + planeOffsets[resolutionIndex][currentPlane].zOffset = output.getFilePointer(); planeOffsets[resolutionIndex][currentPlane].zOffsetSize = tag.elementLength; break; } @@ -1575,58 +1701,59 @@ else if (tag.value != null) { case UI: case UR: case UT: - out.writeBytes(tag.value.toString()); + output.writeBytes(tag.value.toString()); break; case AT: for (short s : (short[]) tag.value) { - out.writeShort(s); + output.writeShort(s); } break; case FL: for (float f : (float[]) tag.value) { - out.writeFloat(f); + output.writeFloat(f); } break; case FD: for (double d : (double[]) tag.value) { - out.writeDouble(d); + output.writeDouble(d); } break; case OB: - out.write((byte[]) tag.value); + output.write((byte[]) tag.value); break; case SL: for (int v : (int[]) tag.value) { - out.writeInt(v); + output.writeInt(v); } break; case SS: for (short s : (short[]) tag.value) { - out.writeShort(s); + output.writeShort(s); } break; case SV: for (long v : (long[]) tag.value) { - out.writeLong(v); + output.writeLong(v); } break; case UL: for (long v : (long[]) tag.value) { - out.writeInt((int) (v & 0xffffffff)); + output.writeInt((int) (v & 0xffffffff)); } break; case US: for (short s : (short[]) tag.value) { - out.writeShort(s); + output.writeShort(s); } break; case IMPLICIT: - out.write((byte[]) tag.value); + output.write((byte[]) tag.value); break; default: throw new IllegalArgumentException(String.valueOf(tag.vr.getCode())); } } + tagWatch.stop("wrote single tag: " + tag); } /** @@ -1665,6 +1792,17 @@ private String padString(String value, String append) { return value + append; } + private String padString(String value, String append, int length) { + String rtn = ""; + if (value != null) { + rtn += value; + } + while (rtn.length() < length) { + rtn += append; + } + return rtn; + } + /** * @return transfer syntax UID corresponding to the current compression type */ @@ -1710,6 +1848,7 @@ private void openFile(int pyramid, int res) throws IOException { // filename for this series/resolution return; } + StopWatch openWatch = stopWatch(); if (out != null) { out.close(); } @@ -1731,6 +1870,7 @@ else if (r.getPixelsBinDataCount(pyramid) == 0) { if (out.length() == 0) { writeHeader(); } + openWatch.stop("opened " + filename); } /** @@ -1738,79 +1878,89 @@ else if (r.getPixelsBinDataCount(pyramid) == 0) { * See http://dicom.nema.org/medical/dicom/current/output/html/part10.html#sect_7.1 */ private void writeHeader() throws IOException { + StopWatch headerWatch = stopWatch(); + ByteArrayHandle buffer = new ByteArrayHandle(); + RandomAccessOutputStream headerBuffer = new RandomAccessOutputStream(buffer); boolean littleEndian = out.isLittleEndian(); + headerBuffer.order(littleEndian); if (writeDualPersonality()) { // write a TIFF header in the preamble if (littleEndian) { - out.writeByte(TiffConstants.LITTLE); - out.writeByte(TiffConstants.LITTLE); + headerBuffer.writeByte(TiffConstants.LITTLE); + headerBuffer.writeByte(TiffConstants.LITTLE); } else { - out.writeByte(TiffConstants.BIG); - out.writeByte(TiffConstants.BIG); + headerBuffer.writeByte(TiffConstants.BIG); + headerBuffer.writeByte(TiffConstants.BIG); } if (bigTiff) { - out.writeShort(TiffConstants.BIG_TIFF_MAGIC_NUMBER); - out.writeShort(8); // number of bytes in an offset - out.writeShort(0); // reserved + headerBuffer.writeShort(TiffConstants.BIG_TIFF_MAGIC_NUMBER); + headerBuffer.writeShort(8); // number of bytes in an offset + headerBuffer.writeShort(0); // reserved - nextIFDPointer[getIndex(series, resolution)] = out.getFilePointer(); - out.writeLong(-1); // placeholder to first IFD + nextIFDPointer[getIndex(series, resolution)] = headerBuffer.getFilePointer(); + headerBuffer.writeLong(-1); // placeholder to first IFD } else { - out.writeShort(TiffConstants.MAGIC_NUMBER); - nextIFDPointer[getIndex(series, resolution)] = out.getFilePointer(); - out.writeInt(-1); // placeholder to first IFD + headerBuffer.writeShort(TiffConstants.MAGIC_NUMBER); + nextIFDPointer[getIndex(series, resolution)] = headerBuffer.getFilePointer(); + headerBuffer.writeInt(-1); // placeholder to first IFD } } else { byte[] preamble = new byte[128]; - out.write(preamble); + headerBuffer.write(preamble); } // seek to end of preamble, then write DICOM header - out.seek(128); - out.order(true); - out.writeBytes("DICM"); + headerBuffer.seek(128); + headerBuffer.order(true); + headerBuffer.writeBytes("DICM"); DicomTag fileMetaLength = new DicomTag(FILE_META_INFO_GROUP_LENGTH, UL); // placeholder value, overwritten at the end of this method fileMetaLength.value = new long[] {0}; - writeTag(fileMetaLength); + writeTag(fileMetaLength, headerBuffer); DicomTag fileMetaVersion = new DicomTag(FILE_META_INFO_VERSION, OB); fileMetaVersion.value = new byte[] {0, 1}; - writeTag(fileMetaVersion); + writeTag(fileMetaVersion, headerBuffer); DicomTag mediaStorageClassUID = new DicomTag(MEDIA_SOP_CLASS_UID, UI); mediaStorageClassUID.value = padUID(SOP_CLASS_UID_VALUE); - writeTag(mediaStorageClassUID); + writeTag(mediaStorageClassUID, headerBuffer); DicomTag mediaStorageInstanceUID = new DicomTag(MEDIA_SOP_INSTANCE_UID, UI); mediaStorageInstanceUID.value = padUID(instanceUIDValue); - writeTag(mediaStorageInstanceUID); + writeTag(mediaStorageInstanceUID, headerBuffer); // placeholder, will be overwritten on the first call to saveBytes DicomTag transferSyntaxUID = new DicomTag(TRANSFER_SYNTAX_UID, UI); transferSyntaxUID.elementLength = 22; - writeTag(transferSyntaxUID); + writeTag(transferSyntaxUID, headerBuffer); DicomTag implementationClassUID = new DicomTag(IMPLEMENTATION_UID, UI); implementationClassUID.value = padUID(implementationUID); - writeTag(implementationClassUID); + writeTag(implementationClassUID, headerBuffer); DicomTag implementationVersionName = new DicomTag(IMPLEMENTATION_VERSION, SH); implementationVersionName.value = padString(FormatTools.VERSION); - writeTag(implementationVersionName); + writeTag(implementationVersionName, headerBuffer); + + int bufferBytes = (int) headerBuffer.getFilePointer(); + out.order(headerBuffer.isLittleEndian()); + headerBuffer.close(); + out.write(buffer.getBytes(), 0, bufferBytes); // count all bytes after the file meta length value int fileMetaBytes = (int) (out.getFilePointer() - fileMetaLengthPointer - 4); out.seek(fileMetaLengthPointer); out.writeInt(fileMetaBytes); fileMetaLengthPointer = 0; - out.skipBytes(fileMetaBytes); + out.skipBytes(fileMetaBytes); out.order(littleEndian); + headerWatch.stop("wrote header for series = " + series + ", resolution = " + resolution); } private String getFilename(int pyramid, int res) { @@ -1862,11 +2012,12 @@ private boolean isReallySequential() { return sizeC * sizeZ * sizeT == 1; } + // check that there is a single channel or Z section (so order doesn't matter) + // or the dimension order indicates that Z is before C DimensionOrder order = retrieve.getPixelsDimensionOrder(series); return sequential && (sizeC == 1 || sizeZ == 1 || order == DimensionOrder.XYZCT || order == DimensionOrder.XYZTC || - order == DimensionOrder.XYZTC || order == DimensionOrder.XYTZC); } @@ -1918,6 +2069,9 @@ private void writeIFDs(int resIndex) throws IOException { out.seek(ifdStart); for (int no=0; no 0) { + ifd.put(IFD.NEW_SUBFILE_TYPE, 1); + } + else { + if (!ifd.containsKey(IFD.SUB_IFD)) { + ifd.put(IFD.SUB_IFD, (long) 0); + } + } + return ifd; + } + @Override public void saveBytes(int no, byte[] buf, IFD ifd, int x, int y, int w, int h) throws FormatException, IOException @@ -118,7 +131,6 @@ public void close() throws IOException { } int mainIFDIndex = 0; - int currentFullResolution = 0; for (int i=0; i 0 && getTileSizeY() > 0; + if (usingTiling) { + ifd.put(new Integer(IFD.TILE_WIDTH), new Long(getTileSizeX())); + ifd.put(new Integer(IFD.TILE_LENGTH), new Long(getTileSizeY())); + } + return ifd; + } + // -- FormatWriter API methods -- /* @see loci.formats.FormatWriter#setId(String) */ @@ -230,8 +307,8 @@ public void saveBytes(int no, byte[] buf, IFD ifd, int x, int y, int w, int h) int currentTileSizeY = getTileSizeY(); boolean usingTiling = currentTileSizeX > 0 && currentTileSizeY > 0; if (usingTiling) { - ifd.put(new Integer(IFD.TILE_WIDTH), new Long(currentTileSizeX)); - ifd.put(new Integer(IFD.TILE_LENGTH), new Long(currentTileSizeY)); + ifd.put(IFD.TILE_WIDTH, Long.valueOf(currentTileSizeX)); + ifd.put(IFD.TILE_LENGTH, Long.valueOf(currentTileSizeY)); } if (usingTiling && (currentTileSizeX < w || currentTileSizeY < h)) { int numTilesX = (w + (x % currentTileSizeX) + currentTileSizeX - 1) / currentTileSizeX; @@ -355,8 +432,8 @@ else if (retrieve.getPixelsBinDataCount(series) == 0) { int width = getSizeX(); int height = getSizeY(); - ifd.put(new Integer(IFD.IMAGE_WIDTH), new Long(width)); - ifd.put(new Integer(IFD.IMAGE_LENGTH), new Long(height)); + ifd.put(IFD.IMAGE_WIDTH, Long.valueOf(width)); + ifd.put(IFD.IMAGE_LENGTH, Long.valueOf(height)); Length px = retrieve.getPixelsPhysicalSizeX(series); Double physicalSizeX = px == null || px.value(UNITS.MICROMETER) == null ? null : px.value(UNITS.MICROMETER).doubleValue(); @@ -387,7 +464,7 @@ else if (retrieve.getPixelsBinDataCount(series) == 0) { } // write the image - ifd.put(new Integer(IFD.LITTLE_ENDIAN), new Boolean(littleEndian)); + ifd.put(IFD.LITTLE_ENDIAN, Boolean.valueOf(littleEndian)); if (!ifd.containsKey(IFD.REUSE)) { ifd.put(IFD.REUSE, out.length()); out.seek(out.length()); diff --git a/components/formats-bsd/src/loci/formats/services/JPEGTurboService.java b/components/formats-bsd/src/loci/formats/services/JPEGTurboService.java index 85570cbaf2c..bddf1be24bb 100644 --- a/components/formats-bsd/src/loci/formats/services/JPEGTurboService.java +++ b/components/formats-bsd/src/loci/formats/services/JPEGTurboService.java @@ -44,21 +44,100 @@ */ public interface JPEGTurboService extends Service { + /** + * @return the restart markers associated with the current JPEG stream + */ long[] getRestartMarkers(); + /** + * @param markers precalculated restart markers associated with + * the current JPEG stream + */ void setRestartMarkers(long[] markers); + /** + * Initialize the given stream, which represents an image of the given + * width and height. This service is primarily intended for very large + * JPEG images whose width and/or height exceed 65535 (the maximum + * that can be recorded in a JPEG stream). + * + * @param jpeg open stream containing JPEG data + * @param width total image width + * @param height total image height + */ void initialize(RandomAccessInputStream jpeg, int width, int height) throws ServiceException, IOException; + /** + * @return the width (in pixels) of a tile + */ + int getTileWidth(); + + /** + * @return the height (in pixels) of a tile + */ + int getTileHeight(); + + /** + * @return the number of rows of tiles + */ + int getTileRows(); + + /** + * @return the number of columns of tiles + */ + int getTileColumns(); + + /** + * Get the uncompressed bytes representing the given bounding box. + * + * @param buf array in which to store uncompressed bytes + * @param xCoordinate upper-left X coordinate of bounding box + * @param yCoordinate upper-left Y coordinate of bounding box + * @param width width of bounding box + * @param height height of bounding box + * @return uncompressed bytes + */ byte[] getTile(byte[] buf, int xCoordinate, int yCoordinate, int width, int height) throws IOException; + /** + * Get the uncompressed bytes representing the given tile index. + * + * @param xTile column index of the tile + * @param yTile row index of the tile + * @return uncompressed bytes + */ byte[] getTile(int xTile, int yTile) throws IOException; + /** + * Similar to getTile(int, int), but returns the JPEG-compressed bytes. + * + * @param xTile column index of the tile + * @param yTile row index of the tile + * @return JPEG-compressed bytes + */ + byte[] getCompressedTile(int xTile, int yTile) throws IOException; + + /** + * Similar to getTile(int, int), but returns the JPEG-compressed bytes. + * + * @param data preallocated array for storing tile + * @param xTile column index of the tile + * @param yTile row index of the tile + * @return JPEG-compressed bytes + */ + byte[] getCompressedTile(byte[] data, int xTile, int yTile) throws IOException; + + /** + * Free resources associated with the initialized stream. + */ void close() throws IOException; - + + /** + * @return true if the underlying native library was successfully loaded + */ boolean isLibraryLoaded(); } diff --git a/components/formats-bsd/src/loci/formats/services/JPEGTurboServiceImpl.java b/components/formats-bsd/src/loci/formats/services/JPEGTurboServiceImpl.java index cfe316b1513..c2e194801a5 100644 --- a/components/formats-bsd/src/loci/formats/services/JPEGTurboServiceImpl.java +++ b/components/formats-bsd/src/loci/formats/services/JPEGTurboServiceImpl.java @@ -229,6 +229,26 @@ else if (marker == SOS) { } } + @Override + public int getTileWidth() { + return tileWidth; + } + + @Override + public int getTileHeight() { + return tileHeight; + } + + @Override + public int getTileRows() { + return yTiles; + } + + @Override + public int getTileColumns() { + return xTiles; + } + @Override public byte[] getTile(byte[] buf, int xCoordinate, int yCoordinate, int width, int height) @@ -287,6 +307,30 @@ public byte[] getTile(byte[] buf, int xCoordinate, int yCoordinate, @Override public byte[] getTile(int tileX, int tileY) throws IOException { + byte[] compressedData = getCompressedTile(tileX, tileY); + + // and here we actually decompress it... + + try { + int pixelType = TJ.PF_RGB; + int pixelSize = TJ.getPixelSize(pixelType); + + TJDecompressor decoder = new TJDecompressor(compressedData); + byte[] decompressed = decoder.decompress(tileWidth, tileWidth * pixelSize, + tileHeight, pixelType, pixelType); + compressedData = null; + decoder.close(); + return decompressed; + } + catch (Exception e) { + IOException ioe = new IOException(e.getMessage()); + ioe.initCause(e); + throw ioe; + } + } + + @Override + public byte[] getCompressedTile(int tileX, int tileY) throws IOException { if (header == null) { header = getFixedHeader(); } @@ -312,12 +356,21 @@ public byte[] getTile(int tileX, int tileY) throws IOException { } byte[] data = new byte[(int) dataLength]; + return getCompressedTile(data, tileX, tileY); + } + + @Override + public byte[] getCompressedTile(byte[] data, int tileX, int tileY) throws IOException { + if (header == null) { + header = getFixedHeader(); + } int offset = 0; System.arraycopy(header, 0, data, offset, header.length); offset += header.length; - start = tileX + (tileY * xTiles * mult); + int mult = tileHeight / mcuHeight; // was restartInterval + int start = tileX + (tileY * xTiles * mult); for (int row=0; row ome pom-bio-formats - 8.0.0-SNAPSHOT + 8.1.0-SNAPSHOT ../.. @@ -66,7 +66,7 @@ edu.ucar cdm-core - 5.3.3 + 5.6.0 com.amazonaws diff --git a/components/formats-gpl/src/loci/formats/in/AIMReader.java b/components/formats-gpl/src/loci/formats/in/AIMReader.java index d40c79bdb66..7f291eebc2b 100644 --- a/components/formats-gpl/src/loci/formats/in/AIMReader.java +++ b/components/formats-gpl/src/loci/formats/in/AIMReader.java @@ -27,6 +27,7 @@ import java.io.IOException; +import loci.common.DataTools; import loci.common.DateTools; import loci.common.RandomAccessInputStream; import loci.formats.CoreMetadata; @@ -152,13 +153,13 @@ else if (key.equals("Orig-ISQ-Dim-p")) { token = token.trim(); if (token.length() > 0) { if (xSize == null) { - xSize = new Double(token); + xSize = DataTools.parseDouble(token); } else if (ySize == null) { - ySize = new Double(token); + ySize = DataTools.parseDouble(token); } else if (zSize == null) { - zSize = new Double(token); + zSize = DataTools.parseDouble(token); } } } @@ -169,13 +170,13 @@ else if (key.equals("Orig-ISQ-Dim-um")) { token = token.trim(); if (token.length() > 0) { if (xLength == null) { - xLength = new Double(token); + xLength = DataTools.parseDouble(token); } else if (yLength == null) { - yLength = new Double(token); + yLength = DataTools.parseDouble(token); } else if (zLength == null) { - zLength = new Double(token); + zLength = DataTools.parseDouble(token); } } } diff --git a/components/formats-gpl/src/loci/formats/in/AliconaReader.java b/components/formats-gpl/src/loci/formats/in/AliconaReader.java index fffe5538280..fa9f85129bb 100644 --- a/components/formats-gpl/src/loci/formats/in/AliconaReader.java +++ b/components/formats-gpl/src/loci/formats/in/AliconaReader.java @@ -27,6 +27,7 @@ import java.io.IOException; +import loci.common.DataTools; import loci.common.RandomAccessInputStream; import loci.formats.CoreMetadata; import loci.formats.FormatException; @@ -238,7 +239,7 @@ else if (key.equals("DepthImageOffset")) { // used when the dataset was acquired, i.e. detector settings. if (voltage != null) { store.setDetectorSettingsVoltage( - new ElectricPotential(new Double(voltage), UNITS.VOLT), 0, 0); + new ElectricPotential(DataTools.parseDouble(voltage), UNITS.VOLT), 0, 0); // link DetectorSettings to an actual Detector String detectorID = MetadataTools.createLSID("Detector", 0, 0); @@ -253,11 +254,11 @@ else if (key.equals("DepthImageOffset")) { if (magnification != null) { store.setObjectiveCalibratedMagnification( - new Double(magnification), 0, 0); + DataTools.parseDouble(magnification), 0, 0); } if (workingDistance != null) { - store.setObjectiveWorkingDistance(new Length(new Double(workingDistance), UNITS.MICROMETER), 0, 0); + store.setObjectiveWorkingDistance(new Length(DataTools.parseDouble(workingDistance), UNITS.MICROMETER), 0, 0); } store.setObjectiveCorrection(MetadataTools.getCorrection("Other"), 0, 0); diff --git a/components/formats-gpl/src/loci/formats/in/BDReader.java b/components/formats-gpl/src/loci/formats/in/BDReader.java index 0d40fede37e..75a529c11d1 100644 --- a/components/formats-gpl/src/loci/formats/in/BDReader.java +++ b/components/formats-gpl/src/loci/formats/in/BDReader.java @@ -460,11 +460,11 @@ protected void initFile(String id) throws FormatException, IOException { } } - Double magnification = new Double(mag); + Double magnification = DataTools.parseDouble(mag); store.setObjectiveNominalMagnification(magnification, 0, 0); if (na != null) { na = na.substring(0, 1) + "." + na.substring(1); - store.setObjectiveLensNA(new Double(na), 0, 0); + store.setObjectiveLensNA(DataTools.parseDouble(na), 0, 0); } if (naIndex + 1 < tokens.length) { store.setObjectiveManufacturer(tokens[naIndex + 1], 0, 0); @@ -762,10 +762,10 @@ private void parseROIs(MetadataStore store) throws IOException { if (cols[2].trim().length() > 0) { String rectangleID = MetadataTools.createLSID("Shape", i - firstRow, 0); store.setRectangleID(rectangleID, i - firstRow, 0); - store.setRectangleX(new Double(cols[2]), i - firstRow, 0); - store.setRectangleY(new Double(cols[3]), i - firstRow, 0); - store.setRectangleWidth(new Double(cols[4]), i - firstRow, 0); - store.setRectangleHeight(new Double(cols[5]), i - firstRow, 0); + store.setRectangleX(DataTools.parseDouble(cols[2]), i - firstRow, 0); + store.setRectangleY(DataTools.parseDouble(cols[3]), i - firstRow, 0); + store.setRectangleWidth(DataTools.parseDouble(cols[4]), i - firstRow, 0); + store.setRectangleHeight(DataTools.parseDouble(cols[5]), i - firstRow, 0); String roiID = MetadataTools.createLSID("ROI", i - firstRow); store.setROIID(roiID, i - firstRow); for (int s=0; s offset.size()) { offset.add(null); } - offset.add(new Double(value)); + offset.add(DataTools.parseDouble(value)); } } else if (key.endsWith("GAIN")) { @@ -684,7 +685,7 @@ else if (key.endsWith("GAIN")) { while (nextDetector > gain.size()) { gain.add(null); } - gain.add(new Double(value)); + gain.add(DataTools.parseDouble(value)); } } nextDetector++; @@ -698,7 +699,7 @@ else if (key.endsWith("GAIN")) { int type = Integer.parseInt(values[0]); if (type == 257 && values.length >= 3) { // found length of axis in um - Double pixelSize = new Double(values[2]); + Double pixelSize = DataTools.parseDouble(values[2]); if (key.equals("AXIS_2")) { Length size = FormatTools.getPhysicalSizeX(pixelSize); @@ -722,7 +723,7 @@ else if (key.equals("AXIS_3")) { } else if (n.p.startsWith("AXIS_2")) { String[] values = n.p.split(" "); - Double pixelSize = new Double(values[3]); + Double pixelSize = DataTools.parseDouble(values[3]); Length size = FormatTools.getPhysicalSizeX(pixelSize); if (size != null) { store.setPixelsPhysicalSizeX(size, 0); @@ -730,7 +731,7 @@ else if (n.p.startsWith("AXIS_2")) { } else if (n.p.startsWith("AXIS_3")) { String[] values = n.p.split(" "); - Double pixelSize = new Double(values[3]); + Double pixelSize = DataTools.parseDouble(values[3]); Length size = FormatTools.getPhysicalSizeY(pixelSize); if (size != null) { store.setPixelsPhysicalSizeY(size, 0); @@ -754,7 +755,7 @@ else if (n.p.startsWith("AXIS_3")) { Double mag = Double.parseDouble(values[11]); store.setObjectiveNominalMagnification(mag, 0, 0); - Double sizeZ = new Double(values[14]); + Double sizeZ = DataTools.parseDouble(values[14]); Length size = FormatTools.getPhysicalSizeZ(sizeZ); if (size != null) { store.setPixelsPhysicalSizeZ(size, 0); @@ -851,8 +852,8 @@ else if (n.p.startsWith("AXIS_3")) { String detectorID = MetadataTools.createLSID("Detector", 0, i); store.setDetectorID(detectorID, 0, i); - store.setDetectorOffset(new Double(values[i * 3]), 0, i); - store.setDetectorGain(new Double(values[i * 3 + 1]), 0, i); + store.setDetectorOffset(DataTools.parseDouble(values[i * 3]), 0, i); + store.setDetectorGain(DataTools.parseDouble(values[i * 3 + 1]), 0, i); store.setDetectorType(MetadataTools.getDetectorType("Other"), 0, i); } break; diff --git a/components/formats-gpl/src/loci/formats/in/BioRadSCNReader.java b/components/formats-gpl/src/loci/formats/in/BioRadSCNReader.java index 2365f8b068c..ea107fb9107 100644 --- a/components/formats-gpl/src/loci/formats/in/BioRadSCNReader.java +++ b/components/formats-gpl/src/loci/formats/in/BioRadSCNReader.java @@ -28,6 +28,7 @@ import java.io.IOException; import java.util.ArrayList; +import loci.common.DataTools; import loci.common.RandomAccessInputStream; import loci.common.xml.BaseHandler; import loci.common.xml.XMLTools; @@ -245,10 +246,10 @@ else if ("channel_count".equals(key)) { core.get(0).sizeC = Integer.parseInt(value); } else if ("application_gain".equals(key)) { - gain = new Double(value); + gain = DataTools.parseDouble(value); } else if ("exposure_time".equals(key)) { - exposureTime = new Double(value); + exposureTime = DataTools.parseDouble(value); } else if ("name".equals(key)) { imageName = value; @@ -287,12 +288,18 @@ else if (value <= 65535) { } else if (key.equals("size_mm")) { if (attrKey.equals("width")) { - physicalSizeX = new Double(attrValue) / getSizeX(); - physicalSizeX *= 1000; // convert from mm to um + Double size = DataTools.parseDouble(attrValue); + if (size != null) { + physicalSizeX = size / getSizeX(); + physicalSizeX *= 1000; // convert from mm to um + } } else if (attrKey.equals("height")) { - physicalSizeY = new Double(attrValue) / getSizeY(); - physicalSizeY *= 1000; // convert from mm to um + Double size = DataTools.parseDouble(attrValue); + if (size != null) { + physicalSizeY = size / getSizeY(); + physicalSizeY *= 1000; // convert from mm to um + } } } else if (key.equals("serial_number")) { diff --git a/components/formats-gpl/src/loci/formats/in/BrukerReader.java b/components/formats-gpl/src/loci/formats/in/BrukerReader.java index 25b61f669f9..d9d6ba5ec89 100644 --- a/components/formats-gpl/src/loci/formats/in/BrukerReader.java +++ b/components/formats-gpl/src/loci/formats/in/BrukerReader.java @@ -216,12 +216,12 @@ protected void initFile(String id) throws FormatException, IOException { public int compare(String s1, String s2) { Integer i1 = 0; try { - i1 = new Integer(s1); + i1 = Integer.parseInt(s1); } catch (NumberFormatException e) { } Integer i2 = 0; try { - i2 = new Integer(s2); + i2 = Integer.parseInt(s2); } catch (NumberFormatException e) { } diff --git a/components/formats-gpl/src/loci/formats/in/CV7000Reader.java b/components/formats-gpl/src/loci/formats/in/CV7000Reader.java index 0d2a65c707a..66b745a1c9e 100644 --- a/components/formats-gpl/src/loci/formats/in/CV7000Reader.java +++ b/components/formats-gpl/src/loci/formats/in/CV7000Reader.java @@ -81,7 +81,7 @@ public class CV7000Reader extends FormatReader { // -- Fields -- - private String[] allFiles; + private List allFiles = new ArrayList(); private MinimalTiffReader reader; private String wppPath; private String detailPath; @@ -223,6 +223,11 @@ public void close(boolean fileOnly) throws IOException { reversePlaneLookup = null; extraFiles = null; acquiredWells.clear(); + if (allFiles != null) { + allFiles.clear(); + } else { + allFiles = new ArrayList(); + } } } @@ -269,15 +274,12 @@ protected void initFile(String id) throws FormatException, IOException { XMLTools.parseXML(wpiXML, plate); Location parent = new Location(id).getAbsoluteFile().getParentFile(); - allFiles = parent.list(true); - Arrays.sort(allFiles); - for (int i=0; i 0) { if (s < files.size() - 1) { setCoreIndex(index); String ff = files.get(s); + /** + * If there are more frame_*.ets files than there are metadata 'pyramids' + * defined in the .vsi, then we have orphaned frame files. In this case + * we need to determine which are the valid frame files and which are + * the orphans. The valid ones need to be matched with the appropriate + * metadata blocks in the vsi, and the orphaned ones need to be ignored. + */ + boolean hasOrphanEtsFiles = pyramids.size() < (files.size() - 1); try (RandomAccessInputStream stream = new RandomAccessInputStream(ff)) { - parseETSFile(stream, ff, s); + boolean validFrameFile = parseETSFile(stream, ff, s, hasOrphanEtsFiles); + /* + * If this frame file is an orphan, "undo" the work that was done for + * it and change its status to being an "extra" file. + */ + if (!validFrameFile) { + core.remove(core.size()-1); + extraFiles.add(files.get(s)); + files.remove(s); + usedFiles = files.toArray(new String[files.size()]); + s--; + seriesCount--; + continue; + } } ms.littleEndian = compressionType.get(index) == RAW; @@ -797,10 +818,6 @@ else if (zCount > 0) { } index += ms.resolutionCount; - if (s < pyramids.size()) { - ms.seriesMetadata = pyramids.get(s).originalMetadata; - } - setCoreIndex(0); ms.dimensionOrder = "XYCZT"; } @@ -1188,7 +1205,8 @@ else if (dim.equals("T")) { return buf; } - private void parseETSFile(RandomAccessInputStream etsFile, String file, int s) + private boolean parseETSFile(RandomAccessInputStream etsFile, String file, int s, + boolean hasOrphanEtsFiles) throws FormatException, IOException { fileMap.put(core.size() - 1, file); @@ -1286,7 +1304,55 @@ private void parseETSFile(RandomAccessInputStream etsFile, String file, int s) int[] maxC = new int[maxResolution]; int[] maxT = new int[maxResolution]; - HashMap dimOrder = pyramids.get(s).dimensionOrdering; + HashMap dimOrder = new HashMap(); + Pyramid pyramid = null; + /** + * If there are orphaned .ets files with this vsi file, we need to determine whether + * the current one is an orphan or a legit file. The logic to determine this is to + * see of there is a metadata block (ie 'pyramid') whose width and height are + * within the correct range for this .ets file. If there is no matching metadata + * block, then we have to assume this is an orphan + **/ + if (hasOrphanEtsFiles) { + int maxXAtRes0 = 0; + int maxYAtRes0 = 0; + for (TileCoordinate t : tmpTiles) { + if (!usePyramid || t.coordinate[t.coordinate.length - 1] == 0) { + maxXAtRes0 = Math.max(maxXAtRes0, t.coordinate[0]); + maxYAtRes0 = Math.max(maxYAtRes0, t.coordinate[1]); + } + } + int maxPixelWidth = (maxXAtRes0 + 1) * tileX.get(tileX.size()-1); + int maxPixelHeight = (maxYAtRes0 + 1) * tileY.get(tileY.size()-1); + for (Pyramid p : pyramids) { + if (p.HasAssociatedEtsFile) // If this pyramid has already been linked to an ETS + continue; // then don't allow it to be linked to another. + if ( (p.width <= maxPixelWidth ) && (p.width >= maxPixelWidth - tileX.get(tileX.size()-1)) + && (p.height <= maxPixelHeight) && (p.height >= maxPixelHeight - tileY.get(tileY.size()-1)) ) { + pyramid = p; + p.HasAssociatedEtsFile = true; // Rememeber that this pyramid is now taken by an Ets. + break; + } + } + /** + * No matching metadata block. This is an orphan ets file. Undo and erase + * all the data elements that have been gathered up for this .ets file. + **/ + if (pyramid == null) { + fileMap.remove(core.size() - 1); + nDimensions.remove(nDimensions.size() - 1); + compressionType.remove(compressionType.size() - 1); + tileX.remove(tileX.size() - 1); + tileY.remove(tileY.size() - 1); + backgroundColor.remove(getCoreIndex()); + tileOffsets.remove(tileOffsets.size()-1); + return(false); + } + } + else { + pyramid = pyramids.get(s); + } + dimOrder = pyramid.dimensionOrdering; for (TileCoordinate t : tmpTiles) { int resolution = usePyramid ? t.coordinate[t.coordinate.length - 1] : 0; @@ -1381,13 +1447,9 @@ private void parseETSFile(RandomAccessInputStream etsFile, String file, int s) maxC[resolution] = t.coordinate[cIndex]; } } - - if (pyramids.get(s).width != null) { - ms.sizeX = pyramids.get(s).width; - } - if (pyramids.get(s).height != null) { - ms.sizeY = pyramids.get(s).height; - } + ms.sizeX = pyramid.width; + ms.sizeY = pyramid.height; + ms.seriesMetadata = pyramid.originalMetadata; ms.sizeZ = maxZ[0] + 1; if (maxC[0] > 0) { ms.sizeC *= (maxC[0] + 1); @@ -1481,6 +1543,7 @@ else if (newResolution.sizeY > maxSizeY) { ms.resolutionCount = finalResolution; } + return(true); } private int convertPixelType(int pixelType) throws FormatException { @@ -1683,7 +1746,7 @@ else if (extendedField && (realType == PROPERTY_SET_VOLUME || value = String.valueOf(vsi.readDouble()); break; case BOOLEAN: - value = new Boolean(vsi.readBoolean()).toString(); + value = Boolean.valueOf(vsi.readBoolean()).toString(); break; case TCHAR: case UNICODE_TCHAR: @@ -1821,72 +1884,72 @@ else if (tag == DEVICE_MANUFACTURER) { pyramid.deviceManufacturers.add(value); } else if (tag == EXPOSURE_TIME && tagPrefix.length() == 0) { - pyramid.exposureTimes.add(new Long(value)); + pyramid.exposureTimes.add(Long.parseLong(value)); } else if (tag == EXPOSURE_TIME) { - pyramid.defaultExposureTime = new Long(value); + pyramid.defaultExposureTime = Long.parseLong(value); pyramid.otherExposureTimes.add(pyramid.defaultExposureTime); } else if (tag == CREATION_TIME && pyramid.acquisitionTime == null) { - pyramid.acquisitionTime = new Long(value); + pyramid.acquisitionTime = Long.parseLong(value); } else if (tag == REFRACTIVE_INDEX) { - pyramid.refractiveIndex = new Double(value); + pyramid.refractiveIndex = DataTools.parseDouble(value); } else if (tag == OBJECTIVE_MAG) { - pyramid.magnification = new Double(value); + pyramid.magnification = DataTools.parseDouble(value); } else if (tag == NUMERICAL_APERTURE) { - pyramid.numericalAperture = new Double(value); + pyramid.numericalAperture = DataTools.parseDouble(value); } else if (tag == WORKING_DISTANCE) { - pyramid.workingDistance = new Double(value); + pyramid.workingDistance = DataTools.parseDouble(value); } else if (tag == OBJECTIVE_NAME) { pyramid.objectiveNames.add(value); } else if (tag == OBJECTIVE_TYPE) { - pyramid.objectiveTypes.add(new Integer(value)); + pyramid.objectiveTypes.add(Integer.parseInt(value)); } else if (tag == BIT_DEPTH) { - pyramid.bitDepth = new Integer(value); + pyramid.bitDepth = Integer.parseInt(value); } else if (tag == X_BINNING) { - pyramid.binningX = new Integer(value); + pyramid.binningX = Integer.parseInt(value); } else if (tag == Y_BINNING) { - pyramid.binningY = new Integer(value); + pyramid.binningY = Integer.parseInt(value); } else if (tag == CAMERA_GAIN) { - pyramid.gain = new Double(value); + pyramid.gain = DataTools.parseDouble(value); } else if (tag == CAMERA_OFFSET) { - pyramid.offset = new Double(value); + pyramid.offset = DataTools.parseDouble(value); } else if (tag == RED_GAIN) { - pyramid.redGain = new Double(value); + pyramid.redGain = DataTools.parseDouble(value); } else if (tag == GREEN_GAIN) { - pyramid.greenGain = new Double(value); + pyramid.greenGain = DataTools.parseDouble(value); } else if (tag == BLUE_GAIN) { - pyramid.blueGain = new Double(value); + pyramid.blueGain = DataTools.parseDouble(value); } else if (tag == RED_OFFSET) { - pyramid.redOffset = new Double(value); + pyramid.redOffset = DataTools.parseDouble(value); } else if (tag == GREEN_OFFSET) { - pyramid.greenOffset = new Double(value); + pyramid.greenOffset = DataTools.parseDouble(value); } else if (tag == BLUE_OFFSET) { - pyramid.blueOffset = new Double(value); + pyramid.blueOffset = DataTools.parseDouble(value); } else if (tag == VALUE) { if (tagPrefix.equals("Channel Wavelength ")) { - pyramid.channelWavelengths.add(new Double(value)); + pyramid.channelWavelengths.add(DataTools.parseDouble(value)); } else if (tagPrefix.startsWith("Objective Working Distance")) { - pyramid.workingDistance = new Double(value); + pyramid.workingDistance = DataTools.parseDouble(value); } else if (tagPrefix.equals("Z start position")) { pyramid.zStart = DataTools.parseDouble(value); @@ -2605,6 +2668,7 @@ class Pyramid { public transient Double zStart; public transient Double zIncrement; public transient ArrayList zValues = new ArrayList(); + public boolean HasAssociatedEtsFile = false; } } diff --git a/components/formats-gpl/src/loci/formats/in/CellWorxReader.java b/components/formats-gpl/src/loci/formats/in/CellWorxReader.java index 244c81add99..4b603927a4d 100644 --- a/components/formats-gpl/src/loci/formats/in/CellWorxReader.java +++ b/components/formats-gpl/src/loci/formats/in/CellWorxReader.java @@ -149,7 +149,7 @@ else if (key.startsWith("WellsSelection")) { int row = Integer.parseInt(key.substring(14)) - 1; String[] mapping = value.split(","); for (int col=0; col 0) { int end = value.indexOf(" ", s + 2); - Double xSize = new Double(value.substring(0, s).trim()); - Double ySize = new Double(value.substring(s + 1, end).trim()); + Double xSize = Double.parseDouble(value.substring(0, s).trim()); + Double ySize = Double.parseDouble(value.substring(s + 1, end).trim()); Length x = FormatTools.getPhysicalSizeX(xSize / getSizeX()); Length y = FormatTools.getPhysicalSizeY(ySize / getSizeY()); @@ -827,7 +827,7 @@ else if (key.startsWith("Channel")) { token = token.trim(); if (token.startsWith("gain")) { String instrumentID = MetadataTools.createLSID("Instrument", 0); - Double gain = new Double(token.replaceAll("gain ", "")); + Double gain = Double.parseDouble(token.replaceAll("gain ", "")); String detectorID = MetadataTools.createLSID("Detector", 0, 0); store.setInstrumentID(instrumentID, 0); @@ -854,8 +854,8 @@ else if (token.startsWith("EX")) { } } - Double emission = new Double(em); - Double excitation = new Double(ex); + Double emission = Double.parseDouble(em); + Double excitation = Double.parseDouble(ex); Length exWave = FormatTools.getExcitationWavelength(excitation); Length emWave = FormatTools.getEmissionWavelength(emission); diff --git a/components/formats-gpl/src/loci/formats/in/ColumbusReader.java b/components/formats-gpl/src/loci/formats/in/ColumbusReader.java index a502fbd1194..2886271d046 100644 --- a/components/formats-gpl/src/loci/formats/in/ColumbusReader.java +++ b/components/formats-gpl/src/loci/formats/in/ColumbusReader.java @@ -186,7 +186,7 @@ public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) Plane p = null; for (Plane plane : planes) { if (plane.series == getSeries() && plane.timepoint == zct[2] && - plane.channel == zct[1]) + plane.channel == zct[1] && plane.z == zct[0]) { p = plane; break; @@ -287,6 +287,9 @@ public int compare(Plane p1, Plane p2) { if (p1.channel != p2.channel) { return p1.channel - p2.channel; } + if (p1.z != p2.z) { + return p1.z - p2.z; + } return 0; } @@ -303,6 +306,7 @@ public int compare(Plane p1, Plane p2) { m.sizeC = 0; m.sizeT = 0; + m.sizeZ = 0; ArrayList uniqueSamples = new ArrayList(); ArrayList uniqueRows = new ArrayList(); @@ -332,10 +336,12 @@ public int compare(Plane p1, Plane p2) { if (p.timepoint >= getSizeT()) { m.sizeT = p.timepoint + 1; } - + if (p.z >= getSizeZ()) { + m.sizeZ = p.z + 1; + } } - m.sizeZ = 1; + m.imageCount = getSizeZ() * getSizeC() * getSizeT(); m.dimensionOrder = "XYCTZ"; m.rgb = false; @@ -376,14 +382,14 @@ public int compare(Plane p1, Plane p2) { store.setWellColumn(new NonNegativeInteger(col), 0, nextWell); for (int field=0; field> 24) & 0xff); int green = (int) ((color >> 16) & 0xff); int red = (int) ((color >> 8) & 0xff); @@ -529,36 +548,36 @@ else if (name.equals("ChannelColor")) { //p.channelColor = new Color(red, green, blue, alpha); } else if (name.equals("MeasurementTimeOffset")) { - p.deltaT = new Double(value); + p.deltaT = DataTools.parseDouble(value); } else if (name.equals("AbsTime")) { p.deltaT = new Timestamp(value).asInstant().getMillis() / 1000d; } else if (name.equals("MainEmissionWavelength")) { - p.emWavelength = new Double(value); + p.emWavelength = DataTools.parseDouble(value); } else if (name.equals("MainExcitationWavelength")) { - p.exWavelength = new Double(value); + p.exWavelength = DataTools.parseDouble(value); } else if (name.equals("ImageResolutionX")) { String unit = attrs.getNamedItem("Unit").getNodeValue(); - p.sizeX = correctUnits(new Double(value), unit); + p.sizeX = correctUnits(DataTools.parseDouble(value), unit); } else if (name.equals("ImageResolutionY")) { String unit = attrs.getNamedItem("Unit").getNodeValue(); - p.sizeY = correctUnits(new Double(value), unit); + p.sizeY = correctUnits(DataTools.parseDouble(value), unit); } else if (name.equals("PositionX")) { String unit = attrs.getNamedItem("Unit").getNodeValue(); - p.positionX = correctUnits(new Double(value), unit); + p.positionX = correctUnits(DataTools.parseDouble(value), unit); } else if (name.equals("PositionY")) { String unit = attrs.getNamedItem("Unit").getNodeValue(); - p.positionY = correctUnits(new Double(value), unit); + p.positionY = correctUnits(DataTools.parseDouble(value), unit); } else if (name.equals("PositionZ")) { String unit = attrs.getNamedItem("Unit").getNodeValue(); - p.positionZ = correctUnits(new Double(value), unit); + p.positionZ = correctUnits(DataTools.parseDouble(value), unit); } } @@ -567,6 +586,9 @@ else if (name.equals("PositionZ")) { } + /** + * Calculate value in micrometers based on input value and units. + */ private Double correctUnits(Double v, String unit) { if (unit == null) { return v; @@ -584,16 +606,16 @@ else if (unit.equals("nm")) { return v; } - private Plane lookupPlane(int row, int col, int field, int t, int c) { + private Plane lookupPlane(int row, int col, int field, int t, int c, int z) { for (Plane p : planes) { if (p.row == row && p.col == col && p.field == field && - p.timepoint == t && p.channel == c) + p.timepoint == t && p.channel == c && p.z == z) { return p; } } - LOGGER.warn("Could not find plane for row={}, column={}, field={}, t={}, c={}", - new Object[] {row, col, field, t, c}); + LOGGER.warn("Could not find plane for row={}, column={}, field={}, t={}, c={}, z={}", + new Object[] {row, col, field, t, c, z}); return null; } @@ -706,10 +728,10 @@ else if (currentName.equals("Reference")) { metadataFiles.add(new Location(value).toString()); } else if (currentName.equals("PlateRows")) { - plateRows = new Integer(value); + plateRows = Integer.parseInt(value); } else if (currentName.equals("PlateColumns")) { - plateColumns = new Integer(value); + plateColumns = Integer.parseInt(value); } currentName = null; @@ -725,6 +747,7 @@ class Plane { public int field; public int timepoint; public int channel; + public int z; public double deltaT; public double emWavelength; public double exWavelength; diff --git a/components/formats-gpl/src/loci/formats/in/DeltavisionReader.java b/components/formats-gpl/src/loci/formats/in/DeltavisionReader.java index f3cc590d4d1..4d415a6f837 100644 --- a/components/formats-gpl/src/loci/formats/in/DeltavisionReader.java +++ b/components/formats-gpl/src/loci/formats/in/DeltavisionReader.java @@ -859,17 +859,17 @@ protected void initExtraMetadata() throws FormatException, IOException { } } - Double x = new Double(pixX); + Double x = Double.valueOf(pixX); Length sizeX = FormatTools.getPhysicalSizeX(x); if (sizeX != null) { store.setPixelsPhysicalSizeX(sizeX, series); } - Double y = new Double(pixY); + Double y = Double.valueOf(pixY); Length sizeY = FormatTools.getPhysicalSizeY(y); if (sizeY != null) { store.setPixelsPhysicalSizeY(sizeY, series); } - Double z = new Double(pixZ); + Double z = Double.valueOf(pixZ); Length sizeZ = FormatTools.getPhysicalSizeZ(z); if (sizeZ != null) { store.setPixelsPhysicalSizeZ(sizeZ, series); @@ -948,12 +948,12 @@ else if (backwardsStageY && xTiles == 1) { DVExtHdrFields hdr = extHdrFields[getPlaneIndex(seriesIndex, i)]; if (expTime[coords[1]] == null) { - expTime[coords[1]] = new Double(hdr.expTime); + expTime[coords[1]] = Double.valueOf(hdr.expTime); } // plane timing store.setPlaneDeltaT( - new Time(new Double(hdr.timeStampSeconds), UNITS.SECOND), series, i); + new Time(Double.valueOf(hdr.timeStampSeconds), UNITS.SECOND), series, i); store.setPlaneExposureTime(new Time(expTime[coords[1]], UNITS.SECOND), series, i); // stage position @@ -967,9 +967,9 @@ else if (backwardsStageY && xTiles == 1) { int w = coords[1]; Length emission = - FormatTools.getEmissionWavelength(new Double(waves[w])); + FormatTools.getEmissionWavelength(Double.valueOf(waves[w])); Length excitation = - FormatTools.getExcitationWavelength(new Double(hdr.exWavelen)); + FormatTools.getExcitationWavelength(Double.valueOf(hdr.exWavelen)); if (emission != null) { store.setChannelEmissionWavelength(emission, series, w); @@ -977,7 +977,7 @@ else if (backwardsStageY && xTiles == 1) { if (excitation != null) { store.setChannelExcitationWavelength(excitation, series, w); } - if (ndFilters[w] == null) ndFilters[w] = new Double(hdr.ndFilter); + if (ndFilters[w] == null) ndFilters[w] = Double.valueOf(hdr.ndFilter); store.setChannelNDFilter(ndFilters[w], series, w); } } @@ -1262,14 +1262,14 @@ private boolean parseLogFile(MetadataStore store) } try { - Double mag = new Double(magnification); + Double mag = DataTools.parseDouble(magnification); store.setObjectiveNominalMagnification(mag, 0, 0); } catch (NumberFormatException e) { LOGGER.warn("Could not parse magnification '{}'", magnification); } try { - store.setObjectiveLensNA(new Double(na), 0, 0); + store.setObjectiveLensNA(DataTools.parseDouble(na), 0, 0); } catch (NumberFormatException e) { LOGGER.warn("Could not parse N.A. '{}'", na); @@ -1308,7 +1308,7 @@ else if (key.equals("Pixel Size")) { for (int q=0; q= 0) { store.setPointTheZ(new NonNegativeInteger( (int) points[obj][contour][i][2]), obj, nextShape); @@ -347,7 +348,7 @@ protected void initFile(String id) throws FormatException, IOException { store.setPolygonID(shapeID, obj, nextShape); store.setPolygonStrokeColor( new Color(r, g, b, 0xff), obj, nextShape); - l = new Length(new Double(lineWidth2D), UNITS.PIXEL); + l = new Length(Double.valueOf(lineWidth2D), UNITS.PIXEL); store.setPolygonStrokeWidth(l, obj, nextShape); if (lineStyle == 1) { store.setPolygonStrokeDashArray("5", obj, nextShape); @@ -363,7 +364,7 @@ protected void initFile(String id) throws FormatException, IOException { store.setPolylineID(shapeID, obj, nextShape); store.setPolylineStrokeColor( new Color(r, g, b, 0xff), obj, nextShape); - l = new Length(new Double(lineWidth2D), UNITS.PIXEL); + l = new Length(Double.valueOf(lineWidth2D), UNITS.PIXEL); store.setPolylineStrokeWidth(l, obj, nextShape); if (lineStyle == 1) { store.setPolylineStrokeDashArray("5", obj, nextShape); diff --git a/components/formats-gpl/src/loci/formats/in/INRReader.java b/components/formats-gpl/src/loci/formats/in/INRReader.java index f04b8ef4923..459145c6278 100644 --- a/components/formats-gpl/src/loci/formats/in/INRReader.java +++ b/components/formats-gpl/src/loci/formats/in/INRReader.java @@ -27,6 +27,7 @@ import java.io.IOException; +import loci.common.DataTools; import loci.common.RandomAccessInputStream; import loci.formats.CoreMetadata; import loci.formats.FormatException; @@ -131,13 +132,13 @@ else if (key.equals("PIXSIZE")) { nBits = Integer.parseInt(bits); } else if (key.equals("VX")) { - physicalSizeX = new Double(value); + physicalSizeX = DataTools.parseDouble(value); } else if (key.equals("VY")) { - physicalSizeY = new Double(value); + physicalSizeY = DataTools.parseDouble(value); } else if (key.equals("VZ")) { - physicalSizeZ = new Double(value); + physicalSizeZ = DataTools.parseDouble(value); } } } diff --git a/components/formats-gpl/src/loci/formats/in/IPLabReader.java b/components/formats-gpl/src/loci/formats/in/IPLabReader.java index 922e1bade09..3c0a740f715 100644 --- a/components/formats-gpl/src/loci/formats/in/IPLabReader.java +++ b/components/formats-gpl/src/loci/formats/in/IPLabReader.java @@ -302,10 +302,10 @@ else if (tag.equals("roi ") && int numRoiPts = in.readInt(); store.setRectangleID(MetadataTools.createLSID("Shape", 0, 0), 0, 0); - store.setRectangleX(new Double(roiLeft), 0, 0); - store.setRectangleY(new Double(roiTop), 0, 0); - store.setRectangleWidth(new Double(roiRight - roiLeft), 0, 0); - store.setRectangleHeight(new Double(roiBottom - roiTop), 0, 0); + store.setRectangleX(Double.valueOf(roiLeft), 0, 0); + store.setRectangleY(Double.valueOf(roiTop), 0, 0); + store.setRectangleWidth(Double.valueOf(roiRight - roiLeft), 0, 0); + store.setRectangleHeight(Double.valueOf(roiBottom - roiTop), 0, 0); String roiID = MetadataTools.createLSID("ROI", 0, 0); store.setROIID(roiID, 0); store.setImageROIRef(roiID, 0, 0); @@ -345,7 +345,7 @@ else if (tag.equals("unit")) { break; } - if (i == 0) pixelSize = new Double(unitsPerPixel); + if (i == 0) pixelSize = Double.valueOf(unitsPerPixel); addGlobalMetaList("UnitName", xUnitName); } @@ -396,11 +396,11 @@ else if (tagBytes[0] == 0x1a && tagBytes[1] == (byte) 0xd9 && for (int c=0; c= colors.size()) { + if (lastChannel < 0 || lastChannel >= colors.size() || colors.get(lastChannel) == null) { return null; } @@ -370,25 +370,25 @@ protected void initFile(String id) throws FormatException, IOException { if (cIndex < gain.size()) { try { - gainValue = new Float(gain.get(cIndex)); + gainValue = Float.parseFloat(gain.get(cIndex)); } catch (NumberFormatException e) { } } if (cIndex < pinhole.size()) { try { - pinholeValue = new Integer(pinhole.get(cIndex)); + pinholeValue = Integer.parseInt(pinhole.get(cIndex)); } catch (NumberFormatException e) { } } if (cIndex < emWave.size()) { try { - emWaveValue = new Integer(emWave.get(cIndex)); + emWaveValue = Integer.parseInt(emWave.get(cIndex)); } catch (NumberFormatException e) { } } if (cIndex < exWave.size()) { try { - exWaveValue = new Integer(exWave.get(cIndex)); + exWaveValue = Integer.parseInt(exWave.get(cIndex)); } catch (NumberFormatException e) { } } @@ -397,18 +397,18 @@ protected void initFile(String id) throws FormatException, IOException { if (cIndex < channelMin.size()) { try { - minValue = new Double(channelMin.get(cIndex)); + minValue = DataTools.parseDouble(channelMin.get(cIndex)); } catch (NumberFormatException e) { } } if (cIndex < channelMax.size()) { try { - maxValue = new Double(channelMax.get(cIndex)); + maxValue = DataTools.parseDouble(channelMax.get(cIndex)); } catch (NumberFormatException e) { } } - if (i < colors.size()) { + if (i < colors.size() && colors.get(i) != null) { double[] color = colors.get(i); Color realColor = new Color( (int) (color[0] * 255), (int) (color[1] * 255), diff --git a/components/formats-gpl/src/loci/formats/in/ImarisTiffReader.java b/components/formats-gpl/src/loci/formats/in/ImarisTiffReader.java index ddb6bc5d2fc..8f2e77905b8 100644 --- a/components/formats-gpl/src/loci/formats/in/ImarisTiffReader.java +++ b/components/formats-gpl/src/loci/formats/in/ImarisTiffReader.java @@ -33,6 +33,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import loci.common.DataTools; import loci.formats.CoreMetadata; import loci.formats.FormatException; import loci.formats.FormatTools; @@ -145,11 +146,11 @@ protected void initFile(String id) throws FormatException, IOException { description = value; } else if (key.equals("LSMEmissionWavelength") && !value.equals("0")) { - emWave.add(new Double(value)); + emWave.add(DataTools.parseDouble(value)); } else if (key.equals("LSMExcitationWavelength") && !value.equals("0")) { - exWave.add(new Double(value)); + exWave.add(DataTools.parseDouble(value)); } else if (key.equals("Name") && !currentId.endsWith(value)) { channelNames.add(value); diff --git a/components/formats-gpl/src/loci/formats/in/InCellReader.java b/components/formats-gpl/src/loci/formats/in/InCellReader.java index 53e343f1693..2c8cdd988ac 100644 --- a/components/formats-gpl/src/loci/formats/in/InCellReader.java +++ b/components/formats-gpl/src/loci/formats/in/InCellReader.java @@ -1047,7 +1047,7 @@ else if (qName.equals("ObjectiveCalibration")) { Double mag = Double.parseDouble(attributes.getValue("magnification")); store.setObjectiveNominalMagnification(mag, 0, 0); - store.setObjectiveLensNA(new Double( + store.setObjectiveLensNA(DataTools.parseDouble( attributes.getValue("numerical_aperture")), 0, 0); try { store.setObjectiveImmersion(MetadataTools.getImmersion("Other"), 0, 0); @@ -1068,20 +1068,20 @@ else if (qName.equals("ObjectiveCalibration")) { LOGGER.warn("", e); } - Double pixelSizeX = new Double(attributes.getValue("pixel_width")); - Double pixelSizeY = new Double(attributes.getValue("pixel_height")); - refractive = new Double(attributes.getValue("refractive_index")); + Double pixelSizeX = DataTools.parseDouble(attributes.getValue("pixel_width")); + Double pixelSizeY = DataTools.parseDouble(attributes.getValue("pixel_height")); + refractive = DataTools.parseDouble(attributes.getValue("refractive_index")); x = FormatTools.getPhysicalSizeX(pixelSizeX); y = FormatTools.getPhysicalSizeY(pixelSizeY); } else if (qName.equals("ExcitationFilter")) { String wave = attributes.getValue("wavelength"); - if (wave != null) exWaves.add(new Double(wave)); + if (wave != null) exWaves.add(DataTools.parseDouble(wave)); } else if (qName.equals("EmissionFilter")) { String wave = attributes.getValue("wavelength"); - if (wave != null) emWaves.add(new Double(wave)); + if (wave != null) emWaves.add(DataTools.parseDouble(wave)); channelNames.add(attributes.getValue("name")); } else if (qName.equals("Camera")) { @@ -1106,14 +1106,14 @@ else if (qName.equals("Gain")) { return; } try { - gain = new Double(value); + gain = DataTools.parseDouble(value); } catch (NumberFormatException e) { LOGGER.debug("Could not parse gain '" + value + "'", e); } } else if (qName.equals("PlateTemperature")) { - temperature = new Double(attributes.getValue("value")); + temperature = DataTools.parseDouble(attributes.getValue("value")); } else if (qName.equals("Plate")) { nextPlate++; diff --git a/components/formats-gpl/src/loci/formats/in/InveonReader.java b/components/formats-gpl/src/loci/formats/in/InveonReader.java index d271876c92c..457cc1896e9 100644 --- a/components/formats-gpl/src/loci/formats/in/InveonReader.java +++ b/components/formats-gpl/src/loci/formats/in/InveonReader.java @@ -335,13 +335,22 @@ else if (key.equals("data_file_pointer")) { } // pixel sizes stored in mm else if (key.equals("pixel_size_x")) { - pixelSizeX = new Double(value) * 1000; + Double size = DataTools.parseDouble(value); + if (size != null) { + pixelSizeX = size * 1000; + } } else if (key.equals("pixel_size_y")) { - pixelSizeY = new Double(value) * 1000; + Double size = DataTools.parseDouble(value); + if (size != null) { + pixelSizeY = size * 1000; + } } else if (key.equals("pixel_size_z")) { - pixelSizeZ = new Double(value) * 1000; + Double size = DataTools.parseDouble(value); + if (size != null) { + pixelSizeZ = size * 1000; + } } addGlobalMeta(key, value); diff --git a/components/formats-gpl/src/loci/formats/in/IvisionReader.java b/components/formats-gpl/src/loci/formats/in/IvisionReader.java index 22b758de9b5..23efc4766e4 100644 --- a/components/formats-gpl/src/loci/formats/in/IvisionReader.java +++ b/components/formats-gpl/src/loci/formats/in/IvisionReader.java @@ -27,6 +27,7 @@ import java.io.IOException; +import loci.common.DataTools; import loci.common.DateTools; import loci.common.RandomAccessInputStream; import loci.common.xml.BaseHandler; @@ -293,7 +294,7 @@ protected void initFile(String id) throws FormatException, IOException { if (deltaT != null) { Double increment = 0d; try { - increment = new Double(deltaT); + increment = DataTools.parseDouble(deltaT); } catch (NumberFormatException e) { LOGGER.debug("Failed to parse time increment", e); @@ -327,7 +328,7 @@ protected void initFile(String id) throws FormatException, IOException { store.setDetectorSettingsBinning(MetadataTools.getBinning(binX + "x" + binY), 0, 0); if (gain != null) { try { - store.setDetectorSettingsGain(new Double(gain), 0, 0); + store.setDetectorSettingsGain(DataTools.parseDouble(gain), 0, 0); } catch (NumberFormatException e) { LOGGER.debug("Failed to parse detector gain", e); @@ -359,19 +360,19 @@ public void endElement(String uri, String localName, String qName) { else if ("iplab:Interval_T".equals(key)) deltaT = value; else if ("iplab:Objective_Mag".equals(key)) { try { - magnification = new Double(value); + magnification = DataTools.parseDouble(value); } catch (NumberFormatException e) { } } else if ("iplab:Objective_NA".equals(key)) { try { - lensNA = new Double(value); + lensNA = DataTools.parseDouble(value); } catch (NumberFormatException e) { } } else if ("iplab:Objective_RI".equals(key)) { try { - refractiveIndex = new Double(value); + refractiveIndex = DataTools.parseDouble(value); } catch (NumberFormatException e) { } } diff --git a/components/formats-gpl/src/loci/formats/in/KodakReader.java b/components/formats-gpl/src/loci/formats/in/KodakReader.java index 2dd72f6be94..77cc26ea569 100644 --- a/components/formats-gpl/src/loci/formats/in/KodakReader.java +++ b/components/formats-gpl/src/loci/formats/in/KodakReader.java @@ -30,6 +30,7 @@ import java.util.regex.Pattern; import loci.common.Constants; +import loci.common.DataTools; import loci.common.DateTools; import loci.common.RandomAccessInputStream; import loci.formats.CoreMetadata; @@ -204,7 +205,7 @@ else if (key.equals("Capture Time/Date")) { } } else if (key.equals("Exposure Time")) { - Double exposureTime = new Double(value.substring(0, value.indexOf(' '))); + Double exposureTime = DataTools.parseDouble(value.substring(0, value.indexOf(' '))); if (exposureTime != null) { store.setPlaneExposureTime(new Time(exposureTime, UNITS.SECOND), 0, 0); } @@ -214,7 +215,7 @@ else if (key.equals("Vertical Resolution")) { if (value.indexOf(' ') > 0) { value = value.substring(0, value.indexOf(' ')); } - Double size = new Double(value); + Double size = DataTools.parseDouble(value); size = 1.0 / (size * (1.0 / 25400)); Length sizeY = FormatTools.getPhysicalSizeY(size); @@ -227,7 +228,7 @@ else if (key.equals("Horizontal Resolution")) { if (value.indexOf(' ') > 0) { value = value.substring(0, value.indexOf(' ')); } - Double size = new Double(value); + Double size = DataTools.parseDouble(value); size = 1.0 / (size * (1.0 / 25400)); Length sizeX = FormatTools.getPhysicalSizeX(size); @@ -240,11 +241,11 @@ else if (key.equals("CCD Temperature")) { Matcher hexMatcher = Pattern.compile("0x([0-9A-F]+)").matcher(value); if (hexMatcher.matches()) { // CCD temperature stored as a hexadecimal string such as "0xEB". - temp = new Double(Integer.parseInt(hexMatcher.group(1), 16)); + temp = Double.valueOf(Integer.parseInt(hexMatcher.group(1), 16)); LOGGER.debug("CCD temperature detected as {}; assumed to be invalid", temp); } else { - temp = new Double(value.substring(0, value.indexOf(' '))); + temp = DataTools.parseDouble(value.substring(0, value.indexOf(' '))); store.setImagingEnvironmentTemperature( new Temperature(temp, UNITS.CELSIUS), 0); } diff --git a/components/formats-gpl/src/loci/formats/in/L2DReader.java b/components/formats-gpl/src/loci/formats/in/L2DReader.java index a55515d06bf..3f3efd4a379 100644 --- a/components/formats-gpl/src/loci/formats/in/L2DReader.java +++ b/components/formats-gpl/src/loci/formats/in/L2DReader.java @@ -353,7 +353,7 @@ else if (key.equals("ScanChannels")) { for (int q=0; q getSeriesCount()) { + LOGGER.debug("Adjusting image offsets; found {} expected {}", + offsets.size(), getSeriesCount()); Long[] storedOffsets = offsets.toArray(new Long[offsets.size()]); + for (int i=0; i 0) { - bytesPerAxis.put(new Integer(bytes), "C"); + bytesPerAxis.put(Integer.valueOf(bytes), "C"); } } else if (qName.equals("DimensionDescription")) { @@ -415,7 +416,7 @@ else if (unit.equals("m")) { physicalLen *= 1000000; } - Double physicalSize = new Double(physicalLen); + Double physicalSize = Double.valueOf(physicalLen); CoreMetadata coreMeta = core.get(core.size() - 1); @@ -445,11 +446,11 @@ else if (unit.equals("m")) { if (coreMeta.sizeY != 0) { if (coreMeta.sizeZ == 1) { coreMeta.sizeZ = len; - bytesPerAxis.put(new Integer(nBytes), "Z"); + bytesPerAxis.put(Integer.valueOf(nBytes), "Z"); } else if (coreMeta.sizeT == 1) { coreMeta.sizeT = len; - bytesPerAxis.put(new Integer(nBytes), "T"); + bytesPerAxis.put(Integer.valueOf(nBytes), "T"); } } else { @@ -471,11 +472,11 @@ else if (coreMeta.sizeT == 1) { if (sizeY != null) { store.setPixelsPhysicalSizeY(sizeY, numDatasets); } - bytesPerAxis.put(new Integer(nBytes), "Y"); + bytesPerAxis.put(Integer.valueOf(nBytes), "Y"); } else { coreMeta.sizeZ = len; - bytesPerAxis.put(new Integer(nBytes), "Z"); + bytesPerAxis.put(Integer.valueOf(nBytes), "Z"); } break; case 4: // T axis @@ -488,11 +489,11 @@ else if (coreMeta.sizeT == 1) { if (sizeY != null) { store.setPixelsPhysicalSizeY(sizeY, numDatasets); } - bytesPerAxis.put(new Integer(nBytes), "Y"); + bytesPerAxis.put(Integer.valueOf(nBytes), "Y"); } else { coreMeta.sizeT = len; - bytesPerAxis.put(new Integer(nBytes), "T"); + bytesPerAxis.put(Integer.valueOf(nBytes), "T"); } break; default: @@ -511,10 +512,10 @@ else if (qName.equals("ScannerSettingRecord") && store.setMicroscopeType(MicroscopeType.OTHER, numDatasets); } else if (id.equals("dblPinhole")) { - pinhole = new Double(Double.parseDouble(value) * 1000000); + pinhole = Double.valueOf(Double.parseDouble(value) * 1000000); } else if (id.equals("dblZoom")) { - zoom = new Double(value); + zoom = DataTools.parseDouble(value); } else if (id.equals("dblStepSize")) { double zStep = Double.parseDouble(value) * 1000000; @@ -524,7 +525,7 @@ else if (id.equals("dblStepSize")) { } } else if (id.equals("nDelayTime_s")) { - Double timeIncrement = new Double(value); + Double timeIncrement = DataTools.parseDouble(value); if (timeIncrement != null) { store.setPixelsTimeIncrement(new Time(timeIncrement, UNITS.SECOND), numDatasets); } @@ -542,7 +543,7 @@ else if (id.indexOf("WFC") == 1) { if (channel == null) channel = new Channel(); if (id.endsWith("ExposureTime") && c < numChannels) { try { - Double exposureTime = new Double(value); + Double exposureTime = DataTools.parseDouble(value); if (exposureTime != null) { store.setPlaneExposureTime(new Time(exposureTime, UNITS.SECOND), numDatasets, c); } @@ -550,7 +551,7 @@ else if (id.indexOf("WFC") == 1) { catch (IndexOutOfBoundsException e) { } } else if (id.endsWith("Gain")) { - channel.gain = new Double(value); + channel.gain = DataTools.parseDouble(value); String detectorID = MetadataTools.createLSID("Detector", numDatasets, 0); @@ -559,7 +560,7 @@ else if (id.endsWith("Gain")) { store.setDetectorType(DetectorType.CCD, numDatasets, 0); } else if (id.endsWith("WaveLength")) { - Double exWave = new Double(value); + Double exWave = DataTools.parseDouble(value); Length ex = FormatTools.getExcitationWavelength(exWave); if (ex != null) { channel.exWave = ex; @@ -582,7 +583,7 @@ else if (qName.equals("FilterSettingRecord") && CoreMetadata coreMeta = core.get(numDatasets); if (attribute.equals("NumericalAperture")) { - store.setObjectiveLensNA(new Double(variant), numDatasets, 0); + store.setObjectiveLensNA(DataTools.parseDouble(variant), numDatasets, 0); } else if (attribute.equals("OrderNumber")) { store.setObjectiveSerialNumber(variant, numDatasets, 0); @@ -601,11 +602,11 @@ else if (objectClass.equals("CDetectionUnit")) { } else if (attribute.equals("HighVoltage")) { Detector d = detectors.get(detectors.size() - 1); - d.voltage = new Double(variant); + d.voltage = DataTools.parseDouble(variant); } else if (attribute.equals("VideoOffset")) { Detector d = detectors.get(detectors.size() - 1); - d.offset = new Double(variant); + d.offset = DataTools.parseDouble(variant); } } else if (attribute.equals("Objective")) { @@ -622,7 +623,7 @@ else if (attribute.equals("Objective")) { String na = token.substring(x + 1); store.setObjectiveNominalMagnification(mag, numDatasets, 0); - store.setObjectiveLensNA(new Double(na), numDatasets, 0); + store.setObjectiveLensNA(DataTools.parseDouble(na), numDatasets, 0); } else { model.append(token); @@ -664,7 +665,7 @@ else if (attribute.equals("RefractionIndex")) { String id = MetadataTools.createLSID("Objective", numDatasets, 0); store.setObjectiveID(id, numDatasets, 0); store.setObjectiveSettingsID(id, numDatasets); - store.setObjectiveSettingsRefractiveIndex(new Double(variant), + store.setObjectiveSettingsRefractiveIndex(DataTools.parseDouble(variant), numDatasets); } else if (attribute.equals("XPos")) { @@ -725,9 +726,9 @@ else if (attributes.getValue("Description").endsWith("(right)")) { } else if (qName.equals("Detector") && level != MetadataLevel.MINIMUM) { String v = attributes.getValue("Gain"); - Double gain = v == null ? null : new Double(v); + Double gain = v == null ? null : DataTools.parseDouble(v); v = attributes.getValue("Offset"); - Double offset = v == null ? null : new Double(v); + Double offset = v == null ? null : DataTools.parseDouble(v); boolean active = "1".equals(attributes.getValue("IsActive")); if (active) { @@ -832,7 +833,7 @@ else if (qName.equals("LaserLineSetting") && level != MetadataLevel.MINIMUM) l.index += (2 - (qualifier / 10)); if (l.index < 0) l.index = 0; l.id = MetadataTools.createLSID("LightSource", numDatasets, l.index); - l.wavelength = new Double(attributes.getValue("LaserLine")); + l.wavelength = DataTools.parseDouble(attributes.getValue("LaserLine")); while (l.index > laserCount) { String lsid = MetadataTools.createLSID("LightSource", numDatasets, laserCount); @@ -890,7 +891,7 @@ else if (qName.equals("RelTimeStamp") && level != MetadataLevel.MINIMUM) { CoreMetadata coreMeta = core.get(numDatasets); int nImages = coreMeta.sizeZ * coreMeta.sizeT * coreMeta.sizeC; if (count < nImages) { - Double time = new Double(attributes.getValue("Time")); + Double time = DataTools.parseDouble(attributes.getValue("Time")); if (time != null) { store.setPlaneDeltaT(new Time(time, UNITS.SECOND), numDatasets, count++); } @@ -919,11 +920,11 @@ else if (qName.equals("Vertex") && level != MetadataLevel.MINIMUM) { String y = attributes.getValue("y"); if (x != null) { x = x.replaceAll(",", "."); - roi.x.add(new Double(x)); + roi.x.add(DataTools.parseDouble(x)); } if (y != null) { y = y.replaceAll(",", "."); - roi.y.add(new Double(y)); + roi.y.add(DataTools.parseDouble(y)); } } else if (qName.equals("ROI")) { @@ -1038,7 +1039,7 @@ public void storeROI(MetadataStore store, int series, int roi) { store.setLabelFontSize(fontSize, roi, 0); } } - Length l = new Length(new Double(linewidth), UNITS.PIXEL); + Length l = new Length(Double.valueOf(linewidth), UNITS.PIXEL); store.setLabelStrokeWidth(l, roi, 0); if (!normalized) normalize(); diff --git a/components/formats-gpl/src/loci/formats/in/LeicaReader.java b/components/formats-gpl/src/loci/formats/in/LeicaReader.java index 2ec4d813d53..5f890fb32f5 100644 --- a/components/formats-gpl/src/loci/formats/in/LeicaReader.java +++ b/components/formats-gpl/src/loci/formats/in/LeicaReader.java @@ -211,7 +211,7 @@ public boolean isThisType(RandomAccessInputStream stream) throws IOException { TiffParser tp = new TiffParser(stream); IFD ifd = tp.getFirstIFD(); if (ifd == null) return false; - return ifd.containsKey(new Integer(LEICA_MAGIC_TAG)); + return ifd.containsKey(Integer.valueOf(LEICA_MAGIC_TAG)); } /* @see loci.formats.IFormatReader#get8BitLookupTable() */ @@ -1339,10 +1339,10 @@ private void parseInstrumentData(MetadataStore store, int blockNum) try { if (tokens[2].equals("VideoOffset")) { - detector.offset = new Double(data); + detector.offset = DataTools.parseDouble(data); } else if (tokens[2].equals("HighVoltage")) { - detector.voltage = new Double(data); + detector.voltage = DataTools.parseDouble(data); } else if (tokens[2].equals("State")) { detector.active = data.equals("Active"); @@ -1369,7 +1369,7 @@ else if (tokens[0].startsWith("CTurret")) { int objective = Integer.parseInt(tokens[3]); if (tokens[2].equals("NumericalAperture")) { - store.setObjectiveLensNA(new Double(data), series, objective); + store.setObjectiveLensNA(DataTools.parseDouble(data), series, objective); } else if (tokens[2].equals("Objective")) { String[] objectiveData = data.split(" "); @@ -1420,7 +1420,7 @@ else if (immersion == null) { store.setObjectiveCorrection( MetadataTools.getCorrection(correction), series, objective); store.setObjectiveModel(model.toString().trim(), series, objective); - store.setObjectiveLensNA(new Double(na), series, objective); + store.setObjectiveLensNA(DataTools.parseDouble(na), series, objective); Double magnification = Double.parseDouble(mag); store.setObjectiveNominalMagnification( @@ -1430,7 +1430,7 @@ else if (tokens[2].equals("OrderNumber")) { store.setObjectiveSerialNumber(data, series, objective); } else if (tokens[2].equals("RefractionIndex")) { - store.setObjectiveSettingsRefractiveIndex(new Double(data), series); + store.setObjectiveSettingsRefractiveIndex(DataTools.parseDouble(data), series); } // link Objective to Image @@ -1609,14 +1609,14 @@ else if (contentID.startsWith("nDelayTime")) { } } if (channel < emWaves[i].size()) { - Double wave = new Double(emWaves[i].get(channel).toString()); + Double wave = DataTools.parseDouble(emWaves[i].get(channel).toString()); Length emission = FormatTools.getEmissionWavelength(wave); if (emission != null) { store.setChannelEmissionWavelength(emission, i, channel); } } if (channel < exWaves[i].size()) { - Double wave = new Double(exWaves[i].get(channel).toString()); + Double wave = DataTools.parseDouble(exWaves[i].get(channel).toString()); Length ex = FormatTools.getExcitationWavelength(wave); if (ex != null) { store.setChannelExcitationWavelength(ex, i, channel); diff --git a/components/formats-gpl/src/loci/formats/in/LeicaSCNReader.java b/components/formats-gpl/src/loci/formats/in/LeicaSCNReader.java index f6e76d32afc..276cedf8c27 100644 --- a/components/formats-gpl/src/loci/formats/in/LeicaSCNReader.java +++ b/components/formats-gpl/src/loci/formats/in/LeicaSCNReader.java @@ -45,6 +45,7 @@ import ome.xml.model.enums.IlluminationType; import ome.xml.model.primitives.Timestamp; +import loci.common.DataTools; import loci.common.RandomAccessInputStream; import loci.common.xml.XMLTools; import loci.formats.CoreMetadata; @@ -395,8 +396,8 @@ protected void initMetadataStore() throws FormatException { // Leica units are nanometres; convert to µm double sizeX = i.vSizeX / 1000.0; double sizeY = i.vSizeY / 1000.0; - final Length offsetX = new Length(i.vOffsetX, UNITS.NM); - final Length offsetY = new Length(i.vOffsetY, UNITS.NM); + final Length offsetX = new Length(i.vOffsetX, UNITS.NANOMETER); + final Length offsetY = new Length(i.vOffsetY, UNITS.NANOMETER); double sizeZ = i.vSpacingZ / 1000.0; store.setPixelsPhysicalSizeX( @@ -422,7 +423,7 @@ protected void initMetadataStore() throws FormatException { Double mag = Double.parseDouble(i.objMag); store.setObjectiveNominalMagnification(mag, inst, objectiveidno); store.setObjectiveCalibratedMagnification(mag, inst, objectiveidno); - store.setObjectiveLensNA(new Double(i.illumNA), inst, objectiveidno); + store.setObjectiveLensNA(DataTools.parseDouble(i.illumNA), inst, objectiveidno); objectiveidno++; } diff --git a/components/formats-gpl/src/loci/formats/in/LiFlimReader.java b/components/formats-gpl/src/loci/formats/in/LiFlimReader.java index c3b5aaee6c2..828861b8095 100644 --- a/components/formats-gpl/src/loci/formats/in/LiFlimReader.java +++ b/components/formats-gpl/src/loci/formats/in/LiFlimReader.java @@ -390,7 +390,7 @@ else if (version.equals("2.0")){ addGlobalMeta(metaKey, value); if (metaKey.startsWith(TIMESTAMP_KEY)) { - Integer index = new Integer(metaKey.replaceAll(TIMESTAMP_KEY, "")); + Integer index = Integer.parseInt(metaKey.replaceAll(TIMESTAMP_KEY, "")); stampValues.put(index, value); } else if (metaKey.equals("ROI: INFO - numregions")) { @@ -401,7 +401,7 @@ else if (metaKey.startsWith("ROI: ROI") && { int start = metaKey.lastIndexOf("ROI") + 3; int end = metaKey.indexOf(" ", start); - Integer index = new Integer(metaKey.substring(start, end)); + Integer index = Integer.parseInt(metaKey.substring(start, end)); ROI roi = rois.get(index); if (roi == null) roi = new ROI(); @@ -410,7 +410,7 @@ else if (metaKey.startsWith("ROI: ROI") && } else if (metaKey.indexOf(" - p") >= 0) { String p = metaKey.substring(metaKey.indexOf(" - p") + 4); - roi.points.put(new Integer(p), value.replaceAll(" ", ",")); + roi.points.put(Integer.parseInt(p), value.replaceAll(" ", ",")); } rois.put(index, roi); } @@ -423,7 +423,7 @@ else if (metaKey.equals("ExposureTime")) { } else { exposureTimeUnit = UNITS.SECOND; } - exposureTime = new Double(expTime); + exposureTime = Double.valueOf(expTime); } } } @@ -567,7 +567,7 @@ private void initOMEMetadata() { } else { long ms = stamp - firstStamp; - deltaT = new Double(ms / 1000.0); + deltaT = Double.valueOf(ms / 1000.0); } for (int c=0; c columns, String[] data, int series, store.setEllipseID(MetadataTools.createLSID("Shape", roi, 0), roi, 0); store.setEllipseTheT(new NonNegativeInteger(time), roi, 0); store.setEllipseTheZ(new NonNegativeInteger(z), roi, 0); - store.setEllipseX(new Double(data[columns.indexOf("Col")]), roi, 0); - store.setEllipseY(new Double(data[columns.indexOf("Row")]), roi, 0); + store.setEllipseX(DataTools.parseDouble(data[columns.indexOf("Col")]), roi, 0); + store.setEllipseY(DataTools.parseDouble(data[columns.indexOf("Row")]), roi, 0); store.setEllipseText(data[columns.indexOf("Label")], roi, 0); double diam = Double.parseDouble(data[columns.indexOf("Cell Diam.")]); @@ -1085,10 +1085,10 @@ else if (key.equals("Carrier")) { store.setPlateName(value, 0); } else if (key.equals("Pixel_X")) { - physicalSizeX = new Double(value); + physicalSizeX = DataTools.parseDouble(value); } else if (key.equals("Pixel_Y")) { - physicalSizeY = new Double(value); + physicalSizeY = DataTools.parseDouble(value); } else if (key.equals("Objective_ID")) { store.setObjectiveID( @@ -1109,7 +1109,7 @@ else if (key.equals("Time")) { date += " " + value; } else if (key.equals("Exposure")) { - exposure = new Double(value); + exposure = DataTools.parseDouble(value); } } } diff --git a/components/formats-gpl/src/loci/formats/in/MetamorphHandler.java b/components/formats-gpl/src/loci/formats/in/MetamorphHandler.java index 8eff5190b52..e6bd7408ae3 100644 --- a/components/formats-gpl/src/loci/formats/in/MetamorphHandler.java +++ b/components/formats-gpl/src/loci/formats/in/MetamorphHandler.java @@ -256,7 +256,7 @@ else if (key.equals("stage-position-y")) { } } if (key.equals("wavelength")) { - wavelengths.add(new Integer(value)); + wavelengths.add(Integer.parseInt(value)); } else if (key.equals("acquisition-time-local")) { date = value; diff --git a/components/formats-gpl/src/loci/formats/in/MetamorphReader.java b/components/formats-gpl/src/loci/formats/in/MetamorphReader.java index 82b27902d0c..fa789935731 100644 --- a/components/formats-gpl/src/loci/formats/in/MetamorphReader.java +++ b/components/formats-gpl/src/loci/formats/in/MetamorphReader.java @@ -1170,7 +1170,7 @@ else if (commentEntry instanceof TiffIFDEntry) { line.lastIndexOf("\"", lastQuote - 1) + 1, lastQuote); if (key.equals("z-position")) { - xmlZPosition = new Double(value); + xmlZPosition = DataTools.parseDouble(value); } else if (key.equals("acquisition-time-local")) { timestamps.add(value); @@ -1473,7 +1473,7 @@ else if (key.equals("Gain")) { nextSpace = value.length(); } try { - gain = new Double(value.substring(space, nextSpace)); + gain = DataTools.parseDouble(value.substring(space, nextSpace)); } catch (NumberFormatException e) { } } @@ -2004,13 +2004,13 @@ else if (valOrOffset == 0 && getSizeZ() < mmPlanes) { if (value instanceof TiffRational) { sizeX = ((TiffRational) value).doubleValue(); } - else sizeX = new Double(value.toString()); + else sizeX = DataTools.parseDouble(value.toString()); } if ("YCalibration".equals(key) && value != null) { if (value instanceof TiffRational) { sizeY = ((TiffRational) value).doubleValue(); } - else sizeY = new Double(value.toString()); + else sizeY = DataTools.parseDouble(value.toString()); } } in.seek(saveLoc); diff --git a/components/formats-gpl/src/loci/formats/in/MicroCTReader.java b/components/formats-gpl/src/loci/formats/in/MicroCTReader.java index ab3b5cac95d..490d7143be2 100644 --- a/components/formats-gpl/src/loci/formats/in/MicroCTReader.java +++ b/components/formats-gpl/src/loci/formats/in/MicroCTReader.java @@ -236,7 +236,7 @@ else if (key.equals("bits")) { ms.pixelType = FormatTools.pixelTypeFromBytes(bits / 8, true, false); } else if (key.equals("elementsize")) { - Double size = new Double(value); + Double size = DataTools.parseDouble(value); // physical size is stored in mm, not um physicalSize = new PositiveFloat(size * 1000); } @@ -328,7 +328,7 @@ private void processKey(String key, String value) { addGlobalMeta(key, value); if (key.equals("Exposure Time (ms)")) { - exposureTime = new Double(value); + exposureTime = DataTools.parseDouble(value); exposureTime /= 1000.0; } else if (key.equals("Description.txt")) { diff --git a/components/formats-gpl/src/loci/formats/in/ND2Handler.java b/components/formats-gpl/src/loci/formats/in/ND2Handler.java index 53ec64c10cf..48d11f30895 100644 --- a/components/formats-gpl/src/loci/formats/in/ND2Handler.java +++ b/components/formats-gpl/src/loci/formats/in/ND2Handler.java @@ -154,7 +154,7 @@ public void populateROIs(MetadataStore store) { store.setLabelFontSize(new Length(fontSize, UNITS.POINT), r, 0); } store.setLabelText(roi.get("eval-text"), r, 0); - Length l = new Length(new Double(roi.get("line-width")), UNITS.PIXEL); + Length l = new Length(Double.parseDouble(roi.get("line-width")), UNITS.PIXEL); store.setLabelStrokeWidth(l, r, 0); String rectangle = roi.get("rectangle"); @@ -568,7 +568,7 @@ else if (qName.equals("dPinholeRadius")) { } else if (qName.endsWith("ChannelColor")) { String name = qName.substring(0, qName.indexOf("Channel")); - colors.put(name, new Integer(value)); + colors.put(name, Integer.parseInt(value)); } else if (qName.endsWith("DyeName")) { int channelIndex = qName.indexOf("Channel"); @@ -885,11 +885,11 @@ else if (key.equals("Line")) { } else if (key.equalsIgnoreCase("Emission wavelength")) { String[] v = value.split(" "); - emWave.add(new Double(v[0])); + emWave.add(Double.parseDouble(v[0])); } else if (key.equalsIgnoreCase("Excitation wavelength")) { String[] v = value.split(" "); - exWave.add(new Double(v[0])); + exWave.add(Double.parseDouble(v[0])); } else if (key.equals("Power")) { power.add(DataTools.parseDouble(value).intValue()); @@ -898,7 +898,7 @@ else if (key.equals("CameraUniqueName")) { cameraModel = value; } else if (key.equals("ExposureTime")) { - exposureTime.add(new Double(value) / 1000d); + exposureTime.add(Double.parseDouble(value) / 1000d); } else if (key.equals("sDate")) { date = DateTools.formatDate(value, DATE_FORMAT); diff --git a/components/formats-gpl/src/loci/formats/in/ND2Reader.java b/components/formats-gpl/src/loci/formats/in/ND2Reader.java index 01e7ce6ccdd..77b03b0cc64 100644 --- a/components/formats-gpl/src/loci/formats/in/ND2Reader.java +++ b/components/formats-gpl/src/loci/formats/in/ND2Reader.java @@ -713,7 +713,7 @@ else if (trueSizeY == 0) { lastImage = entry; - imageOffsets.add(new Long(entry.position + 16)); + imageOffsets.add(Long.valueOf(entry.position + 16)); int realLength = (int) Math.max(entry.name.length() + 1, nameLength); imageLengths.add(new long[] {realLength, entry.length - nameLength - 16, getSizeX() * getSizeY()}); imageNames.add(entry.name.substring(12)); @@ -2188,7 +2188,7 @@ private ArrayList iterateIn(RandomAccessInputStream in, Long stop, boole name = name.trim(); if (name.equals("bUseZ")) { - useZ = new Boolean(value.toString()); + useZ = Boolean.parseBoolean(value.toString()); } else if (name.equals("sDescription")) { if (currentColor != null) { @@ -2209,7 +2209,7 @@ else if (name.equals("EmWavelength")) { textEmissionWavelengths.add(wave); } else if (name.equals("dZStep")) { - trueSizeZ = new Double(value.toString()); + trueSizeZ = DataTools.parseDouble(value.toString()); } else if (name.equals("dZHigh")) { zHigh = DataTools.parseDouble(value.toString()); diff --git a/components/formats-gpl/src/loci/formats/in/NDPIReader.java b/components/formats-gpl/src/loci/formats/in/NDPIReader.java index 32fc44d20df..f1735dbf8e3 100644 --- a/components/formats-gpl/src/loci/formats/in/NDPIReader.java +++ b/components/formats-gpl/src/loci/formats/in/NDPIReader.java @@ -35,6 +35,8 @@ import loci.formats.FormatException; import loci.formats.FormatTools; import loci.formats.MetadataTools; +import loci.formats.codec.Codec; +import loci.formats.codec.CodecOptions; import loci.formats.meta.MetadataStore; import loci.formats.services.JPEGTurboService; import loci.formats.services.JPEGTurboServiceImpl; @@ -119,6 +121,92 @@ public NDPIReader() { canSeparateSeries = false; } + // -- ICompressedTileReader API methods -- + + @Override + public int getTileRows(int no) { + FormatTools.assertId(currentId, true, 1); + + int ifdIndex = getIFDIndex(getCoreIndex(), no); + //service.initialize(); + return service.getTileRows(); + } + + @Override + public int getTileColumns(int no) { + FormatTools.assertId(currentId, true, 1); + + int ifdIndex = getIFDIndex(getCoreIndex(), no); + //service.initialize(); + return service.getTileColumns(); + } + + @Override + public byte[] openCompressedBytes(int no, int x, int y) throws FormatException, IOException { + FormatTools.assertId(currentId, true, 1); + + int ifdIndex = getIFDIndex(getCoreIndex(), no); + IFD ifd = ifds.get(ifdIndex); + + if (useTiffParser(ifd)) { + byte[] buf = new byte[(int) getCompressedByteCount(ifd, x, y)]; + return openCompressedBytes(no, buf, x, y); + } + + if (initializedSeries != getCoreIndex() || initializedPlane != no) { + resetStream(ifd); + initializedSeries = getCoreIndex(); + initializedPlane = no; + } + return service.getCompressedTile(x, y); + } + + @Override + public byte[] openCompressedBytes(int no, byte[] buf, int x, int y) throws FormatException, IOException { + FormatTools.assertId(currentId, true, 1); + + int ifdIndex = getIFDIndex(getCoreIndex(), no); + IFD ifd = ifds.get(ifdIndex); + + if (useTiffParser(ifd)) { + try (RandomAccessInputStream s = new RandomAccessInputStream(currentId)) { + tiffParser = new TiffParser(s); + tiffParser.setUse64BitOffsets(true); + return copyTile(ifd, buf, x, y); + } + finally { + tiffParser.getStream().close(); + } + } + + if (initializedSeries != getCoreIndex() || initializedPlane != no) { + resetStream(ifd); + initializedSeries = getCoreIndex(); + initializedPlane = no; + } + service.getCompressedTile(buf, x, y); + return buf; + } + + @Override + public Codec getTileCodec(int no) throws FormatException, IOException { + FormatTools.assertId(currentId, true, 1); + int ifdIndex = getIFDIndex(getCoreIndex(), no); + IFD ifd = ifds.get(ifdIndex); + return ifd.getCompression().getCodec(); + } + + @Override + public CodecOptions getTileCodecOptions(int no, int x, int y) throws FormatException, IOException { + FormatTools.assertId(currentId, true, 1); + int ifdIndex = getIFDIndex(getCoreIndex(), no); + IFD ifd = ifds.get(ifdIndex); + CodecOptions options = ifd.getCompression().getCompressionCodecOptions(ifd); + options.width = getOptimalTileWidth(); + options.height = getOptimalTileHeight(); + return options; + } + // -- IFormatReader API methods -- /* (non-Javadoc) @@ -185,56 +273,7 @@ else if (useTiffParser(ifds.get(ifdIndex))) { if (initializedSeries != getCoreIndex() || initializedPlane != no) { IFD ifd = ifds.get(ifdIndex); - - long offset = ifd.getStripOffsets()[0]; - long byteCount = ifd.getStripByteCounts()[0]; - if (in != null) { - in.close(); - } - in = new RandomAccessInputStream(currentId); - in.seek(offset); - in.setLength(offset + byteCount); - - try { - service.close(); - long[] markers = ifd.getIFDLongArray(MARKER_TAG); - long[] markerHighBytes = ifd.getIFDLongArray(MARKER_TAG_HIGH_BYTES); - if (!use64Bit) { - for (int i=0; i cztToPixelBlocks = new HashMap<>(); private String baseName; private int lastChannel = -1; + private int optimalTileHeight; private int minZ = Integer.MAX_VALUE; private int minT = Integer.MAX_VALUE; @@ -169,6 +172,17 @@ public short[][] get16BitLookupTable() throws FormatException, IOException { return (short[][]) channels.get(lastChannel).lut; } + @Override + public int getOptimalTileHeight() { + FormatTools.assertId(currentId, true, 1); + return Math.min(2048, optimalTileHeight); + } + + @Override + public int getOptimalTileWidth() { + FormatTools.assertId(currentId, true, 1); + return Math.min(2048, getSizeX()); + } /** * @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int) @@ -182,77 +196,58 @@ public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) int[] zct = getZCTCoords(no); lastChannel = zct[1]; - int first = 0; - int startIndex = -1; - int end = 0; - while (first < pixelUIDs.length) { - if (getZ(pixelUIDs[first]) - minZ == zct[0] && - getT(pixelUIDs[first]) - minT == zct[2] && - pixelUIDs[first].indexOf(channels.get(zct[1] % channels.size()).id) > 0) - { - if (startIndex < 0) { - startIndex = first; - } - end = first; - } - first++; - } + // Gets all the PixelBlock potentially contained within c, z and t + PixelBlock[] blocks = cztToPixelBlocks.get(new CZTKey(zct[1], zct[0], zct[2])); - if (startIndex < 0) { + if ((blocks == null) || (blocks.length == 0)) { LOGGER.warn("No pixel blocks for plane #{}", no); Arrays.fill(buf, getFillColor()); return buf; } int bpp = FormatTools.getBytesPerPixel(getPixelType()); - int bufferOffset = bpp * ((y * getSizeX()) + x); - int rowLen = bpp * w; - int imageWidth = bpp * getSizeX(); - int bufferEnd = bpp * (((y + h) * getSizeX()) + x + w); - int bufferPointer = 0; - - RandomAccessInputStream s = null; - String openFile = null; - try { - for (int i=startIndex; i<=end; i++) { - PixelBlock block = pixelBlocks.get(pixelUIDs[i]); + int nBytesPerLineInBuf = w * bpp; // number of bytes for one line within the exported buffer + int nBytesPerLineInBlock = getSizeX() * bpp; // number of bytes for one line within a PixelBlock - if (bufferPointer + block.length < bufferOffset || - bufferPointer >= bufferEnd) - { - bufferPointer += block.length; - continue; - } - - byte[] pixels = null; - if (s == null || !block.file.equals(openFile)) { - if (s != null) { - s.close(); - } - s = new RandomAccessInputStream(block.file, BUFFER_SIZE); - openFile = block.file; - } - pixels = readPixelBlock(s, block.offset); - if (pixels != null) { - int blockY = bufferPointer / imageWidth; - int blockH = pixels.length / imageWidth; + // Iterators: y position + int yOffsetInBuffer = 0; // current y offset within the exported buffer - for (int yy=blockY; yy= y + h) { - continue; - } - int blockOffset = (yy - blockY) * imageWidth + x * bpp; - int bufOffset = (yy - y) * rowLen; - System.arraycopy(pixels, blockOffset, buf, bufOffset, rowLen); - } - } - bufferPointer += block.length; - } - } - finally { - if (s != null) { - s.close(); + for (PixelBlock block : blocks) { // This list is sorted along y + if (block == null) { + LOGGER.warn("Block not found."); + continue; } + // Skips blocks positioned fully outside [y, y+h[ + if (block.yEndy+h) break; // The pixel block is completely below the requested region - skip all remaining blocks + + // At this point of the code we know for sure that this PixelBlock overlaps with the requested region, + // We need to copy lines from this PixelBlock to the buffer, cropping properly the PixelBlock + // and taking into account the x and y offset + + // Skips the first lines of the block if necessary - the result will be non-zero only for the first PixelBlock + // that lies within the buffer region + skips the bytes according to the x offset + int blockOffset = + ((y+yOffsetInBuffer)-block.yStart)*nBytesPerLineInBlock // y Offset + + (x * bpp); // x offset + + // Number of lines to be copied within the PixelBlock + // The stop condition happens either: + // - if we reach the end of the bytes to be read within the requested region + // - or if we reach the end of the current PixelBlock + int nLines = Math.min(h-yOffsetInBuffer, block.yEnd-(y+yOffsetInBuffer)); + + // Perform the copy + copyPixelBlock(block, buf, + yOffsetInBuffer * nBytesPerLineInBuf, // Current position within the exported buffer + blockOffset, // Current position within the PixelBlock, taking into account the x offset + nBytesPerLineInBuf, // number of bytes within a line of the exported buffer + nBytesPerLineInBlock, // number of bytes within a line of a PixelBlock + nLines + ); + + // Updates new position within the exported buffer + yOffsetInBuffer+=nLines; // nLines filled } return buf; @@ -274,7 +269,8 @@ public void close(boolean fileOnly) throws IOException { acquisitionDate = null; defaultXMLSkip = 36; blocksPerPlane = 0; - pixelUIDs = null; + cztToPixelBlocks.clear(); + optimalTileHeight = 0; baseName = null; lastChannel = -1; minZ = Integer.MAX_VALUE; @@ -412,51 +408,53 @@ else if (!checkSuffix(id, "oir")) { } } - pixelUIDs = pixelBlocks.keySet().toArray(new String[pixelBlocks.size()]); - Arrays.sort(pixelUIDs, new Comparator() { - @Override - public int compare(String s1, String s2) { - int lastUnderscore1 = s1.lastIndexOf("_"); - int lastUnderscore2 = s2.lastIndexOf("_"); - - Integer block1 = new Integer(s1.substring(lastUnderscore1 + 1)); - Integer block2 = new Integer(s2.substring(lastUnderscore2 + 1)); + int maxNumberOfBlocks = -1; - int underscore1 = s1.lastIndexOf("_", lastUnderscore1 - 1); - int underscore2 = s2.lastIndexOf("_", lastUnderscore2 - 1); - - String prefix1 = s1.substring(0, underscore1); - String prefix2 = s2.substring(0, underscore2); + // Get max number of blocks + for (String uid: pixelBlocks.keySet()) { + int b = getBlock(uid); + if (b>=maxNumberOfBlocks) maxNumberOfBlocks = b+1; + } - String channel1 = s1.substring(underscore1 + 1, lastUnderscore1); - String channel2 = s2.substring(underscore2 + 1, lastUnderscore2); + for (String uid: pixelBlocks.keySet()) { + int z = getZ(uid)-minZ; + int t = getT(uid)-minT; + int c = getC(uid) + getL(uid); // Channel index or lambda index (We suppose there's no multichannel + lambda); + int b = getBlock(uid); - if (!prefix1.equals(prefix2)) { - return s1.compareTo(s2); - } + CZTKey key = new CZTKey(c,z,t); + if (!cztToPixelBlocks.containsKey(key)) cztToPixelBlocks.put(key, new PixelBlock[maxNumberOfBlocks]); + PixelBlock pb = pixelBlocks.get(uid); + cztToPixelBlocks.get(key)[b] = pb; + } - if (!channel1.equals(channel2)) { - Integer index1 = -1; - Integer index2 = -2; - for (int i=0; i optimalTileHeight) { + optimalTileHeight = nLines; + } + yStart+=block.length/bytesPerLine; + block.yEnd = yStart; // start of the next block = end (excluded) of the previous block } - - return block1.compareTo(block2); } - }); + } - if (LOGGER.isTraceEnabled()) { - for (int i=0; i that probably shouldn't happen + if ((long)optimalTileHeight*(long)m.sizeX*(long)bpp > Integer.MAX_VALUE) { + optimalTileHeight = Integer.MAX_VALUE / (bpp * m.sizeX) - 1; } // populate original metadata @@ -1466,34 +1464,48 @@ else if (pixelBytes <= 0) { return true; } - private byte[] readPixelBlock(RandomAccessInputStream s, long offset) throws IOException { - s.order(true); - s.seek(offset); + private void copyPixelBlock(PixelBlock block, + byte[] buf, int offsetBuf, int offsetBlock, + int nBytesPerLinesBuf, int nBytesPerLineBlock, int nLines) throws IOException { - int checkLength = s.readInt(); - int check = s.readInt(); - if (check != 3) { + try (RandomAccessInputStream s = new RandomAccessInputStream(block.file, BUFFER_SIZE)) { + + long offset = block.offset; + s.order(true); s.seek(offset); - return null; - } - s.skipBytes(8); // currently unknown + int checkLength = s.readInt(); + int check = s.readInt(); + if (check != 3) { + s.seek(offset); + return; + } - int uidLength = s.readInt(); - String uid = s.readString(uidLength); - LOGGER.debug("reading pixel block with uid = {}", uid); - if (checkLength != uidLength + 12) { - s.seek(offset); - return null; - } + s.skipBytes(8); // currently unknown - int pixelBytes = s.readInt(); + int uidLength = s.readInt(); + String uid = s.readString(uidLength); + LOGGER.debug("reading pixel block with uid = {}", uid); + if (checkLength != uidLength + 12) { + s.seek(offset); + return; + } - s.skipBytes(4); // currently unknown + int pixelBytes = s.readInt(); + s.skipBytes(4); // currently unknown + s.skipBytes(offsetBlock); - byte[] pixels = new byte[pixelBytes]; - s.readFully(pixels); - return pixels; + if (nBytesPerLineBlock==nBytesPerLinesBuf) { + // Full line copy, no skip needed + s.read(buf, offsetBuf, nBytesPerLineBlock*nLines); + } else { + for (int i = 0; i < nLines; i++) { + s.read(buf, offsetBuf, nBytesPerLinesBuf); + s.skipBytes(nBytesPerLineBlock-nBytesPerLinesBuf); + offsetBuf += nBytesPerLinesBuf; + } + } + } } private int getZ(String uid) { @@ -1514,6 +1526,16 @@ private int getT(String uid) { return Integer.parseInt(tSubString.substring(0, tSubString.indexOf("_"))) - 1; } + private int getC(String uid) { + String toParse = uid.substring(0,uid.lastIndexOf("_")); + String channelSignature = toParse.substring(toParse.lastIndexOf("_")+1); + for (int iCh = 0; iCh + * It's used to create a Map from CZTKey to PixelBlocks + */ + private static class CZTKey { + public final int c,z,t; + public final int hashCode; + public CZTKey(int c, int z, int t) { + this.c = c; + this.z = z; + this.t = t; + hashCode = Objects.hash(c,z,t); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + CZTKey that = (CZTKey) o; + return (that.z == this.z)&&(that.c == this.c)&&(that.t == this.t); + } + @Override + public int hashCode() { + return hashCode; + } + + @Override + public String toString() { + return "C:"+c+"; Z:"+z+"; T:"+t; + } } } diff --git a/components/formats-gpl/src/loci/formats/in/OlympusTileReader.java b/components/formats-gpl/src/loci/formats/in/OlympusTileReader.java index 0a1152cf658..b4a5191a4a6 100644 --- a/components/formats-gpl/src/loci/formats/in/OlympusTileReader.java +++ b/components/formats-gpl/src/loci/formats/in/OlympusTileReader.java @@ -295,8 +295,8 @@ else if (checkSuffix(tileFile, "vsi")) { int diffY = stageOverlap * rows * 4; if (stitchedWidth != null && stitchedHeight != null) { - int actualWidth = (int) (stitchedWidth / physicalSizeX.value(UNITS.NM).doubleValue()); - int actualHeight = (int) (stitchedHeight / physicalSizeY.value(UNITS.NM).doubleValue()); + int actualWidth = (int) (stitchedWidth / physicalSizeX.value(UNITS.NANOMETER).doubleValue()); + int actualHeight = (int) (stitchedHeight / physicalSizeY.value(UNITS.NANOMETER).doubleValue()); diffX = widthWithOverlaps - actualWidth; diffY = heightWithOverlaps - actualHeight; diff --git a/components/formats-gpl/src/loci/formats/in/OpenlabReader.java b/components/formats-gpl/src/loci/formats/in/OpenlabReader.java index edfe7da01cf..d5484891333 100644 --- a/components/formats-gpl/src/loci/formats/in/OpenlabReader.java +++ b/components/formats-gpl/src/loci/formats/in/OpenlabReader.java @@ -30,6 +30,7 @@ import java.util.List; import loci.common.ByteArrayHandle; +import loci.common.DataTools; import loci.common.Location; import loci.common.RandomAccessInputStream; import loci.formats.ChannelSeparator; @@ -597,8 +598,8 @@ else if (tag == USER) { if (level != MetadataLevel.MINIMUM) { // populate MetadataStore - Length sizeX = FormatTools.getPhysicalSizeX(new Double(xcal)); - Length sizeY = FormatTools.getPhysicalSizeY(new Double(ycal)); + Length sizeX = FormatTools.getPhysicalSizeX(Double.valueOf(xcal)); + Length sizeY = FormatTools.getPhysicalSizeY(Double.valueOf(ycal)); if (sizeX != null) { store.setPixelsPhysicalSizeX(sizeX, 0); @@ -614,13 +615,13 @@ else if (tag == USER) { try { if (gain != null) { - store.setDetectorSettingsGain(new Double(gain), 0, 0); + store.setDetectorSettingsGain(DataTools.parseDouble(gain), 0, 0); } } catch (NumberFormatException e) { } try { if (detectorOffset != null) { - store.setDetectorSettingsOffset(new Double(detectorOffset), 0, 0); + store.setDetectorSettingsOffset(DataTools.parseDouble(detectorOffset), 0, 0); } } catch (NumberFormatException e) { } diff --git a/components/formats-gpl/src/loci/formats/in/OperettaReader.java b/components/formats-gpl/src/loci/formats/in/OperettaReader.java index 305eabe3ad6..15db568d5ab 100644 --- a/components/formats-gpl/src/loci/formats/in/OperettaReader.java +++ b/components/formats-gpl/src/loci/formats/in/OperettaReader.java @@ -1199,6 +1199,7 @@ else if (emWavelength < 610) { } @Override + @Deprecated protected AcquisitionMode getAcquisitionMode(String mode) throws FormatException { if (mode == null) { return null; diff --git a/components/formats-gpl/src/loci/formats/in/PCIReader.java b/components/formats-gpl/src/loci/formats/in/PCIReader.java index 6dae3ff5589..7ff38888ada 100644 --- a/components/formats-gpl/src/loci/formats/in/PCIReader.java +++ b/components/formats-gpl/src/loci/formats/in/PCIReader.java @@ -228,7 +228,7 @@ protected void initFile(String id) throws FormatException, IOException { for (String name : allFiles) { int separator = name.lastIndexOf(File.separator); String parent = name.substring(0, separator); - String relativePath = name.substring(separator + 1); + String relativePath = name.substring(separator + 1).trim(); RandomAccessInputStream stream = null; if (!(relativePath.startsWith("Bitmap") || @@ -296,7 +296,7 @@ else if (relativePath.indexOf("Image_Width") != -1 && getSizeX() == 0) { else if (relativePath.indexOf("Time_From_Start") != -1) { timestamps.put(getTimestampIndex(parent), stream.readDouble()); } - else if (relativePath.indexOf("Position_Z") != -1) { + else if (relativePath.endsWith("Position_Z")) { double zPos = stream.readDouble(); if (!uniqueZ.contains(zPos) && getSizeZ() <= 1) { diff --git a/components/formats-gpl/src/loci/formats/in/PCORAWReader.java b/components/formats-gpl/src/loci/formats/in/PCORAWReader.java index a4172d68529..19630ca92a6 100644 --- a/components/formats-gpl/src/loci/formats/in/PCORAWReader.java +++ b/components/formats-gpl/src/loci/formats/in/PCORAWReader.java @@ -208,7 +208,7 @@ protected void initFile(String id) throws FormatException, IOException { // set the exposure time String exp = value.substring(0, value.indexOf(' ')); - Double parsedExp = new Double(exp); + Double parsedExp = DataTools.parseDouble(exp); Time exposure = null; if (parsedExp != null) { exposure = new Time(parsedExp / 1000, UNITS.SECOND); diff --git a/components/formats-gpl/src/loci/formats/in/PDSReader.java b/components/formats-gpl/src/loci/formats/in/PDSReader.java index 8ebd371110c..8ad93d0d9e2 100644 --- a/components/formats-gpl/src/loci/formats/in/PDSReader.java +++ b/components/formats-gpl/src/loci/formats/in/PDSReader.java @@ -234,10 +234,10 @@ else if (key.equals("SIGNY")) { reverseY = value.replaceAll("'", "").trim().equals("-"); } else if (key.equals("DELTAX")) { - deltaX = new Double(value); + deltaX = DataTools.parseDouble(value); } else if (key.equals("DELTAY")) { - deltaY = new Double(value); + deltaY = DataTools.parseDouble(value); } else if (key.equals("COLOR")) { int color = Integer.parseInt(value); diff --git a/components/formats-gpl/src/loci/formats/in/PerkinElmerReader.java b/components/formats-gpl/src/loci/formats/in/PerkinElmerReader.java index d960c6c169a..35f2960bfd8 100644 --- a/components/formats-gpl/src/loci/formats/in/PerkinElmerReader.java +++ b/components/formats-gpl/src/loci/formats/in/PerkinElmerReader.java @@ -489,7 +489,7 @@ protected void initFile(String id) throws FormatException, IOException { if (exposure.endsWith(",")) { exposure = exposure.substring(0, exposure.length() - 1); } - exposureTimes.add(new Double(Double.parseDouble(exposure) / 1000)); + exposureTimes.add(Double.parseDouble(exposure) / 1000); if (tokens[j].indexOf("nm") != -1) { int nmIndex = tokens[j].indexOf("nm"); @@ -497,14 +497,14 @@ protected void initFile(String id) throws FormatException, IOException { int slash = tokens[j].lastIndexOf("/", nmIndex); if (slash == -1) slash = nmIndex; emWaves.add( - new Double(tokens[j].substring(paren + 1, slash).trim())); + DataTools.parseDouble(tokens[j].substring(paren + 1, slash).trim())); if (tokens[j].indexOf("nm", nmIndex + 3) != -1) { nmIndex = tokens[j].indexOf("nm", nmIndex + 3); paren = tokens[j].lastIndexOf(" ", nmIndex); slash = tokens[j].lastIndexOf("/", nmIndex); if (slash == -1) slash = nmIndex + 2; exWaves.add( - new Double(tokens[j].substring(paren + 1, slash).trim())); + DataTools.parseDouble(tokens[j].substring(paren + 1, slash).trim())); } } @@ -514,7 +514,7 @@ else if (tokens[j + 1].trim().equals("Slice Z positions")) { for (int q=j + 2; q 1; } } return false; @@ -306,21 +308,7 @@ public int getTileColumns(int no) { public byte[] openCompressedBytes(int no, int x, int y) throws FormatException, IOException { FormatTools.assertId(currentId, true, 1); IFD ifd = getIFD(no); - long[] byteCounts = ifd.getStripByteCounts(); - int tileIndex = getTileIndex(ifd, x, y); - - byte[] jpegTable = (byte[]) ifd.getIFDValue(IFD.JPEG_TABLES); - int jpegTableBytes = jpegTable == null ? 0 : jpegTable.length - 2; - long expectedBytes = byteCounts[tileIndex]; - if (expectedBytes > 0) { - expectedBytes += jpegTableBytes; - } - - if (expectedBytes < 0 || expectedBytes > Integer.MAX_VALUE) { - throw new IOException("Invalid compressed tile size: " + expectedBytes); - } - - byte[] buf = new byte[(int) expectedBytes]; + byte[] buf = new byte[(int) getCompressedByteCount(ifd, x, y)]; return openCompressedBytes(no, buf, x, y); } @@ -328,38 +316,7 @@ public byte[] openCompressedBytes(int no, int x, int y) throws FormatException, public byte[] openCompressedBytes(int no, byte[] buf, int x, int y) throws FormatException, IOException { FormatTools.assertId(currentId, true, 1); IFD ifd = getIFD(no); - long[] offsets = ifd.getStripOffsets(); - long[] byteCounts = ifd.getStripByteCounts(); - - int tileIndex = getTileIndex(ifd, x, y); - - byte[] jpegTable = (byte[]) ifd.getIFDValue(IFD.JPEG_TABLES); - int jpegTableBytes = jpegTable == null ? 0 : jpegTable.length - 2; - long expectedBytes = byteCounts[tileIndex]; - if (expectedBytes > 0) { - expectedBytes += jpegTableBytes; - } - - if (buf.length < expectedBytes) { - throw new IllegalArgumentException("Tile buffer too small: expected >=" + - expectedBytes + ", got " + buf.length); - } - else if (expectedBytes < 0 || expectedBytes > Integer.MAX_VALUE) { - throw new IOException("Invalid compressed tile size: " + expectedBytes); - } - - if (jpegTable != null && expectedBytes > 0) { - System.arraycopy(jpegTable, 0, buf, 0, jpegTable.length - 2); - // skip over the duplicate SOI marker - tiffParser.getStream().seek(offsets[tileIndex] + 2); - tiffParser.getStream().readFully(buf, jpegTable.length - 2, (int) byteCounts[tileIndex]); - } - else if (byteCounts[tileIndex] > 0) { - tiffParser.getStream().seek(offsets[tileIndex]); - tiffParser.getStream().readFully(buf, 0, (int) byteCounts[tileIndex]); - } - - return buf; + return copyTile(ifd, buf, x, y); } @Override @@ -437,7 +394,7 @@ else if (macroIndex == -1) { key = t.substring(0, t.indexOf('=')).trim(); value = t.substring(t.indexOf('=') + 1).trim(); if (key.equals("TotalDepth")) { - zPosition[index] = new Double(0); + zPosition[index] = 0d; } else if (key.equals("OffsetZ")) { zPosition[index] = DataTools.parseDouble(value); @@ -689,13 +646,13 @@ protected void initMetadataStore() throws FormatException { if (i == 0) { if (physicalDistanceFromTopEdge != null) { - Length yPos = FormatTools.getStagePosition(physicalDistanceFromTopEdge, UNITS.MM); + Length yPos = FormatTools.getStagePosition(physicalDistanceFromTopEdge, UNITS.MILLIMETER); for (int p=0; p= cols) { - throw new IllegalArgumentException("X index " + x + " not in range [0, " + cols + ")"); - } - if (y < 0 || y >= rows) { - throw new IllegalArgumentException("Y index " + y + " not in range [0, " + rows + ")"); - } - - return (cols * y) + x; - } - } diff --git a/components/formats-gpl/src/loci/formats/in/ScanrReader.java b/components/formats-gpl/src/loci/formats/in/ScanrReader.java index 99cde8c5c40..64318040bc0 100644 --- a/components/formats-gpl/src/loci/formats/in/ScanrReader.java +++ b/components/formats-gpl/src/loci/formats/in/ScanrReader.java @@ -470,8 +470,8 @@ public int compare(String s1, String s2) { char row1 = s1.charAt(0); char row2 = s2.charAt(0); - final Integer col1 = new Integer(s1.substring(1)); - final Integer col2 = new Integer(s2.substring(1)); + final Integer col1 = Integer.parseInt(s1.substring(1)); + final Integer col2 = Integer.parseInt(s2.substring(1)); if (row1 < row2) { return -1; @@ -830,7 +830,7 @@ else if (key.equals("plate name")) { plateName = v; } else if (key.equals("exposure time")) { - exposures.add(new Double(v)); + exposures.add(DataTools.parseDouble(v)); } else if (key.equals("idle") && validChannel) { int lastIndex = channelNames.size() - 1; @@ -847,15 +847,15 @@ else if (key.equals("idle") && validChannel) { else if (key.equals("well selection table + cDNA")) { if (Character.isDigit(v.charAt(0))) { wellIndex = v; - wellNumbers.put(wellCount, new Integer(v)); + wellNumbers.put(wellCount, Integer.parseInt(v)); wellCount++; } else { - wellLabels.put(v, new Integer(wellIndex)); + wellLabels.put(v, Integer.parseInt(wellIndex)); } } else if (key.equals("conversion factor um/pixel")) { - pixelSize = new Double(v); + pixelSize = DataTools.parseDouble(v); } else if (foundPositions) { if (nextXPos == nextYPos) { diff --git a/components/formats-gpl/src/loci/formats/in/SimplePCITiffReader.java b/components/formats-gpl/src/loci/formats/in/SimplePCITiffReader.java index e4f451a0444..899a3043e0b 100644 --- a/components/formats-gpl/src/loci/formats/in/SimplePCITiffReader.java +++ b/components/formats-gpl/src/loci/formats/in/SimplePCITiffReader.java @@ -31,6 +31,7 @@ import java.util.ArrayList; import java.util.HashMap; +import loci.common.DataTools; import loci.common.DateTools; import loci.common.IniList; import loci.common.IniParser; @@ -163,7 +164,7 @@ protected void initStandardMetadata() throws FormatException, IOException { String objective = microscopeTable.get("Objective"); int space = objective.indexOf(' '); if (space != -1) { - magnification = new Double(objective.substring(0, space - 1)); + magnification = DataTools.parseDouble(objective.substring(0, space - 1)); immersion = objective.substring(space + 1); } } @@ -192,7 +193,7 @@ protected void initStandardMetadata() throws FormatException, IOException { int index = 1; for (int i=0; i 0) { store.setPixelsPhysicalSizeX(FormatTools.getPhysicalSizeX(size), 0); store.setPixelsPhysicalSizeY(FormatTools.getPhysicalSizeY(size), 0); @@ -252,7 +253,7 @@ protected void initMetadataStore() throws FormatException { store.setObjectiveID(MetadataTools.createLSID("Objective", 0, 0), 0, 0); store.setObjectiveCorrection(MetadataTools.getCorrection("Other"), 0, 0); store.setObjectiveImmersion(MetadataTools.getImmersion("Other"), 0, 0); - store.setObjectiveNominalMagnification(new Double(mag), 0, 0); + store.setObjectiveNominalMagnification(DataTools.parseDouble(mag), 0, 0); } final Double xn = Double.valueOf(ifd.getIFDTextValue(X_POS_TAG)); diff --git a/components/formats-gpl/src/loci/formats/in/SpiderReader.java b/components/formats-gpl/src/loci/formats/in/SpiderReader.java index 1db9ed62015..f3e2d98e097 100644 --- a/components/formats-gpl/src/loci/formats/in/SpiderReader.java +++ b/components/formats-gpl/src/loci/formats/in/SpiderReader.java @@ -274,7 +274,7 @@ protected void initFile(String id) throws FormatException, IOException { } if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { - Double size = new Double(pixelSize); + Double size = Double.valueOf(pixelSize); Length sizeX = FormatTools.getPhysicalSizeX(size, UNITS.ANGSTROM); Length sizeY = FormatTools.getPhysicalSizeY(size, UNITS.ANGSTROM); if (sizeX != null) { diff --git a/components/formats-gpl/src/loci/formats/in/TCSReader.java b/components/formats-gpl/src/loci/formats/in/TCSReader.java index 951a5fe05d2..e05296595f5 100644 --- a/components/formats-gpl/src/loci/formats/in/TCSReader.java +++ b/components/formats-gpl/src/loci/formats/in/TCSReader.java @@ -568,7 +568,7 @@ private void groupFiles() throws FormatException, IOException { String software = ifd.getIFDStringValue(IFD.SOFTWARE); if (software != null && software.trim().startsWith("TCS")) { - timestamps.put(file, new Long(stamp)); + timestamps.put(file, Long.valueOf(stamp)); } } } diff --git a/components/formats-gpl/src/loci/formats/in/ZeissCZIReader.java b/components/formats-gpl/src/loci/formats/in/ZeissCZIReader.java index c05d47da625..db5d505a895 100644 --- a/components/formats-gpl/src/loci/formats/in/ZeissCZIReader.java +++ b/components/formats-gpl/src/loci/formats/in/ZeissCZIReader.java @@ -1424,7 +1424,7 @@ else if (extraIndex >= 0 && extraIndex < extraImages.size()) { if (airPressure != null) { store.setImagingEnvironmentAirPressure( - new Pressure(new Double(airPressure), UNITS.MILLIBAR), i); + new Pressure(Double.parseDouble(airPressure), UNITS.MILLIBAR), i); } if (co2Percent != null) { store.setImagingEnvironmentCO2Percent( @@ -1436,21 +1436,21 @@ else if (extraIndex >= 0 && extraIndex < extraImages.size()) { } if (temperature != null) { store.setImagingEnvironmentTemperature(new Temperature( - new Double(temperature), UNITS.CELSIUS), i); + Double.parseDouble(temperature), UNITS.CELSIUS), i); } if (objectiveSettingsID != null) { store.setObjectiveSettingsID(objectiveSettingsID, i); if (correctionCollar != null) { store.setObjectiveSettingsCorrectionCollar( - new Double(correctionCollar), i); + Double.parseDouble(correctionCollar), i); } if (medium != null) { store.setObjectiveSettingsMedium(MetadataTools.getMedium(medium), i); } if (refractiveIndex != null) { store.setObjectiveSettingsRefractiveIndex( - new Double(refractiveIndex), i); + Double.parseDouble(refractiveIndex), i); } } @@ -1687,7 +1687,7 @@ else if (getZCTCoords(plane)[2] < timestamps.size()) { String emWave = channels.get(c).emission; if (emWave != null) { - Double wave = new Double(emWave); + Double wave = Double.parseDouble(emWave); Length em = FormatTools.getEmissionWavelength(wave); if (em != null) { store.setChannelEmissionWavelength(em, i, c); @@ -1695,7 +1695,7 @@ else if (getZCTCoords(plane)[2] < timestamps.size()) { } String exWave = channels.get(c).excitation; if (exWave != null) { - Double wave = new Double(exWave); + Double wave = Double.parseDouble(exWave); Length ex = FormatTools.getExcitationWavelength(wave); if (ex != null) { store.setChannelExcitationWavelength(ex, i, c); @@ -1709,7 +1709,7 @@ else if (getZCTCoords(plane)[2] < timestamps.size()) { if (channels.get(c).pinhole != null) { store.setChannelPinholeSize( - new Length(new Double(channels.get(c).pinhole), UNITS.MICROMETER), i, c); + new Length(Double.parseDouble(channels.get(c).pinhole), UNITS.MICROMETER), i, c); } if (channels.get(c).acquisitionMode != null) { @@ -2509,7 +2509,7 @@ private void translateInformation(Element root) throws FormatException { String power = getFirstNodeValue(lightSource, "Power"); if ("Laser".equals(type)) { if (power != null) { - store.setLaserPower(new Power(new Double(power), UNITS.MILLIWATT), 0, i); + store.setLaserPower(new Power(Double.parseDouble(power), UNITS.MILLIWATT), 0, i); } store.setLaserLotNumber(lotNumber, 0, i); store.setLaserManufacturer(manufacturer, 0, i); @@ -2518,7 +2518,7 @@ private void translateInformation(Element root) throws FormatException { } else if ("Arc".equals(type)) { if (power != null) { - store.setArcPower(new Power(new Double(power), UNITS.MILLIWATT), 0, i); + store.setArcPower(new Power(Double.parseDouble(power), UNITS.MILLIWATT), 0, i); } store.setArcLotNumber(lotNumber, 0, i); store.setArcManufacturer(manufacturer, 0, i); @@ -2527,7 +2527,7 @@ else if ("Arc".equals(type)) { } else if ("LightEmittingDiode".equals(type)) { if (power != null) { - store.setLightEmittingDiodePower(new Power(new Double(power), UNITS.MILLIWATT), 0, i); + store.setLightEmittingDiodePower(new Power(Double.parseDouble(power), UNITS.MILLIWATT), 0, i); } store.setLightEmittingDiodeLotNumber(lotNumber, 0, i); store.setLightEmittingDiodeManufacturer(manufacturer, 0, i); @@ -2536,7 +2536,7 @@ else if ("LightEmittingDiode".equals(type)) { } else if ("Filament".equals(type)) { if (power != null) { - store.setFilamentPower(new Power(new Double(power), UNITS.MILLIWATT), 0, i); + store.setFilamentPower(new Power(Double.parseDouble(power), UNITS.MILLIWATT), 0, i); } store.setFilamentLotNumber(lotNumber, 0, i); store.setFilamentManufacturer(manufacturer, 0, i); @@ -2594,7 +2594,7 @@ else if ("Filament".equals(type)) { String offset = getFirstNodeValue(detector, "Offset"); if (offset != null && !offset.equals("")) { - store.setDetectorOffset(new Double(offset), 0, detectorIndex); + store.setDetectorOffset(Double.parseDouble(offset), 0, detectorIndex); } zoom = getFirstNodeValue(detector, "Zoom"); @@ -2609,7 +2609,7 @@ else if ("Filament".equals(type)) { String ampGain = getFirstNodeValue(detector, "AmplificationGain"); if (ampGain != null && !ampGain.equals("")) { - store.setDetectorAmplificationGain(new Double(ampGain), 0, detectorIndex); + store.setDetectorAmplificationGain(Double.parseDouble(ampGain), 0, detectorIndex); } String detectorType = getFirstNodeValue(detector, "Type"); @@ -2725,8 +2725,8 @@ else if ("Filament".equals(type)) { String cutIn = getFirstNodeValue(transmittance, "CutIn"); String cutOut = getFirstNodeValue(transmittance, "CutOut"); - Double inWave = cutIn == null ? 0 : new Double(cutIn); - Double outWave = cutOut == null ? 0 : new Double(cutOut); + Double inWave = cutIn == null ? 0 : Double.parseDouble(cutIn); + Double outWave = cutOut == null ? 0 : Double.parseDouble(cutOut); Length in = FormatTools.getCutIn(inWave); Length out = FormatTools.getCutOut(outWave); @@ -2743,13 +2743,13 @@ else if ("Filament".equals(type)) { getFirstNodeValue(transmittance, "CutOutTolerance"); if (inTolerance != null) { - Double cutInTolerance = new Double(inTolerance); + Double cutInTolerance = Double.parseDouble(inTolerance); store.setTransmittanceRangeCutInTolerance( new Length(cutInTolerance, UNITS.NANOMETER), 0, i); } if (outTolerance != null) { - Double cutOutTolerance = new Double(outTolerance); + Double cutOutTolerance = Double.parseDouble(outTolerance); store.setTransmittanceRangeCutOutTolerance( new Length(cutOutTolerance, UNITS.NANOMETER), 0, i); } @@ -2813,7 +2813,7 @@ private void translateScaling(Element root) { if (originalValue == null) { continue; } - Double value = new Double(originalValue) * 1000000; + Double value = Double.parseDouble(originalValue) * 1000000; if (value > 0) { PositiveFloat size = new PositiveFloat(value); @@ -2940,20 +2940,20 @@ private void translateLayers(Element root) { String centerY = getFirstNodeValue(geometry, "CenterY"); if (length != null) { - Double halfLen = new Double(length) / 2; + Double halfLen = Double.parseDouble(length) / 2; if (centerX != null) { - store.setLineX1(new Double(centerX) - halfLen, roiCount, shape); - store.setLineX2(new Double(centerX) + halfLen, roiCount, shape); + store.setLineX1(Double.parseDouble(centerX) - halfLen, roiCount, shape); + store.setLineX2(Double.parseDouble(centerX) + halfLen, roiCount, shape); - store.setLineX1(new Double(centerX), roiCount, shape + 1); - store.setLineX2(new Double(centerX), roiCount, shape + 1); + store.setLineX1(Double.parseDouble(centerX), roiCount, shape + 1); + store.setLineX2(Double.parseDouble(centerX), roiCount, shape + 1); } if (centerY != null) { - store.setLineY1(new Double(centerY), roiCount, shape); - store.setLineY2(new Double(centerY), roiCount, shape); + store.setLineY1(Double.parseDouble(centerY), roiCount, shape); + store.setLineY2(Double.parseDouble(centerY), roiCount, shape); - store.setLineY1(new Double(centerY) - halfLen, roiCount, shape + 1); - store.setLineY2(new Double(centerY) + halfLen, roiCount, shape + 1); + store.setLineY1(Double.parseDouble(centerY) - halfLen, roiCount, shape + 1); + store.setLineY2(Double.parseDouble(centerY) + halfLen, roiCount, shape + 1); } } store.setLineText(getFirstNodeValue(textElements, "Text"), roiCount, shape); @@ -2983,16 +2983,16 @@ private void translateLayers(Element root) { String centerY = getFirstNodeValue(geometry, "CenterY"); if (radiusX != null) { - store.setEllipseRadiusX(new Double(radiusX), roiCount, shape); + store.setEllipseRadiusX(Double.parseDouble(radiusX), roiCount, shape); } if (radiusY != null) { - store.setEllipseRadiusY(new Double(radiusY), roiCount, shape); + store.setEllipseRadiusY(Double.parseDouble(radiusY), roiCount, shape); } if (centerX != null) { - store.setEllipseX(new Double(centerX), roiCount, shape); + store.setEllipseX(Double.parseDouble(centerX), roiCount, shape); } if (centerY != null) { - store.setEllipseY(new Double(centerY), roiCount, shape); + store.setEllipseY(Double.parseDouble(centerY), roiCount, shape); } store.setEllipseText( getFirstNodeValue(textElements, "Text"), roiCount, shape); @@ -3165,7 +3165,7 @@ private void translateHardwareSettings(Element root) throws FormatException { if (magnification != null) { try { store.setObjectiveNominalMagnification( - new Double(magnification), 0, i); + Double.parseDouble(magnification), 0, i); } catch (NumberFormatException e) { LOGGER.debug("Could not parse magnification", e); @@ -3173,7 +3173,7 @@ private void translateHardwareSettings(Element root) throws FormatException { } if (na != null) { try { - store.setObjectiveLensNA(new Double(na), 0, i); + store.setObjectiveLensNA(Double.parseDouble(na), 0, i); } catch (NumberFormatException e) { LOGGER.debug("Could not parse numerical aperture", e); @@ -3181,7 +3181,7 @@ private void translateHardwareSettings(Element root) throws FormatException { } if (wd != null) { try { - store.setObjectiveWorkingDistance(new Length(new Double(wd), UNITS.MICROMETER), 0, i); + store.setObjectiveWorkingDistance(new Length(Double.parseDouble(wd), UNITS.MICROMETER), 0, i); } catch (NumberFormatException e) { LOGGER.debug("Could not parse working distance", e); @@ -3209,10 +3209,10 @@ private int populateRectangles(NodeList rectangles, int roi, int shape) { if (left != null && top != null && width != null && height != null) { store.setRectangleID( MetadataTools.createLSID("Shape", roi, shape), roi, shape); - store.setRectangleX(new Double(left), roi, shape); - store.setRectangleY(new Double(top), roi, shape); - store.setRectangleWidth(new Double(width), roi, shape); - store.setRectangleHeight(new Double(height), roi, shape); + store.setRectangleX(Double.parseDouble(left), roi, shape); + store.setRectangleY(Double.parseDouble(top), roi, shape); + store.setRectangleWidth(Double.parseDouble(width), roi, shape); + store.setRectangleHeight(Double.parseDouble(height), roi, shape); String name = getFirstNodeValue(attributes, "Name"); String label = getFirstNodeValue(textElements, "Text"); @@ -3272,16 +3272,16 @@ private int populateLines(NodeList lines, int roi, int shape) { MetadataTools.createLSID("Shape", roi, shape), roi, shape); if (x1 != null) { - store.setLineX1(new Double(x1), roi, shape); + store.setLineX1(Double.parseDouble(x1), roi, shape); } if (x2 != null) { - store.setLineX2(new Double(x2), roi, shape); + store.setLineX2(Double.parseDouble(x2), roi, shape); } if (y1 != null) { - store.setLineY1(new Double(y1), roi, shape); + store.setLineY1(Double.parseDouble(y1), roi, shape); } if (y2 != null) { - store.setLineY2(new Double(y2), roi, shape); + store.setLineY2(Double.parseDouble(y2), roi, shape); } store.setLineText(getFirstNodeValue(textElements, "Text"), roi, shape); } @@ -3302,14 +3302,14 @@ private int populateCircles(NodeList circles, int roi, int shape) { String centerY = getFirstNodeValue(geometry, "CenterY"); if (radius != null) { - store.setEllipseRadiusX(new Double(radius), roi, shape); - store.setEllipseRadiusY(new Double(radius), roi, shape); + store.setEllipseRadiusX(Double.parseDouble(radius), roi, shape); + store.setEllipseRadiusY(Double.parseDouble(radius), roi, shape); } if (centerX != null) { - store.setEllipseX(new Double(centerX), roi, shape); + store.setEllipseX(Double.parseDouble(centerX), roi, shape); } if (centerY != null) { - store.setEllipseY(new Double(centerY), roi, shape); + store.setEllipseY(Double.parseDouble(centerY), roi, shape); } store.setEllipseText(getFirstNodeValue(textElements, "Text"), roi, shape); } @@ -3535,7 +3535,7 @@ private void translateExperiment(Element root) throws FormatException { try { if (exposure != null) { - channels.get(i).exposure = new Double(exposure); + channels.get(i).exposure = Double.parseDouble(exposure); } } catch (NumberFormatException e) { @@ -3543,7 +3543,7 @@ private void translateExperiment(Element root) throws FormatException { } try { if (gain != null) { - channels.get(i).gain = new Double(gain); + channels.get(i).gain = Double.parseDouble(gain); } } catch (NumberFormatException e) { @@ -3825,7 +3825,7 @@ private void parseObjectives(NodeList objectives) throws FormatException { String lensNA = getFirstNodeValue(objective, "LensNA"); if (lensNA != null) { - store.setObjectiveLensNA(new Double(lensNA), 0, i); + store.setObjectiveLensNA(Double.parseDouble(lensNA), 0, i); } String magnification = @@ -3833,7 +3833,7 @@ private void parseObjectives(NodeList objectives) throws FormatException { if (magnification == null) { magnification = getFirstNodeValue(objective, "Magnification"); } - Double mag = magnification == null ? null : new Double(magnification); + Double mag = magnification == null ? null : Double.parseDouble(magnification); if (mag != null) { store.setObjectiveNominalMagnification(mag, 0, i); @@ -3842,15 +3842,15 @@ private void parseObjectives(NodeList objectives) throws FormatException { getFirstNodeValue(objective, "CalibratedMagnification"); if (calibratedMag != null) { store.setObjectiveCalibratedMagnification( - new Double(calibratedMag), 0, i); + Double.parseDouble(calibratedMag), 0, i); } String wd = getFirstNodeValue(objective, "WorkingDistance"); if (wd != null) { - store.setObjectiveWorkingDistance(new Length(new Double(wd), UNITS.MICROMETER), 0, i); + store.setObjectiveWorkingDistance(new Length(Double.parseDouble(wd), UNITS.MICROMETER), 0, i); } String iris = getFirstNodeValue(objective, "Iris"); if (iris != null) { - store.setObjectiveIris(new Boolean(iris), 0, i); + store.setObjectiveIris(Boolean.parseBoolean(iris), 0, i); } } } @@ -4286,7 +4286,7 @@ else if (tagNode.getNodeName().equals("AcquisitionTime")) { timestamp = t.asInstant().getMillis() / 1000d; } else if (tagNode.getNodeName().equals("ExposureTime")) { - exposureTime = new Double(text); + exposureTime = Double.parseDouble(text); } } } diff --git a/components/formats-gpl/src/loci/formats/in/ZeissLSMReader.java b/components/formats-gpl/src/loci/formats/in/ZeissLSMReader.java index ed22ac83ba9..b33d2a042b4 100644 --- a/components/formats-gpl/src/loci/formats/in/ZeissLSMReader.java +++ b/components/formats-gpl/src/loci/formats/in/ZeissLSMReader.java @@ -1134,7 +1134,7 @@ else if (zCoordinates.size() == i) { // if this is not the first channel, copy the color from the // previous channel (necessary for SIM data) // otherwise set the color to white, as this will display better - if (red == 0 && green == 0 & blue == 0) { + if (red == 0 && green == 0 && blue == 0) { if (i > 0 && isSIM) { red = channelColor[i - 1].getRed(); green = channelColor[i - 1].getGreen(); @@ -1486,7 +1486,7 @@ nextDetectChannel < getSizeC() && channel.acquire) String transmittance = channel.filter.substring(space + 1).trim(); String[] v = transmittance.split("-"); try { - final Double cutIn = new Double(v[0].trim()); + final Double cutIn = DataTools.parseDouble(v[0].trim()); Length in = FormatTools.getCutIn(cutIn); if (in != null) { store.setTransmittanceRangeCutIn(in, instrument, nextFilter); @@ -1495,7 +1495,7 @@ nextDetectChannel < getSizeC() && channel.acquire) catch (NumberFormatException e) { } if (v.length > 1) { try { - final Double cutOut = new Double(v[1].trim()); + final Double cutOut = DataTools.parseDouble(v[1].trim()); Length out = FormatTools.getCutOut(cutOut); if (out != null) { store.setTransmittanceRangeCutOut(out, instrument, nextFilter); @@ -2410,13 +2410,13 @@ protected void read() throws IOException { int slash = p.indexOf('/'); if (slash > 0) { try { - magnification = new Double(p.substring(0, slash - 1)); + magnification = DataTools.parseDouble(p.substring(0, slash - 1)); } catch (NumberFormatException e) { } } if (slash >= 0 && slash < p.length() - 1) { try { - lensNA = new Double(p.substring(slash + 1)); + lensNA = DataTools.parseDouble(p.substring(slash + 1)); } catch (NumberFormatException e) { } } @@ -2519,7 +2519,7 @@ protected void read() throws IOException { name = getStringValue(ILLUM_CHANNEL_NAME); try { - wavelength = new Double(name); + wavelength = DataTools.parseDouble(name); } catch (NumberFormatException e) { } } diff --git a/components/test-suite/pom.xml b/components/test-suite/pom.xml index 2ad76017821..74c5dcd3dec 100644 --- a/components/test-suite/pom.xml +++ b/components/test-suite/pom.xml @@ -8,7 +8,7 @@ ome pom-bio-formats - 8.0.0-SNAPSHOT + 8.1.0-SNAPSHOT ../.. diff --git a/components/test-suite/src/loci/tests/testng/Configuration.java b/components/test-suite/src/loci/tests/testng/Configuration.java index 6a4b26d35a4..a4d65ba6523 100644 --- a/components/test-suite/src/loci/tests/testng/Configuration.java +++ b/components/test-suite/src/loci/tests/testng/Configuration.java @@ -202,12 +202,12 @@ public boolean doTest() { if (delim >= 0) { test = test.substring(0, delim); } - return new Boolean(test.trim()).booleanValue(); + return Boolean.parseBoolean(test.trim()); } public boolean hasValidXML() { if (globalTable.get(HAS_VALID_XML) == null) return true; - return new Boolean(globalTable.get(HAS_VALID_XML)).booleanValue(); + return Boolean.parseBoolean(globalTable.get(HAS_VALID_XML)); } public String getReader() { @@ -261,19 +261,19 @@ public String getDimensionOrder() { } public boolean isInterleaved() { - return new Boolean(currentTable.get(IS_INTERLEAVED)).booleanValue(); + return Boolean.parseBoolean(currentTable.get(IS_INTERLEAVED)); } public boolean isIndexed() { - return new Boolean(currentTable.get(IS_INDEXED)).booleanValue(); + return Boolean.parseBoolean(currentTable.get(IS_INDEXED)); } public boolean isFalseColor() { - return new Boolean(currentTable.get(IS_FALSE_COLOR)).booleanValue(); + return Boolean.parseBoolean(currentTable.get(IS_FALSE_COLOR)); } public boolean isRGB() { - return new Boolean(currentTable.get(IS_RGB)).booleanValue(); + return Boolean.parseBoolean(currentTable.get(IS_RGB)); } public int getThumbSizeX() { @@ -289,7 +289,7 @@ public String getPixelType() { } public boolean isLittleEndian() { - return new Boolean(currentTable.get(IS_LITTLE_ENDIAN)).booleanValue(); + return Boolean.parseBoolean(currentTable.get(IS_LITTLE_ENDIAN)); } public String getMD5() { @@ -324,7 +324,7 @@ public Time getTimeIncrement() { String timeIncrement = currentTable.get(TIME_INCREMENT); String timeIncrementUnits = currentTable.get(TIME_INCREMENT_UNIT); try { - return timeIncrement == null ? null : FormatTools.getTime(new Double(timeIncrement), timeIncrementUnits); + return timeIncrement == null ? null : FormatTools.getTime(Double.parseDouble(timeIncrement), timeIncrementUnits); } catch (NumberFormatException e) { return null; @@ -351,7 +351,7 @@ public Time getExposureTime(int channel) { String exposure = currentTable.get(EXPOSURE_TIME + channel); String exposureUnits = currentTable.get(EXPOSURE_TIME_UNIT + channel); try { - return exposure == null ? null : FormatTools.getTime(new Double(exposure), exposureUnits); + return exposure == null ? null : FormatTools.getTime(Double.parseDouble(exposure), exposureUnits); } catch (NumberFormatException e) { return null; @@ -360,12 +360,12 @@ public Time getExposureTime(int channel) { public Double getDeltaT(int plane) { String deltaT = currentTable.get(DELTA_T + plane); - return deltaT == null ? null : new Double(deltaT); + return deltaT == null ? null : Double.parseDouble(deltaT); } public Double getPositionX(int plane) { String pos = currentTable.get(X_POSITION + plane); - return pos == null ? null : new Double(pos); + return pos == null ? null : Double.parseDouble(pos); } public String getPositionXUnit(int plane) { @@ -374,7 +374,7 @@ public String getPositionXUnit(int plane) { public Double getPositionY(int plane) { String pos = currentTable.get(Y_POSITION + plane); - return pos == null ? null : new Double(pos); + return pos == null ? null : Double.parseDouble(pos); } public String getPositionYUnit(int plane) { @@ -383,7 +383,7 @@ public String getPositionYUnit(int plane) { public Double getPositionZ(int plane) { String pos = currentTable.get(Z_POSITION + plane); - return pos == null ? null : new Double(pos); + return pos == null ? null : Double.parseDouble(pos); } public String getPositionZUnit(int plane) { @@ -394,7 +394,7 @@ public Length getEmissionWavelength(int channel) { String wavelength = currentTable.get(EMISSION_WAVELENGTH + channel); String emissionUnits = currentTable.get(EMISSION_WAVELENGTH_UNIT + channel); try { - return wavelength == null ? null : FormatTools.getWavelength(new Double(wavelength), emissionUnits); + return wavelength == null ? null : FormatTools.getWavelength(Double.parseDouble(wavelength), emissionUnits); } catch (NumberFormatException e) { return null; @@ -405,7 +405,7 @@ public Length getExcitationWavelength(int channel) { String wavelength = currentTable.get(EXCITATION_WAVELENGTH + channel); String excitationUnits = currentTable.get(EXCITATION_WAVELENGTH_UNIT + channel); try { - return wavelength == null ? null : FormatTools.getWavelength(new Double(wavelength), excitationUnits); + return wavelength == null ? null : FormatTools.getWavelength(Double.parseDouble(wavelength), excitationUnits); } catch (NumberFormatException e) { return null; @@ -828,7 +828,7 @@ private Length getPhysicalSize(String valueKey, String unitKey) { String units = currentTable.get(unitKey); try { UnitsLength unit = units == null ? UnitsLength.MICROMETER : UnitsLength.fromString(units); - return physicalSize == null ? null : UnitsLength.create(new Double(physicalSize), unit); + return physicalSize == null ? null : UnitsLength.create(Double.parseDouble(physicalSize), unit); } catch (NumberFormatException e) { } catch (EnumerationException e) { } diff --git a/components/test-suite/src/loci/tests/testng/FormatWriterTest.java b/components/test-suite/src/loci/tests/testng/FormatWriterTest.java index 5d8846d6f42..e79f0df3e36 100644 --- a/components/test-suite/src/loci/tests/testng/FormatWriterTest.java +++ b/components/test-suite/src/loci/tests/testng/FormatWriterTest.java @@ -110,16 +110,15 @@ public Object[][] getWriterList() { String[] compressionTypes = writers[i].getCompressionTypes(); if (compressionTypes == null) { try { - IFormatWriter w = (IFormatWriter) writers[i].getClass().newInstance(); + IFormatWriter w = (IFormatWriter) writers[i].getClass().getDeclaredConstructor().newInstance(); tmp.add(w); } - catch (InstantiationException ie) { } - catch (IllegalAccessException iae) { } + catch (ReflectiveOperationException roe) { } continue; } for (int q=0; qome pom-bio-formats - 8.0.0-SNAPSHOT + 8.1.0-SNAPSHOT pom Bio-Formats projects @@ -34,27 +34,27 @@ When possible, we advise using the relevant groupId and version properties for your dependencies rather than hardcoding them. --> - 8.0.0-SNAPSHOT + 8.1.0-SNAPSHOT ${maven.build.timestamp} 2017 ${basedir} 1.54c 1.7.2 1.3.14 - 6.0.1 + 6.0.2 ${ome-stubs.version} - 5.3.5 + 5.3.7 ${ome-metakit.version} 2.0.9 5.4.0 6.8 - 6.0.21 + 6.0.24 org.openmicroscopy - 6.3.4 - 5.3.7 - 5.3.2 - 0.1.3 - 1.0.1 + 6.3.6 + 5.3.9 + 5.3.3 + 0.1.4 + 1.0.3 0.2.4 2.7.3 3.28.0