use of loci.formats.meta.MetadataRetrieve in project bioformats by openmicroscopy.
the class ImagePlusReader method constructSliceLabel.
private String constructSliceLabel(int ndx, IFormatReader r, IMetadata meta, int series, int zCount, int cCount, int tCount) {
r.setSeries(series);
String sliceLabelPattern = LociPrefs.getSliceLabelPattern();
String order = r.getDimensionOrder();
int sizeC = r.getEffectiveSizeC();
int sizeT = r.getSizeT();
int sizeZ = r.getSizeZ();
int seriesCount = r.getImageCount();
int indexBase = LociPrefs.getSliceLabelBaseIndex();
int[] coordinates = FormatTools.getZCTCoords(order, sizeZ, sizeC, sizeT, sizeZ * sizeC * sizeT, ndx);
MetadataStore store = r.getMetadataStore();
MetadataRetrieve retrieve = store instanceof MetadataRetrieve ? (MetadataRetrieve) store : new DummyMetadata();
String filename = sliceLabelPattern.replaceAll(FormatTools.SERIES_NUM, String.format("%d", series));
String imageName = retrieve.getImageName(series);
if (imageName == null)
imageName = "Series" + series;
filename = sliceLabelPattern;
filename = filename.replaceAll(FormatTools.SERIES_NUM, String.format("%d", series));
filename = filename.replaceAll(FormatTools.SERIES_NAME, imageName);
if (sizeC > 1) {
int[] subC;
String[] subCTypes;
Modulo moduloC = r.getModuloC();
if (moduloC.length() > 1) {
subC = new int[] { r.getSizeC() / moduloC.length(), moduloC.length() };
subCTypes = new String[] { moduloC.parentType, moduloC.type };
} else {
subC = new int[] { r.getSizeC() };
subCTypes = new String[] { FormatTools.CHANNEL };
}
int[] subCPos = FormatTools.rasterToPosition(subC, coordinates[1]);
StringBuffer channelString = new StringBuffer();
for (int i = 0; i < subC.length; i++) {
boolean ch = subCTypes[i] == null || FormatTools.CHANNEL.equals(subCTypes[i]);
channelString.append(ch ? "c" : subCTypes[i]);
channelString.append(":");
channelString.append(subCPos[i] + 1);
channelString.append("/");
channelString.append(subC[i]);
if (i < subC.length - 1)
channelString.append(", ");
}
filename = filename.replaceAll(FormatTools.CHANNEL_NUM, channelString.toString() + " ");
int channelCount = retrieve.getChannelCount(series);
if (coordinates[1] < channelCount) {
String channelName = retrieve.getChannelName(series, coordinates[1]);
if (channelName == null)
channelName = String.valueOf(coordinates[1]);
filename = filename.replaceAll(FormatTools.CHANNEL_NAME, channelName);
} else {
filename = filename.replaceAll(FormatTools.CHANNEL_NAME, String.valueOf(coordinates[1]));
}
} else {
filename = filename.replaceAll(FormatTools.CHANNEL_NUM, "");
filename = filename.replaceAll(FormatTools.CHANNEL_NAME, "");
}
if (sizeZ > 1) {
filename = filename.replaceAll(FormatTools.Z_NUM, "z:" + String.format("%d", coordinates[0] + 1) + "/" + String.format("%d", sizeZ) + " ");
} else {
filename = filename.replaceAll(FormatTools.Z_NUM, "");
}
if (sizeT > 1) {
filename = filename.replaceAll(FormatTools.T_NUM, "t:" + String.format("%d", coordinates[2] + 1) + "/" + String.format("%d", sizeT) + " ");
} else {
filename = filename.replaceAll(FormatTools.T_NUM, "");
}
Timestamp timestamp = retrieve.getImageAcquisitionDate(series);
long stamp = 0;
String date = null;
if (timestamp != null) {
date = timestamp.getValue();
if (retrieve.getPlaneCount(series) > ndx) {
Time deltaT = retrieve.getPlaneDeltaT(series, ndx);
if (deltaT != null) {
stamp = (long) (deltaT.value(UNITS.SECOND).doubleValue() * 1000);
}
}
stamp += DateTools.getTime(date, DateTools.ISO8601_FORMAT);
} else {
stamp = System.currentTimeMillis();
}
date = DateTools.convertDate(stamp, (int) DateTools.UNIX_EPOCH);
filename = filename.replaceAll(FormatTools.TIMESTAMP, date);
return filename;
}
use of loci.formats.meta.MetadataRetrieve in project bioformats by openmicroscopy.
the class ChannelSeparator method setId.
/* @see IFormatHandler#setId(String) */
@Override
public void setId(String id) throws FormatException, IOException {
super.setId(id);
// clear last image cache
lastImage = null;
lastImageIndex = -1;
lastImageSeries = -1;
lastImageX = -1;
lastImageY = -1;
lastImageWidth = -1;
lastImageHeight = -1;
MetadataStore store = getMetadataStore();
boolean pixelsPopulated = false;
if (store instanceof MetadataRetrieve) {
MetadataRetrieve retrieve = (MetadataRetrieve) store;
for (int s = 0; s < getSeriesCount(); s++) {
setSeries(s);
int rgbChannels = getSizeC() / reader.getEffectiveSizeC();
if (rgbChannels == 1) {
continue;
}
for (int c = 0; c < reader.getEffectiveSizeC(); c++) {
if (c * rgbChannels >= retrieve.getChannelCount(s)) {
break;
}
String originalChannelName = retrieve.getChannelName(s, c * rgbChannels);
if (originalChannelName == null) {
continue;
}
if (!pixelsPopulated) {
MetadataTools.populatePixelsOnly(store, this);
pixelsPopulated = true;
}
for (int i = 1; i < rgbChannels; i++) {
store.setChannelName(originalChannelName, s, c * rgbChannels + i);
}
}
}
setSeries(0);
}
}
use of loci.formats.meta.MetadataRetrieve in project bioformats by openmicroscopy.
the class BufferedImageWriter method toBytes.
// -- Utility methods --
public static byte[] toBytes(BufferedImage image, IFormatWriter writer) {
boolean littleEndian = false;
int bpp = FormatTools.getBytesPerPixel(AWTImageTools.getPixelType(image));
MetadataRetrieve r = writer.getMetadataRetrieve();
if (r != null) {
Boolean bigEndian = false;
if (r.getPixelsBigEndian(writer.getSeries()) != null) {
bigEndian = r.getPixelsBigEndian(writer.getSeries()).booleanValue();
} else if (r.getPixelsBinDataCount(writer.getSeries()) == 0) {
bigEndian = r.getPixelsBinDataBigEndian(writer.getSeries(), 0).booleanValue();
}
if (bigEndian != null)
littleEndian = !bigEndian.booleanValue();
}
byte[][] pixelBytes = AWTImageTools.getPixelBytes(image, littleEndian);
byte[] buf = new byte[pixelBytes.length * pixelBytes[0].length];
if (writer.isInterleaved()) {
for (int i = 0; i < pixelBytes[0].length; i += bpp) {
for (int j = 0; j < pixelBytes.length; j++) {
System.arraycopy(pixelBytes[j], i, buf, i * pixelBytes.length + j * bpp, bpp);
}
}
} else {
for (int i = 0; i < pixelBytes.length; i++) {
System.arraycopy(pixelBytes[i], 0, buf, i * pixelBytes[0].length, pixelBytes[i].length);
}
}
pixelBytes = null;
return buf;
}
use of loci.formats.meta.MetadataRetrieve in project bioformats by openmicroscopy.
the class CellH5Writer method saveBytes.
/**
* Saves the given image to the specified (possibly already open) file.
*/
@Override
public void saveBytes(int no, byte[] buf) throws IOException, FormatException {
LOGGER.info("CellH5Writer: Save image to HDF5 path: " + outputPath);
MetadataRetrieve r = getMetadataRetrieve();
int sizeX = r.getPixelsSizeX(series).getValue();
int sizeY = r.getPixelsSizeY(series).getValue();
int sizeC = r.getPixelsSizeC(series).getValue();
int sizeT = r.getPixelsSizeT(series).getValue();
int sizeZ = r.getPixelsSizeZ(series).getValue();
DimensionOrder dimo = r.getPixelsDimensionOrder(0);
int c, z, t;
if (dimo.equals(DimensionOrder.XYCZT)) {
c = no % sizeC;
z = ((no - c) / sizeC) % sizeZ;
t = (((no - c) / sizeC)) / sizeZ;
} else if (dimo.equals(DimensionOrder.XYCTZ)) {
c = no % sizeC;
t = ((no - c) / sizeC) % sizeT;
z = (((no - c) / sizeC)) / sizeT;
} else if (dimo.equals(DimensionOrder.XYZTC)) {
z = no % sizeZ;
t = ((no - z) / sizeZ) % sizeT;
c = (((no - z) / sizeZ)) / sizeT;
} else {
throw new FormatException("CellH5Writer: Dimension order not understood: " + dimo.getValue());
}
LOGGER.info("CellH5Writer.saveBytes(): Current c, t, z == {} {} {}", c, t, z);
LOGGER.info("CellH5Writer.saveBytes(): bpp {} byte buffer len {}", bpp, buf.length);
if (bpp == 1) {
MDByteArray image = new MDByteArray(new int[] { 1, 1, 1, sizeY, sizeX });
for (int x_i = 0; x_i < sizeX; x_i++) {
for (int y_i = 0; y_i < sizeY; y_i++) {
byte value = (byte) buf[y_i * sizeX + x_i];
image.set(value, 0, 0, 0, y_i, x_i);
}
}
jhdf.writeArraySlice(outputPath, image, new long[] { c, t, z, 0, 0 });
} else if (bpp == 2) {
ByteBuffer bb = ByteBuffer.wrap(buf);
ShortBuffer sb = bb.asShortBuffer();
MDShortArray image = new MDShortArray(new int[] { 1, 1, 1, sizeY, sizeX });
for (int x_i = 0; x_i < sizeX; x_i++) {
for (int y_i = 0; y_i < sizeY; y_i++) {
short value = sb.get(y_i * sizeX + x_i);
image.set(value, 0, 0, 0, y_i, x_i);
}
}
jhdf.writeArraySlice(outputPath, image, new long[] { c, t, z, 0, 0 });
} else if (bpp == 4) {
ByteBuffer bb = ByteBuffer.wrap(buf);
IntBuffer ib = bb.asIntBuffer();
MDIntArray image = new MDIntArray(new int[] { 1, 1, 1, sizeY, sizeX });
for (int x_i = 0; x_i < sizeX; x_i++) {
for (int y_i = 0; y_i < sizeY; y_i++) {
int value = (int) ib.get(y_i * sizeX + x_i);
image.set(value, 0, 0, 0, y_i, x_i);
}
}
jhdf.writeArraySlice(outputPath, image, new long[] { c, t, z, 0, 0 });
} else {
throw new FormatException("CellH5Writer: Pixel type not supported");
}
}
use of loci.formats.meta.MetadataRetrieve 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;
}
Aggregations