use of loci.common.services.ServiceException in project bioformats by openmicroscopy.
the class LIFReader method initMetadata.
// -- Helper methods --
/**
* Parses a string of XML and puts the values in a Hashtable.
*/
private void initMetadata(String xml) throws FormatException, IOException {
try {
ServiceFactory factory = new ServiceFactory();
OMEXMLService service = factory.getInstance(OMEXMLService.class);
service.createOMEXMLMetadata();
} catch (DependencyException exc) {
throw new FormatException("Could not create OME-XML store.", exc);
} catch (ServiceException exc) {
throw new FormatException("Could not create OME-XML store.", exc);
}
MetadataStore store = makeFilterMetadata();
// the XML blocks stored in a LIF file are invalid,
// because they don't have a root node
xml = "<?xml version=\"1.0\" encoding=\"" + ENCODING + "\"?><LEICA>" + xml + "</LEICA>";
xml = XMLTools.sanitizeXML(xml);
LOGGER.trace(xml);
translateMetadata(getMetadataRoot(xml));
for (int i = 0; i < imageNames.length; i++) {
setSeries(i);
addSeriesMeta("Image name", imageNames[i]);
}
setSeries(0);
// set up mapping to rearrange channels
// for instance, the green channel may be #0, and the red channel may be #1
realChannel = new int[tileCount.length][];
int nextLut = 0;
for (int i = 0; i < core.size(); i++) {
int index = getTileIndex(i);
if (realChannel[index] != null) {
continue;
}
CoreMetadata ms = core.get(i);
realChannel[index] = new int[ms.sizeC];
for (int q = 0; q < ms.sizeC; q++) {
String lut = "";
if (nextLut < lutNames.size()) {
lut = lutNames.get(nextLut++).toLowerCase();
}
if (!CHANNEL_PRIORITIES.containsKey(lut))
lut = "";
realChannel[index][q] = CHANNEL_PRIORITIES.get(lut).intValue();
}
int[] sorted = new int[ms.sizeC];
Arrays.fill(sorted, -1);
for (int q = 0; q < sorted.length; q++) {
int min = Integer.MAX_VALUE;
int minIndex = -1;
for (int n = 0; n < ms.sizeC; n++) {
if (realChannel[index][n] < min && !DataTools.containsValue(sorted, n)) {
min = realChannel[index][n];
minIndex = n;
}
}
sorted[q] = minIndex;
}
}
MetadataTools.populatePixels(store, this, true, false);
int roiCount = 0;
for (int i = 0; i < getSeriesCount(); i++) {
setSeries(i);
String instrumentID = MetadataTools.createLSID("Instrument", i);
store.setInstrumentID(instrumentID, i);
int index = getTileIndex(i);
store.setMicroscopeModel(microscopeModels[index], i);
store.setMicroscopeType(getMicroscopeType("Other"), i);
String objectiveID = MetadataTools.createLSID("Objective", i, 0);
store.setObjectiveID(objectiveID, i, 0);
store.setObjectiveLensNA(lensNA[index], i, 0);
store.setObjectiveSerialNumber(serialNumber[index], i, 0);
if (magnification[index] != null) {
store.setObjectiveNominalMagnification(magnification[index], i, 0);
}
store.setObjectiveImmersion(getImmersion(immersions[index]), i, 0);
store.setObjectiveCorrection(getCorrection(corrections[index]), i, 0);
store.setObjectiveModel(objectiveModels[index], i, 0);
if (cutIns[index] != null && filterModels[index] != null) {
int channel = 0;
if (cutIns[index].size() >= filterModels[index].size() * 2) {
int diff = cutIns[index].size() - filterModels[index].size();
for (int q = 0; q < diff; q++) {
cutIns[index].remove(filterModels[index].size());
}
}
for (int filter = 0; filter < cutIns[index].size(); filter++) {
String filterID = MetadataTools.createLSID("Filter", i, filter);
store.setFilterID(filterID, i, filter);
if (filterModels[index] != null && filter < filterModels[index].size()) {
store.setFilterModel((String) filterModels[index].get(filter), i, filter);
}
store.setTransmittanceRangeCutIn((Length) cutIns[index].get(filter), i, filter);
store.setTransmittanceRangeCutOut((Length) cutOuts[index].get(filter), i, filter);
}
}
final List<Double> lasers = laserWavelength[index];
final List<Double> laserIntensities = laserIntensity[index];
final List<Boolean> active = laserActive[index];
final List<Boolean> frap = laserFrap[index];
int nextChannel = 0;
if (lasers != null) {
int laserIndex = 0;
while (laserIndex < lasers.size()) {
if ((Double) lasers.get(laserIndex) == 0) {
lasers.remove(laserIndex);
} else {
laserIndex++;
}
}
for (int laser = 0; laser < lasers.size(); laser++) {
String id = MetadataTools.createLSID("LightSource", i, laser);
store.setLaserID(id, i, laser);
store.setLaserType(LaserType.OTHER, i, laser);
store.setLaserLaserMedium(LaserMedium.OTHER, i, laser);
Double wavelength = (Double) lasers.get(laser);
Length wave = FormatTools.getWavelength(wavelength);
if (wave != null) {
store.setLaserWavelength(wave, i, laser);
}
}
Set<Integer> ignoredChannels = new HashSet<Integer>();
final List<Integer> validIntensities = new ArrayList<Integer>();
int size = lasers.size();
int channel = 0;
Set<Integer> channels = new HashSet<Integer>();
for (int laser = 0; laser < laserIntensities.size(); laser++) {
double intensity = (Double) laserIntensities.get(laser);
channel = laser / size;
if (intensity < 100) {
validIntensities.add(laser);
channels.add(channel);
}
ignoredChannels.add(channel);
}
// remove channels w/o valid intensities
ignoredChannels.removeAll(channels);
// remove entries if channel has 2 wavelengths
// e.g. 30% 458 70% 633
int s = validIntensities.size();
int jj;
Set<Integer> toRemove = new HashSet<Integer>();
int as = active.size();
for (int j = 0; j < s; j++) {
if (j < as && !(Boolean) active.get(j)) {
toRemove.add(validIntensities.get(j));
}
jj = j + 1;
if (jj < s) {
int v = validIntensities.get(j) / size;
int vv = validIntensities.get(jj) / size;
if (vv == v) {
// do not consider that channel.
toRemove.add(validIntensities.get(j));
toRemove.add(validIntensities.get(jj));
ignoredChannels.add(j);
}
}
}
if (toRemove.size() > 0) {
validIntensities.removeAll(toRemove);
}
boolean noNames = true;
if (channelNames[index] != null) {
for (String name : channelNames[index]) {
if (name != null && !name.equals("")) {
noNames = false;
break;
}
}
}
if (!noNames && frap != null) {
// only use name for frap.
for (int k = 0; k < frap.size(); k++) {
if (!frap.get(k)) {
noNames = true;
break;
}
}
}
int nextFilter = 0;
// int nextFilter = cutIns[i].size() - getEffectiveSizeC();
for (int k = 0; k < validIntensities.size(); k++, nextChannel++) {
int laserArrayIndex = validIntensities.get(k);
double intensity = (Double) laserIntensities.get(laserArrayIndex);
int laser = laserArrayIndex % lasers.size();
Double wavelength = (Double) lasers.get(laser);
if (wavelength != 0) {
while (ignoredChannels.contains(nextChannel)) {
nextChannel++;
}
while (channelNames != null && nextChannel < getEffectiveSizeC() && channelNames[index] != null && ((channelNames[index][nextChannel] == null || channelNames[index][nextChannel].equals("")) && !noNames)) {
nextChannel++;
}
if (nextChannel < getEffectiveSizeC()) {
String id = MetadataTools.createLSID("LightSource", i, laser);
store.setChannelLightSourceSettingsID(id, i, nextChannel);
store.setChannelLightSourceSettingsAttenuation(new PercentFraction((float) intensity / 100f), i, nextChannel);
Length ex = FormatTools.getExcitationWavelength(wavelength);
if (ex != null) {
store.setChannelExcitationWavelength(ex, i, nextChannel);
}
if (wavelength > 0) {
if (cutIns[index] == null || nextFilter >= cutIns[index].size()) {
continue;
}
Double cutIn = ((Length) cutIns[index].get(nextFilter)).value(UNITS.NANOMETER).doubleValue();
while (cutIn - wavelength > 20) {
nextFilter++;
if (nextFilter < cutIns[index].size()) {
cutIn = ((Length) cutIns[index].get(nextFilter)).value(UNITS.NANOMETER).doubleValue();
} else {
break;
}
}
if (nextFilter < cutIns[index].size()) {
String fid = MetadataTools.createLSID("Filter", i, nextFilter);
// store.setLightPathEmissionFilterRef(fid, i, nextChannel, 0);
nextFilter++;
}
}
}
}
}
}
store.setImageInstrumentRef(instrumentID, i);
store.setObjectiveSettingsID(objectiveID, i);
store.setObjectiveSettingsRefractiveIndex(refractiveIndex[index], i);
store.setImageDescription(descriptions[index], i);
if (acquiredDate[index] > 0) {
store.setImageAcquisitionDate(new Timestamp(DateTools.convertDate((long) (acquiredDate[index] * 1000), DateTools.COBOL, DateTools.ISO8601_FORMAT, false)), i);
}
store.setImageName(imageNames[index].trim(), i);
Length sizeX = FormatTools.getPhysicalSizeX(physicalSizeXs.get(index));
Length sizeY = FormatTools.getPhysicalSizeY(physicalSizeYs.get(index));
Length sizeZ = FormatTools.getPhysicalSizeZ(zSteps[index]);
if (sizeX != null) {
store.setPixelsPhysicalSizeX(sizeX, i);
}
if (sizeY != null) {
store.setPixelsPhysicalSizeY(sizeY, i);
}
if (sizeZ != null) {
store.setPixelsPhysicalSizeZ(sizeZ, i);
}
if (tSteps[index] != null) {
store.setPixelsTimeIncrement(new Time(tSteps[index], UNITS.SECOND), i);
}
final List<String> detectors = detectorModels[index];
if (detectors != null) {
nextChannel = 0;
int start = detectors.size() - getEffectiveSizeC();
if (start < 0) {
start = 0;
}
for (int detector = start; detector < detectors.size(); detector++) {
int dIndex = detector - start;
String detectorID = MetadataTools.createLSID("Detector", i, dIndex);
store.setDetectorID(detectorID, i, dIndex);
store.setDetectorModel((String) detectors.get(detector), i, dIndex);
store.setDetectorZoom(zooms[index], i, dIndex);
store.setDetectorType(DetectorType.PMT, i, dIndex);
if (activeDetector[index] != null) {
int detectorIndex = activeDetector[index].size() - getEffectiveSizeC() + dIndex;
if (detectorIndex >= 0 && detectorIndex < activeDetector[index].size() && (Boolean) activeDetector[index].get(detectorIndex) && detectorOffsets[index] != null && nextChannel < detectorOffsets[index].length) {
store.setDetectorOffset(detectorOffsets[index][nextChannel++], i, dIndex);
}
}
}
}
final List<Boolean> activeDetectors = activeDetector[index];
int firstDetector = activeDetectors == null ? 0 : activeDetectors.size() - getEffectiveSizeC();
int nextDetector = firstDetector;
int nextFilter = 0;
int nextFilterDetector = 0;
if (activeDetectors != null && activeDetectors.size() > cutIns[index].size() && (Boolean) activeDetectors.get(activeDetectors.size() - 1) && (Boolean) activeDetectors.get(activeDetectors.size() - 2)) {
nextFilterDetector = activeDetectors.size() - cutIns[index].size();
if (cutIns[index].size() > filterModels[index].size()) {
nextFilterDetector += filterModels[index].size();
nextFilter += filterModels[index].size();
}
}
for (int c = 0; c < getEffectiveSizeC(); c++) {
if (activeDetectors != null) {
while (nextDetector >= 0 && nextDetector < activeDetectors.size() && !(Boolean) activeDetectors.get(nextDetector)) {
nextDetector++;
}
if (nextDetector < activeDetectors.size() && detectors != null && nextDetector - firstDetector < detectors.size()) {
String detectorID = MetadataTools.createLSID("Detector", i, nextDetector - firstDetector);
store.setDetectorSettingsID(detectorID, i, c);
nextDetector++;
if (detectorOffsets[index] != null && c < detectorOffsets[index].length) {
store.setDetectorSettingsOffset(detectorOffsets[index][c], i, c);
}
if (gains[index] != null) {
store.setDetectorSettingsGain(gains[index][c], i, c);
}
}
}
if (channelNames[index] != null) {
store.setChannelName(channelNames[index][c], i, c);
}
if (pinholes[index] != null) {
store.setChannelPinholeSize(new Length(pinholes[index], UNITS.MICROMETER), i, c);
}
if (exWaves[index] != null) {
if (exWaves[index][c] != null && exWaves[index][c] > 1) {
Length ex = FormatTools.getExcitationWavelength(exWaves[index][c]);
if (ex != null) {
store.setChannelExcitationWavelength(ex, i, c);
}
}
}
// channel coloring is implicit if the image is stored as RGB
Color channelColor = getChannelColor(realChannel[index][c]);
if (!isRGB()) {
store.setChannelColor(channelColor, i, c);
}
if (channelColor.getValue() != -1 && nextFilter >= 0) {
if (nextDetector - firstDetector != getSizeC() && cutIns[index] != null && nextDetector >= cutIns[index].size()) {
while (nextFilterDetector < firstDetector) {
String filterID = MetadataTools.createLSID("Filter", i, nextFilter);
store.setFilterID(filterID, i, nextFilter);
nextFilterDetector++;
nextFilter++;
}
}
while (activeDetectors != null && nextFilterDetector < activeDetectors.size() && !(Boolean) activeDetectors.get(nextFilterDetector)) {
String filterID = MetadataTools.createLSID("Filter", i, nextFilter);
store.setFilterID(filterID, i, nextFilter);
nextFilterDetector++;
nextFilter++;
}
String filterID = MetadataTools.createLSID("Filter", i, nextFilter);
store.setFilterID(filterID, i, nextFilter);
store.setLightPathEmissionFilterRef(filterID, i, c, 0);
nextFilterDetector++;
nextFilter++;
}
}
for (int image = 0; image < getImageCount(); image++) {
Length xPos = posX[index];
Length yPos = posY[index];
if (i < fieldPosX.size() && fieldPosX.get(i) != null) {
xPos = fieldPosX.get(i);
}
if (i < fieldPosY.size() && fieldPosY.get(i) != null) {
yPos = fieldPosY.get(i);
}
if (xPos != null) {
store.setPlanePositionX(xPos, i, image);
}
if (yPos != null) {
store.setPlanePositionY(yPos, i, image);
}
store.setPlanePositionZ(posZ[index], i, image);
if (timestamps[index] != null) {
if (timestamps[index][image] != null) {
double timestamp = timestamps[index][image];
if (timestamps[index][0] == acquiredDate[index]) {
timestamp -= acquiredDate[index];
} else if (timestamp == acquiredDate[index] && image > 0) {
timestamp = timestamps[index][0];
}
store.setPlaneDeltaT(new Time(timestamp, UNITS.SECOND), i, image);
}
}
if (expTimes[index] != null) {
int c = getZCTCoords(image)[1];
if (expTimes[index][c] != null) {
store.setPlaneExposureTime(new Time(expTimes[index][c], UNITS.SECOND), i, image);
}
}
}
if (imageROIs[index] != null) {
for (int roi = 0; roi < imageROIs[index].length; roi++) {
if (imageROIs[index][roi] != null) {
imageROIs[index][roi].storeROI(store, i, roiCount++, roi);
}
}
}
}
}
use of loci.common.services.ServiceException in project bioformats by openmicroscopy.
the class ImarisHDFReader method getImageData.
// -- Helper methods --
/**
* Retrieve an array corresponding to the specified image tile.
* In some cases, the returned tile will be larger than the requested tile;
* openBytes will correct for this as needed.
*/
private Object getImageData(int no, int x, int y, int width, int height) throws FormatException {
int[] zct = getZCTCoords(no);
String path = "/DataSet/ResolutionLevel_" + getCoreIndex() + "/TimePoint_" + zct[2] + "/Channel_" + zct[1] + "/Data";
Object image = null;
// singleton instead of an array
if (height == 1) {
height++;
// so that we don't attempt to read past the end of the image
if (y == getSizeY() - 1) {
y--;
}
}
if (width == 1) {
width++;
// so that we don't attempt to read past the end of the image
if (x == getSizeX() - 1) {
x--;
}
}
// moving the X coordinate to the left and adjusting the width.
if (x >= getSizeX() / 2 && y >= getSizeY() / 2) {
width += x - (getSizeX() / 2) + 1;
x = (getSizeX() / 2) - 1;
}
int[] dimensions = new int[] { 1, height, width };
int[] indices = new int[] { zct[0], y, x };
try {
image = netcdf.getArray(path, indices, dimensions);
} catch (ServiceException e) {
throw new FormatException(e);
}
return image;
}
use of loci.common.services.ServiceException in project bioformats by openmicroscopy.
the class TiledExportExample method main.
public static void main(String[] args) throws Exception {
if (args.length < 2) {
System.out.println("Usage: java TiledExportExample <infile> <outfile>");
System.exit(1);
}
ImageReader reader = new ImageReader();
ImageWriter writer = new ImageWriter();
IMetadata meta;
try {
ServiceFactory factory = new ServiceFactory();
OMEXMLService service = factory.getInstance(OMEXMLService.class);
meta = 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);
}
reader.setMetadataStore(meta);
reader.setId(args[0]);
writer.setMetadataRetrieve(meta);
writer.setId(args[1]);
for (int series = 0; series < reader.getSeriesCount(); series++) {
reader.setSeries(series);
writer.setSeries(series);
for (int image = 0; image < reader.getImageCount(); image++) {
for (int row = 0; row < 2; row++) {
for (int col = 0; col < 2; col++) {
int w = reader.getSizeX() / 2;
int h = reader.getSizeY() / 2;
int x = col * w;
int y = row * h;
/* debug */
System.out.println("[" + x + ", " + y + ", " + w + ", " + h + "]");
byte[] buf = reader.openBytes(image, x, y, w, h);
writer.saveBytes(image, buf, x, y, w, h);
}
}
}
}
reader.close();
writer.close();
}
use of loci.common.services.ServiceException in project digilib by robcast.
the class BioFormatsDocuImage method loadImage.
@Override
public void loadImage(ImageInput ii) throws FileOpException {
logger.debug("loadImage: " + ii);
this.input = ii;
reader = new ImageReader();
try {
// construct the object that stores OME-XML metadata
ServiceFactory factory = new ServiceFactory();
OMEXMLService service = factory.getInstance(OMEXMLService.class);
meta = service.createOMEXMLMetadata();
// set up the reader and associate it with the input file
reader = new ImageReader();
reader.setMetadataStore(meta);
reader.setId(ii.getFile().getAbsolutePath());
BufferedImageReader biReader = BufferedImageReader.makeBufferedImageReader(reader);
img = biReader.openImage(0);
logger.debug("image loaded: " + img);
} catch (FormatException e) {
throw new FileOpException("Unable to load image format: " + e);
} catch (IOException e) {
throw new FileOpException("Unable to load image file: " + e);
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (DependencyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Aggregations