use of loci.common.services.ServiceException in project bioformats by openmicroscopy.
the class WriterUtilities method createMetadata.
public static IMetadata createMetadata(String pixelType, int rgbChannels, int seriesCount, boolean littleEndian, int sizeT) throws Exception {
IMetadata metadata;
try {
ServiceFactory factory = new ServiceFactory();
OMEXMLService service = factory.getInstance(OMEXMLService.class);
metadata = service.createOMEXMLMetadata();
} catch (DependencyException exc) {
throw new FormatException("Could not create OME-XML store.", exc);
} catch (ServiceException exc) {
throw new FormatException("Could not create OME-XML store.", exc);
}
for (int i = 0; i < seriesCount; i++) {
MetadataTools.populateMetadata(metadata, i, "image #" + i, littleEndian, "XYCZT", pixelType, 160, 160, 1, rgbChannels, sizeT, rgbChannels);
}
return metadata;
}
use of loci.common.services.ServiceException in project bioformats by openmicroscopy.
the class LosslessJPEG2000Test method setUp.
@BeforeMethod
public void setUp() throws Exception {
File temp8 = File.createTempFile("test", ".jp2");
File temp16 = File.createTempFile("test", ".jp2");
temp8.deleteOnExit();
temp16.deleteOnExit();
Location.mapId(FILE_8, temp8.getAbsolutePath());
Location.mapId(FILE_16, temp16.getAbsolutePath());
IMetadata metadata8;
try {
ServiceFactory factory = new ServiceFactory();
OMEXMLService service = factory.getInstance(OMEXMLService.class);
metadata8 = service.createOMEXMLMetadata();
} catch (DependencyException exc) {
throw new FormatException("Could not create OME-XML store.", exc);
} catch (ServiceException exc) {
throw new FormatException("Could not create OME-XML store.", exc);
}
MetadataTools.populateMetadata(metadata8, 0, "foo", false, "XYCZT", "uint8", 1, 1, 1, 1, 1, 1);
IFormatWriter writer8 = new JPEG2000Writer();
writer8.setMetadataRetrieve(metadata8);
writer8.setId(FILE_8);
writer8.saveBytes(0, PIXELS_8);
writer8.close();
IMetadata metadata16;
try {
ServiceFactory factory = new ServiceFactory();
OMEXMLService service = factory.getInstance(OMEXMLService.class);
metadata16 = service.createOMEXMLMetadata();
} catch (DependencyException exc) {
throw new FormatException("Could not create OME-XML store.", exc);
} catch (ServiceException exc) {
throw new FormatException("Could not create OME-XML store.", exc);
}
MetadataTools.populateMetadata(metadata16, 0, "foo", false, "XYCZT", "uint16", 1, 1, 1, 1, 1, 1);
IFormatWriter writer16 = new JPEG2000Writer();
writer16.setMetadataRetrieve(metadata16);
writer16.setId(FILE_16);
writer16.saveBytes(0, PIXELS_16);
writer16.close();
}
use of loci.common.services.ServiceException in project bioformats by openmicroscopy.
the class ImageConverter method testConvert.
// -- Utility methods --
/**
* A utility method for converting a file from the command line.
*/
public boolean testConvert(IFormatWriter writer, String[] args) throws FormatException, IOException {
nextOutputIndex.clear();
options.setValidate(validate);
writer.setMetadataOptions(options);
firstTile = true;
boolean success = parseArgs(args);
if (!success) {
return false;
}
if (printVersion) {
CommandLineTools.printVersion();
return true;
}
CommandLineTools.runUpgradeCheck(args);
if (in == null || out == null) {
printUsage();
return false;
}
if (new Location(out).exists()) {
if (overwrite == null) {
LOGGER.warn("Output file {} exists.", out);
LOGGER.warn("Do you want to overwrite it? ([y]/n)");
BufferedReader r = new BufferedReader(new InputStreamReader(System.in, Constants.ENCODING));
String choice = r.readLine().trim().toLowerCase();
overwrite = !choice.startsWith("n");
}
if (!overwrite) {
LOGGER.warn("Exiting; next time, please specify an output file that " + "does not exist.");
return false;
} else {
new Location(out).delete();
}
}
if (map != null)
Location.mapId(in, map);
long start = System.currentTimeMillis();
LOGGER.info(in);
reader = new ImageReader();
if (stitch) {
reader = new FileStitcher(reader);
Location f = new Location(in);
String pat = null;
if (!f.exists()) {
pat = in;
} else {
pat = FilePattern.findPattern(f);
}
if (pat != null)
in = pat;
}
if (separate)
reader = new ChannelSeparator(reader);
if (merge)
reader = new ChannelMerger(reader);
if (fill)
reader = new ChannelFiller(reader);
minMax = null;
if (autoscale) {
reader = new MinMaxCalculator(reader);
minMax = (MinMaxCalculator) reader;
}
reader.setMetadataOptions(options);
reader.setGroupFiles(group);
reader.setMetadataFiltered(true);
reader.setOriginalMetadataPopulated(true);
OMEXMLService service = null;
try {
ServiceFactory factory = new ServiceFactory();
service = factory.getInstance(OMEXMLService.class);
reader.setMetadataStore(service.createOMEXMLMetadata());
} catch (DependencyException de) {
throw new MissingLibraryException(OMEXMLServiceImpl.NO_OME_XML_MSG, de);
} catch (ServiceException se) {
throw new FormatException(se);
}
reader.setId(in);
MetadataStore store = reader.getMetadataStore();
MetadataTools.populatePixels(store, reader, false, false);
boolean dimensionsSet = true;
if (width == 0 || height == 0) {
// otherwise default to series 0
if (series >= 0) {
reader.setSeries(series);
}
width = reader.getSizeX();
height = reader.getSizeY();
dimensionsSet = false;
}
if (channel >= reader.getEffectiveSizeC()) {
throw new FormatException("Invalid channel '" + channel + "' (" + reader.getEffectiveSizeC() + " channels in source file)");
}
if (timepoint >= reader.getSizeT()) {
throw new FormatException("Invalid timepoint '" + timepoint + "' (" + reader.getSizeT() + " timepoints in source file)");
}
if (zSection >= reader.getSizeZ()) {
throw new FormatException("Invalid Z section '" + zSection + "' (" + reader.getSizeZ() + " Z sections in source file)");
}
if (store instanceof MetadataRetrieve) {
try {
String xml = service.getOMEXML(service.asRetrieve(store));
OMEXMLMetadataRoot root = (OMEXMLMetadataRoot) store.getRoot();
IMetadata meta = service.createOMEXMLMetadata(xml);
if (series >= 0) {
Image exportImage = new Image(root.getImage(series));
Pixels exportPixels = new Pixels(root.getImage(series).getPixels());
exportImage.setPixels(exportPixels);
OMEXMLMetadataRoot newRoot = (OMEXMLMetadataRoot) meta.getRoot();
while (newRoot.sizeOfImageList() > 0) {
newRoot.removeImage(newRoot.getImage(0));
}
newRoot.addImage(exportImage);
meta.setRoot(newRoot);
meta.setPixelsSizeX(new PositiveInteger(width), 0);
meta.setPixelsSizeY(new PositiveInteger(height), 0);
if (autoscale) {
store.setPixelsType(PixelType.UINT8, 0);
}
if (channel >= 0) {
meta.setPixelsSizeC(new PositiveInteger(1), 0);
}
if (zSection >= 0) {
meta.setPixelsSizeZ(new PositiveInteger(1), 0);
}
if (timepoint >= 0) {
meta.setPixelsSizeT(new PositiveInteger(1), 0);
}
writer.setMetadataRetrieve((MetadataRetrieve) meta);
} else {
for (int i = 0; i < reader.getSeriesCount(); i++) {
meta.setPixelsSizeX(new PositiveInteger(width), 0);
meta.setPixelsSizeY(new PositiveInteger(height), 0);
if (autoscale) {
store.setPixelsType(PixelType.UINT8, i);
}
if (channel >= 0) {
meta.setPixelsSizeC(new PositiveInteger(1), 0);
}
if (zSection >= 0) {
meta.setPixelsSizeZ(new PositiveInteger(1), 0);
}
if (timepoint >= 0) {
meta.setPixelsSizeT(new PositiveInteger(1), 0);
}
}
writer.setMetadataRetrieve((MetadataRetrieve) meta);
}
} catch (ServiceException e) {
throw new FormatException(e);
}
}
writer.setWriteSequentially(true);
if (writer instanceof TiffWriter) {
((TiffWriter) writer).setBigTiff(bigtiff);
} else if (writer instanceof ImageWriter) {
IFormatWriter w = ((ImageWriter) writer).getWriter(out);
if (w instanceof TiffWriter) {
((TiffWriter) w).setBigTiff(bigtiff);
}
}
String format = writer.getFormat();
LOGGER.info("[{}] -> {} [{}]", new Object[] { reader.getFormat(), out, format });
long mid = System.currentTimeMillis();
int total = 0;
int num = writer.canDoStacks() ? reader.getSeriesCount() : 1;
long read = 0, write = 0;
int first = series == -1 ? 0 : series;
int last = series == -1 ? num : series + 1;
long timeLastLogged = System.currentTimeMillis();
for (int q = first; q < last; q++) {
reader.setSeries(q);
firstTile = true;
if (!dimensionsSet) {
width = reader.getSizeX();
height = reader.getSizeY();
}
int writerSeries = series == -1 ? q : 0;
writer.setSeries(writerSeries);
writer.setInterleaved(reader.isInterleaved() && !autoscale);
writer.setValidBitsPerPixel(reader.getBitsPerPixel());
int numImages = writer.canDoStacks() ? reader.getImageCount() : 1;
int startPlane = (int) Math.max(0, firstPlane);
int endPlane = (int) Math.min(numImages, lastPlane);
numImages = endPlane - startPlane;
if (channel >= 0) {
numImages /= reader.getEffectiveSizeC();
}
if (zSection >= 0) {
numImages /= reader.getSizeZ();
}
if (timepoint >= 0) {
numImages /= reader.getSizeT();
}
total += numImages;
int count = 0;
for (int i = startPlane; i < endPlane; i++) {
int[] coords = reader.getZCTCoords(i);
if ((zSection >= 0 && coords[0] != zSection) || (channel >= 0 && coords[1] != channel) || (timepoint >= 0 && coords[2] != timepoint)) {
continue;
}
String outputName = FormatTools.getFilename(q, i, reader, out, zeroPadding);
if (outputName.equals(FormatTools.getTileFilename(0, 0, 0, outputName))) {
writer.setId(outputName);
if (compression != null)
writer.setCompression(compression);
} else {
int tileNum = outputName.indexOf(FormatTools.TILE_NUM);
int tileX = outputName.indexOf(FormatTools.TILE_X);
int tileY = outputName.indexOf(FormatTools.TILE_Y);
if (tileNum < 0 && (tileX < 0 || tileY < 0)) {
throw new FormatException("Invalid file name pattern; " + FormatTools.TILE_NUM + " or both of " + FormatTools.TILE_X + " and " + FormatTools.TILE_Y + " must be specified.");
}
}
int outputIndex = 0;
if (nextOutputIndex.containsKey(outputName)) {
outputIndex = nextOutputIndex.get(outputName);
}
long s = System.currentTimeMillis();
long m = convertPlane(writer, i, outputIndex, outputName);
long e = System.currentTimeMillis();
read += m - s;
write += e - m;
nextOutputIndex.put(outputName, outputIndex + 1);
if (i == endPlane - 1) {
nextOutputIndex.remove(outputName);
}
// log number of planes processed every second or so
if (count == numImages - 1 || (e - timeLastLogged) / 1000 > 0) {
int current = (count - startPlane) + 1;
int percent = 100 * current / numImages;
StringBuilder sb = new StringBuilder();
sb.append("\t");
int numSeries = last - first;
if (numSeries > 1) {
sb.append("Series ");
sb.append(q);
sb.append(": converted ");
} else
sb.append("Converted ");
LOGGER.info(sb.toString() + "{}/{} planes ({}%)", new Object[] { current, numImages, percent });
timeLastLogged = e;
}
count++;
}
}
writer.close();
long end = System.currentTimeMillis();
LOGGER.info("[done]");
// output timing results
float sec = (end - start) / 1000f;
long initial = mid - start;
float readAvg = (float) read / total;
float writeAvg = (float) write / total;
LOGGER.info("{}s elapsed ({}+{}ms per plane, {}ms overhead)", new Object[] { sec, readAvg, writeAvg, initial });
return true;
}
use of loci.common.services.ServiceException in project bioformats by openmicroscopy.
the class FormatReaderTest method setupReader.
// -- Helper methods --
/**
* Sets up the current IFormatReader.
*/
private void setupReader() {
// Remove external SlideBook6Reader class for testing purposes
ImageReader ir = new ImageReader();
reader = new BufferedImageReader(new FileStitcher(new Memoizer(ir, Memoizer.DEFAULT_MINIMUM_ELAPSED, new File(""))));
reader.setMetadataOptions(new DefaultMetadataOptions(MetadataLevel.NO_OVERLAYS));
reader.setNormalized(true);
reader.setOriginalMetadataPopulated(false);
reader.setMetadataFiltered(true);
MetadataStore store = null;
try {
store = omexmlService.createOMEXMLMetadata();
} catch (ServiceException e) {
LOGGER.warn("Could not parse OME-XML", e);
}
reader.setMetadataStore(store);
}
use of loci.common.services.ServiceException in project bioformats by openmicroscopy.
the class FileConvert method initialize.
/**
* Set up the file reader and writer, ensuring that the input file is
* associated with the reader and the output file is associated with the
* writer.
*
* @return true if the reader and writer were successfully set up, or false
* if an error occurred
*/
private boolean initialize() {
Exception exception = null;
try {
// construct the object that stores OME-XML metadata
ServiceFactory factory = new ServiceFactory();
OMEXMLService service = factory.getInstance(OMEXMLService.class);
IMetadata omexml = service.createOMEXMLMetadata();
// set up the reader and associate it with the input file
reader = new ImageReader();
reader.setMetadataStore(omexml);
reader.setId(inputFile);
// set up the writer and associate it with the output file
writer = new ImageWriter();
writer.setMetadataRetrieve(omexml);
writer.setInterleaved(reader.isInterleaved());
writer.setId(outputFile);
} catch (FormatException e) {
exception = e;
} catch (IOException e) {
exception = e;
} catch (DependencyException e) {
exception = e;
} catch (ServiceException e) {
exception = e;
}
if (exception != null) {
System.err.println("Failed to initialize files.");
exception.printStackTrace();
}
return exception == null;
}
Aggregations