use of loci.formats.FormatException in project bioformats by openmicroscopy.
the class Colorizer method applyDisplayRanges.
// -- Helper methods --
private void applyDisplayRanges(ImagePlus imp, int series) {
if (imp instanceof VirtualImagePlus) {
// virtual stacks handle their own display ranges
return;
}
final ImporterOptions options = process.getOptions();
final ImageProcessorReader reader = process.getReader();
final int pixelType = reader.getPixelType();
final boolean autoscale = options.isAutoscale() || // always autoscale float data
FormatTools.isFloatingPoint(pixelType);
final int cSize = imp.getNChannels();
final double[] cMin = new double[cSize];
final double[] cMax = new double[cSize];
Arrays.fill(cMin, Double.NaN);
Arrays.fill(cMax, Double.NaN);
if (autoscale) {
// extract display ranges for autoscaling
final MinMaxCalculator minMaxCalc = process.getMinMaxCalculator();
final int cBegin = process.getCBegin(series);
final int cStep = process.getCStep(series);
for (int c = 0; c < cSize; c++) {
final int cIndex = cBegin + c * cStep;
Double cMinVal = null, cMaxVal = null;
try {
cMinVal = minMaxCalc.getChannelGlobalMinimum(cIndex);
cMaxVal = minMaxCalc.getChannelGlobalMaximum(cIndex);
if (cMinVal == null) {
cMinVal = minMaxCalc.getChannelKnownMinimum(cIndex);
}
if (cMaxVal == null) {
cMaxVal = minMaxCalc.getChannelKnownMaximum(cIndex);
}
} catch (FormatException exc) {
} catch (IOException exc) {
}
if (cMinVal != null)
cMin[c] = cMinVal;
if (cMaxVal != null)
cMax[c] = cMaxVal;
}
}
// for calibrated data, the offset from zero
final double zeroOffset = getZeroOffset(imp);
// fill in default display ranges as appropriate
final double min, max;
if (FormatTools.isFloatingPoint(pixelType)) {
// no defined min and max values for floating point data
min = max = Double.NaN;
} else {
final int bitDepth = reader.getBitsPerPixel();
final double halfPow = Math.pow(2, bitDepth - 1);
final double fullPow = 2 * halfPow;
final boolean signed = FormatTools.isSigned(pixelType);
if (signed) {
// signed data is centered at 0
min = -halfPow;
max = halfPow - 1;
} else {
// unsigned data begins at 0
min = 0;
max = fullPow - 1;
}
for (int c = 0; c < cSize; c++) {
if (Double.isNaN(cMin[c]))
cMin[c] = min;
if (Double.isNaN(cMax[c]))
cMax[c] = max;
}
}
// apply display ranges
if (imp instanceof CompositeImage) {
// apply channel display ranges
final CompositeImage compImage = (CompositeImage) imp;
for (int c = 0; c < cSize; c++) {
LUT lut = compImage.getChannelLut(c + 1);
// NB: Uncalibrate values before assigning to LUT min/max.
lut.min = cMin[c] - zeroOffset;
lut.max = cMax[c] - zeroOffset;
}
} else {
// compute global display range from channel display ranges
double globalMin = Double.POSITIVE_INFINITY;
double globalMax = Double.NEGATIVE_INFINITY;
for (int c = 0; c < cSize; c++) {
if (cMin[c] < globalMin)
globalMin = cMin[c];
if (cMax[c] > globalMax)
globalMax = cMax[c];
}
// NB: Uncalibrate values before assigning to display range min/max.
globalMin -= zeroOffset;
globalMax -= zeroOffset;
// apply global display range
ImageProcessor proc = imp.getProcessor();
if (proc instanceof ColorProcessor) {
// NB: Should never occur. ;-)
final ColorProcessor colorProc = (ColorProcessor) proc;
colorProc.setMinAndMax(globalMin, globalMax, 3);
} else {
ColorModel model = proc.getColorModel();
proc.setMinAndMax(globalMin, globalMax);
proc.setColorModel(model);
imp.setDisplayRange(globalMin, globalMax);
}
}
}
use of loci.formats.FormatException in project bioformats by openmicroscopy.
the class ImagePlusReader method readPlanes.
private ImageStack readPlanes(ImportProcess process, int s, List<LUT> luts, boolean thumbnail) throws FormatException, IOException {
final ImageProcessorReader reader = process.getReader();
reader.setSeries(s);
final int zCount = process.getZCount(s);
final int cCount = process.getCCount(s);
final int tCount = process.getTCount(s);
final IMetadata meta = process.getOMEMetadata();
// get list of planes to load
final boolean[] load = getPlanesToLoad(s);
int current = 0, total = 0;
for (int j = 0; j < load.length; j++) if (load[j])
total++;
final List<ImageProcessor> procs = new ArrayList<ImageProcessor>();
final List<String> labels = new ArrayList<String>();
// read applicable image planes
final Region region = process.getCropRegion(s);
for (int i = 0; i < load.length; i++) {
if (!load[i])
continue;
// limit message update rate
updateTiming(s, current, current++, total);
// get image processor for ith plane
final ImageProcessor[] p = readProcessors(process, i, region, thumbnail);
if (p == null || p.length == 0) {
throw new FormatException("Cannot read plane #" + i);
}
// generate a label for ith plane
String label = constructSliceLabel(i, reader, meta, s, zCount, cCount, tCount);
for (ImageProcessor ip : p) {
procs.add(ip);
labels.add(label);
}
}
return createStack(procs, labels, luts);
}
use of loci.formats.FormatException in project bioformats by openmicroscopy.
the class Slicer method makeStack.
/**
* Returns a new ImageStack using the given ImageStack as a template.
*/
private ImageStack makeStack(ImageStack stack) {
if (!(stack instanceof BFVirtualStack)) {
return new ImageStack(stack.getWidth(), stack.getHeight());
}
BFVirtualStack virtualStack = (BFVirtualStack) stack;
String path = virtualStack.getPath();
ImageProcessorReader reader = virtualStack.getReader();
try {
return new BFVirtualStack(path, reader, false, false, false);
} catch (FormatException e) {
WindowTools.reportException(e);
} catch (IOException e) {
WindowTools.reportException(e);
}
return null;
}
use of loci.formats.FormatException in project bioformats by openmicroscopy.
the class LegacyND2Reader method initFile.
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
try {
openFile(id);
int numSeries = getNumSeries();
core.clear();
for (int i = 0; i < numSeries; i++) {
CoreMetadata ms = new CoreMetadata();
core.add(ms);
ms.sizeX = getWidth(i);
if (ms.sizeX % 2 != 0)
ms.sizeX++;
ms.sizeY = getHeight(i);
ms.sizeZ = getZSlices(i);
ms.sizeT = getTFrames(i);
ms.sizeC = getChannels(i);
int bytes = getBytesPerPixel(i);
if (bytes % 3 == 0) {
ms.sizeC *= 3;
bytes /= 3;
ms.rgb = true;
} else
ms.rgb = false;
ms.pixelType = FormatTools.pixelTypeFromBytes(bytes, false, true);
ms.imageCount = ms.sizeZ * ms.sizeT;
if (!ms.rgb)
ms.imageCount *= ms.sizeC;
ms.interleaved = true;
ms.littleEndian = true;
ms.dimensionOrder = "XYCZT";
ms.indexed = false;
ms.falseColor = false;
}
} catch (UnsatisfiedLinkError e) {
throw new MissingLibraryException(NO_NIKON_MSG, e);
} catch (Exception e) {
throw new MissingLibraryException(NO_NIKON_MSG, e);
}
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this);
for (int i = 0; i < getSeriesCount(); i++) {
store.setImageName("Series " + (i + 1), i);
}
}
use of loci.formats.FormatException in project bioformats by openmicroscopy.
the class LeicaReader method initFile.
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
close();
String leiFile = findLEIFile(id);
if (leiFile == null || leiFile.trim().length() == 0 || new Location(leiFile).isDirectory()) {
if (checkSuffix(id, TiffReader.TIFF_SUFFIXES)) {
super.initFile(id);
TiffReader r = new TiffReader();
r.setMetadataStore(getMetadataStore());
r.setId(id);
core = new ArrayList<CoreMetadata>(r.getCoreMetadataList());
metadataStore = r.getMetadataStore();
final Map<String, Object> globalMetadata = r.getGlobalMetadata();
for (final Map.Entry<String, Object> entry : globalMetadata.entrySet()) {
addGlobalMeta(entry.getKey(), entry.getValue());
}
r.close();
files = new List[] { new ArrayList<String>() };
files[0].add(id);
tiff = new MinimalTiffReader();
return;
} else {
throw new FormatException("LEI file not found.");
}
}
// parse the LEI file
super.initFile(leiFile);
leiFilename = new File(leiFile).exists() ? new Location(leiFile).getAbsolutePath() : id;
in = new RandomAccessInputStream(leiFile);
byte[] data = null;
try {
data = new byte[(int) in.length()];
in.read(data);
} finally {
in.close();
}
in = new RandomAccessInputStream(data);
MetadataLevel metadataLevel = metadataOptions.getMetadataLevel();
seriesNames = new ArrayList<String>();
byte[] fourBytes = new byte[4];
in.read(fourBytes);
core.get(0).littleEndian = (fourBytes[0] == TiffConstants.LITTLE && fourBytes[1] == TiffConstants.LITTLE && fourBytes[2] == TiffConstants.LITTLE && fourBytes[3] == TiffConstants.LITTLE);
boolean realLittleEndian = isLittleEndian();
in.order(isLittleEndian());
LOGGER.info("Reading metadata blocks");
in.skipBytes(8);
int addr = in.readInt();
headerIFDs = new IFDList();
while (addr != 0) {
IFD ifd = new IFD();
headerIFDs.add(ifd);
in.seek(addr + 4);
int tag = in.readInt();
while (tag != 0) {
// create the IFD structure
int offset = in.readInt();
long pos = in.getFilePointer();
in.seek(offset + 12);
int size = in.readInt();
ifd.putIFDValue(tag, in.getFilePointer());
in.seek(pos);
tag = in.readInt();
}
addr = in.readInt();
}
numSeries = headerIFDs.size();
tileWidth = new int[numSeries];
tileHeight = new int[numSeries];
core.clear();
for (int i = 0; i < numSeries; i++) {
core.add(new CoreMetadata());
}
files = new List[numSeries];
channelNames = new List[getSeriesCount()];
emWaves = new List[getSeriesCount()];
exWaves = new List[getSeriesCount()];
cutInPopulated = new boolean[getSeriesCount()][];
cutOutPopulated = new boolean[getSeriesCount()][];
filterRefPopulated = new boolean[getSeriesCount()][];
for (int i = 0; i < getSeriesCount(); i++) {
channelNames[i] = new ArrayList();
emWaves[i] = new ArrayList();
exWaves[i] = new ArrayList();
}
// determine the length of a filename
LOGGER.info("Parsing metadata blocks");
core.get(0).littleEndian = !isLittleEndian();
int seriesIndex = 0;
int invalidCount = 0;
valid = new boolean[numSeries];
timestamps = new String[headerIFDs.size()][];
for (int i = 0; i < headerIFDs.size(); i++) {
IFD ifd = headerIFDs.get(i);
valid[i] = true;
if (ifd.get(SERIES) != null) {
long offset = ((Long) ifd.get(SERIES)).longValue();
in.seek(offset + 8);
nameLength = in.readInt() * 2;
}
in.seek(((Long) ifd.get(IMAGES)).longValue());
parseFilenames(i);
if (!valid[i])
invalidCount++;
}
numSeries -= invalidCount;
if (numSeries <= 0) {
throw new FormatException("TIFF files not found");
}
int[] count = new int[getSeriesCount()];
for (int i = 0; i < getSeriesCount(); i++) {
count[i] = core.get(i).imageCount;
}
final List<String>[] tempFiles = files;
IFDList tempIFDs = headerIFDs;
core = new ArrayList<CoreMetadata>(numSeries);
files = new List[numSeries];
headerIFDs = new IFDList();
int index = 0;
core.clear();
for (int i = 0; i < numSeries; i++) {
CoreMetadata ms = new CoreMetadata();
while (index < valid.length && !valid[index]) index++;
if (index >= valid.length) {
break;
}
ms.imageCount = count[index];
files[i] = tempFiles[index];
Collections.sort(files[i]);
headerIFDs.add(tempIFDs.get(index));
index++;
core.add(ms);
}
tiff = new MinimalTiffReader();
LOGGER.info("Populating metadata");
if (headerIFDs == null)
headerIFDs = ifds;
seriesDescriptions = new ArrayList<String>();
physicalSizes = new double[headerIFDs.size()][5];
pinhole = new double[headerIFDs.size()];
exposureTime = new double[headerIFDs.size()];
channelColor = new Color[headerIFDs.size()][];
for (int i = 0; i < headerIFDs.size(); i++) {
IFD ifd = headerIFDs.get(i);
CoreMetadata ms = core.get(i);
ms.littleEndian = isLittleEndian();
setSeries(i);
Integer[] keys = ifd.keySet().toArray(new Integer[ifd.size()]);
Arrays.sort(keys);
for (Integer key : keys) {
long offset = ((Long) ifd.get(key)).longValue();
in.seek(offset);
if (key.equals(SERIES)) {
parseSeriesTag();
} else if (key.equals(IMAGES)) {
parseImageTag(i);
} else if (key.equals(DIMDESCR)) {
parseDimensionTag(i);
} else if (key.equals(TIMEINFO) && metadataLevel != MetadataLevel.MINIMUM) {
parseTimeTag(i);
} else if (key.equals(EXPERIMENT) && metadataLevel != MetadataLevel.MINIMUM) {
parseExperimentTag();
} else if (key.equals(LUTDESC)) {
parseLUT(i);
} else if (key.equals(CHANDESC) && metadataLevel != MetadataLevel.MINIMUM) {
parseChannelTag();
}
}
ms.orderCertain = true;
ms.littleEndian = isLittleEndian();
ms.falseColor = true;
ms.metadataComplete = true;
ms.interleaved = false;
String filename = (String) files[i].get(0);
if (checkSuffix(filename, TiffReader.TIFF_SUFFIXES)) {
RandomAccessInputStream s = new RandomAccessInputStream(filename, 16);
try {
TiffParser parser = new TiffParser(s);
parser.setDoCaching(false);
IFD firstIFD = parser.getFirstIFD();
parser.fillInIFD(firstIFD);
ms.sizeX = (int) firstIFD.getImageWidth();
ms.sizeY = (int) firstIFD.getImageLength();
// override the .lei pixel type, in case a TIFF file was overwritten
ms.pixelType = firstIFD.getPixelType();
// won't affect the pixel data
if (FormatTools.getBytesPerPixel(ms.pixelType) > 1) {
ms.littleEndian = firstIFD.isLittleEndian();
} else {
ms.littleEndian = realLittleEndian;
}
tileWidth[i] = (int) firstIFD.getTileWidth();
tileHeight[i] = (int) firstIFD.getTileLength();
} finally {
s.close();
}
} else {
ms.littleEndian = realLittleEndian;
}
}
for (int i = 0; i < getSeriesCount(); i++) {
setSeries(i);
CoreMetadata ms = core.get(i);
if (getSizeZ() == 0)
ms.sizeZ = 1;
if (getSizeT() == 0)
ms.sizeT = 1;
if (getSizeC() == 0)
ms.sizeC = 1;
if (getImageCount() == 0)
ms.imageCount = 1;
if (getImageCount() == 1 && getSizeZ() * getSizeT() > 1) {
ms.sizeZ = 1;
ms.sizeT = 1;
}
if (getSizeY() == 1 || getSizeY() == getSizeZ() || getSizeY() == getSizeT()) {
// XZ or XT scan
if (getSizeZ() > 1 && getImageCount() == getSizeC() * getSizeT()) {
ms.sizeY = getSizeZ();
ms.sizeZ = 1;
} else if (getSizeT() > 1 && getImageCount() == getSizeC() * getSizeZ()) {
ms.sizeY = getSizeT();
ms.sizeT = 1;
}
}
if (isRGB())
ms.indexed = false;
ms.dimensionOrder = MetadataTools.makeSaneDimensionOrder(getDimensionOrder());
}
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this, true);
// minimum metadata level.
for (int i = 0; i < getSeriesCount(); i++) {
store.setImageName(seriesNames.get(i), i);
}
if (metadataLevel == MetadataLevel.MINIMUM)
return;
for (int i = 0; i < getSeriesCount(); i++) {
CoreMetadata ms = core.get(i);
IFD ifd = headerIFDs.get(i);
long firstPlane = 0;
if (i < timestamps.length && timestamps[i] != null && timestamps[i].length > 0) {
firstPlane = DateTools.getTime(timestamps[i][0], DATE_FORMAT, ":");
String date = DateTools.formatDate(timestamps[i][0], DATE_FORMAT);
if (date != null) {
store.setImageAcquisitionDate(new Timestamp(date), i);
}
}
store.setImageDescription(seriesDescriptions.get(i), i);
String instrumentID = MetadataTools.createLSID("Instrument", i);
store.setInstrumentID(instrumentID, i);
// parse instrument data
nextDetector = 0;
nextChannel = 0;
detectors.clear();
cutInPopulated[i] = new boolean[ms.sizeC];
cutOutPopulated[i] = new boolean[ms.sizeC];
filterRefPopulated[i] = new boolean[ms.sizeC];
Integer[] keys = ifd.keySet().toArray(new Integer[ifd.size()]);
Arrays.sort(keys);
int nextInstrumentBlock = 1;
sequential = DataTools.indexOf(keys, SEQ_SCANNERSET) != -1;
for (Integer key : keys) {
if (key.equals(FILTERSET) || key.equals(SCANNERSET) || key.equals(SEQ_SCANNERSET) || key.equals(SEQ_FILTERSET) || (key > SEQ_SCANNERSET && key < SEQ_SCANNERSET_END) || (key > SEQ_FILTERSET && key < SEQ_FILTERSET_END)) {
if (sequential && (key.equals(FILTERSET) || key.equals(SCANNERSET))) {
continue;
}
long offset = ((Long) ifd.get(key)).longValue();
in.seek(offset);
setSeries(i);
parseInstrumentData(store, nextInstrumentBlock++);
}
}
activeChannelIndices.clear();
// link Instrument and Image
store.setImageInstrumentRef(instrumentID, i);
Length sizeX = FormatTools.getPhysicalSizeX(physicalSizes[i][0]);
Length sizeY = FormatTools.getPhysicalSizeY(physicalSizes[i][1]);
Length sizeZ = FormatTools.getPhysicalSizeZ(physicalSizes[i][2]);
if (sizeX != null) {
store.setPixelsPhysicalSizeX(sizeX, i);
}
if (sizeY != null) {
store.setPixelsPhysicalSizeY(sizeY, i);
}
if (sizeZ != null) {
store.setPixelsPhysicalSizeZ(sizeZ, i);
}
if ((int) physicalSizes[i][4] > 0) {
store.setPixelsTimeIncrement(new Time(physicalSizes[i][4], UNITS.SECOND), i);
}
for (int j = 0; j < ms.imageCount; j++) {
if (timestamps[i] != null && j < timestamps[i].length) {
long time = DateTools.getTime(timestamps[i][j], DATE_FORMAT, ":");
double elapsedTime = (double) (time - firstPlane) / 1000;
store.setPlaneDeltaT(new Time(elapsedTime, UNITS.SECOND), i, j);
if (exposureTime[i] > 0) {
store.setPlaneExposureTime(new Time(exposureTime[i], UNITS.SECOND), i, j);
}
}
}
}
setSeries(0);
}
Aggregations