use of loci.formats.FilePattern in project bioformats by openmicroscopy.
the class FilePatternTest method testRegex.
@Test(dataProvider = "booleanStates")
public void testRegex(Boolean createFiles) throws IOException {
String[] names = { "z0.tif", "z1.tif" };
Path wd = Files.createTempDirectory("");
wd.toFile().deleteOnExit();
String pattern = resolveToString(wd, "z.*.tif");
FilePattern fp = new FilePattern(pattern);
assertTrue(fp.isValid());
assertTrue(fp.isRegex());
assertEquals(fp.getPattern(), pattern);
if (!createFiles) {
// pattern matches a single (nonexistent) file with name == pattern
assertEquals(fp.getFiles(), new String[] { pattern });
return;
}
String[] fullNames = mkFiles(wd, names);
assertEqualsNoOrder(new FilePattern(pattern).getFiles(), fullNames);
}
use of loci.formats.FilePattern in project bioformats by openmicroscopy.
the class Mass_Importer method run.
public void run(String arg) {
// prompt user for directory to process
DirectoryChooser dc = new DirectoryChooser("Bio-Formats Mass Importer");
String dirPath = dc.getDirectory();
// create a list of files we have already processed
HashSet<String> done = new HashSet<String>();
// list of files to actually open with Bio-Formats Importer
ArrayList<String> filesToOpen = new ArrayList<String>();
// process all files in the chosen directory
File dir = new File(dirPath);
File[] files = dir.listFiles();
IJ.showStatus("Scanning directory");
// image reader object, for testing whether a file is in a supported format
try (ImageReader tester = new ImageReader()) {
for (int i = 0; i < files.length; i++) {
String id = files[i].getAbsolutePath();
IJ.showProgress((double) i / files.length);
// skip files that have already been processed
if (done.contains(id))
continue;
// skip unsupported files
if (!tester.isThisType(id, false))
continue;
// use FilePattern to group files with similar names
String name = files[i].getName();
FilePattern fp = new FilePattern(name, dirPath);
// get a list of all files part of this group, and mark them as done
String[] used = fp.getFiles();
for (int j = 0; j < used.length; j++) done.add(used[j]);
filesToOpen.add(id);
}
} catch (IOException e) {
IJ.error("Sorry, an error while closing ImageReader: " + e.getMessage());
}
IJ.showProgress(1.0);
IJ.showStatus("");
// confirm that user wants to proceed in opening the file groups
int numToOpen = filesToOpen.size();
if (numToOpen == 0) {
IJ.showMessage("No file groups found.");
return;
}
String groups = numToOpen == 1 ? "1 file group" : (numToOpen + " file groups");
YesNoCancelDialog confirm = new YesNoCancelDialog(IJ.getInstance(), "Bio-Formats Mass Importer", "Found " + groups + " in directory '" + dirPath + "'; proceed?");
if (!confirm.yesPressed())
return;
// launch the Bio-Formats Importer plugin to open each group of files
for (int i = 0; i < numToOpen; i++) {
String id = (String) filesToOpen.get(i);
String params = "location=[Local machine] " + "windowless=true " + "groupFiles=true " + "id=[" + id + "] ";
new LociImporter().run(params);
}
IJ.showStatus("");
}
use of loci.formats.FilePattern in project bioformats by openmicroscopy.
the class DicomReader method scanDirectory.
// -- Utility methods --
/**
* Scan the given directory for files that belong to this dataset.
*/
private void scanDirectory(Location dir, boolean checkSeries) throws FormatException, IOException {
Location currentFile = new Location(currentId).getAbsoluteFile();
FilePattern pattern = new FilePattern(currentFile.getName(), dir.getAbsolutePath());
String[] patternFiles = pattern.getFiles();
if (patternFiles == null)
patternFiles = new String[0];
Arrays.sort(patternFiles);
// path separator normalization is inconsistent
for (int i = 0; i < patternFiles.length; i++) {
patternFiles[i] = new Location(patternFiles[i]).getAbsolutePath();
}
String[] files = dir.list(true);
if (files == null)
return;
Arrays.sort(files);
for (String f : files) {
String file = new Location(dir, f).getAbsolutePath();
LOGGER.debug("Checking file {}", file);
if (!f.equals(currentId) && !file.equals(currentId) && isThisType(file) && Arrays.binarySearch(patternFiles, file) >= 0) {
addFileToList(file, checkSeries);
}
}
}
use of loci.formats.FilePattern in project bioformats by openmicroscopy.
the class AxisGuesserTest method check.
private void check(// IN
String p, // IN
String order, // IN
int sZ, // IN
int sT, // IN
int sC, // IN
boolean cert, String newOrder, int[] types) {
// OUT
FilePattern fp = new FilePattern(p);
AxisGuesser ag = new AxisGuesser(fp, order, sZ, sT, sC, cert);
assertEquals(ag.getFilePattern().getPattern(), p);
assertEquals(ag.getOriginalOrder(), order);
assertEquals(ag.getAdjustedOrder(), newOrder);
assertEquals(ag.getAxisTypes(), types);
checkAxisCount(ag, types);
}
use of loci.formats.FilePattern in project bioformats by openmicroscopy.
the class DataConverter method run.
// -- Runnable methods --
@Override
public void run() {
convert.setEnabled(false);
includeZ.setEnabled(false);
includeT.setEnabled(false);
includeC.setEnabled(false);
zChoice.setEnabled(false);
tChoice.setEnabled(false);
cChoice.setEnabled(false);
input.setEditable(false);
fps.setEnabled(false);
if (series != null)
series.setEnabled(false);
forceType.setEnabled(false);
codec.setEnabled(false);
progress.setString("Getting ready");
try {
String in = input.getText();
String out = output.getText();
if (in.trim().equals("")) {
msg("Please specify input files.");
convert.setEnabled(true);
progress.setString("");
return;
}
if (out.trim().equals("")) {
File f = new File(in);
String name = new FilePattern(in).getPrefix();
String stitchDir = name + "-stitched";
new File(f.getParent() + File.separator + stitchDir).mkdir();
out = f.getParent() + File.separator + stitchDir + File.separator + name + ".tif";
out = out.replaceAll(File.separator + File.separator, File.separator);
output.setText(out);
}
output.setEditable(false);
swap.setId(in);
if (series != null) {
swap.setSeries(((Integer) series.getValue()).intValue() - 1);
}
writer.setFramesPerSecond(((Integer) fps.getValue()).intValue());
try {
writer.getWriter(out).setCompression((String) codec.getSelectedItem());
} catch (NullPointerException npe) {
}
// boolean isQT = swap.getFormat().equals("QuickTime");
// boolean useQTJ = isQT && qtJava.isSelected();
// ((QTReader) reader.getReader(QTReader.class)).setLegacy(useQTJ);
// swap dimensions based on user input
String order = swap.getDimensionOrder();
if (zLabel.getText().indexOf("Time") != -1) {
order = order.replace('Z', 'T');
} else if (zLabel.getText().indexOf("Channel") != -1) {
order = order.replace('Z', 'C');
}
if (tLabel.getText().indexOf("Slice") != -1) {
order = order.replace('T', 'Z');
} else if (tLabel.getText().indexOf("Channel") != -1) {
order = order.replace('T', 'C');
}
if (cLabel.getText().indexOf("Time") != -1) {
order = order.replace('C', 'T');
} else if (cLabel.getText().indexOf("Slice") != -1) {
order = order.replace('C', 'Z');
}
swap.swapDimensions(order);
// determine internal and external dimensions for each axis
int internalZ = includeZ.isSelected() ? swap.getSizeZ() : 1;
int internalT = includeT.isSelected() ? swap.getSizeT() : 1;
int internalC = includeC.isSelected() ? swap.getEffectiveSizeC() : 1;
int externalZ = includeZ.isSelected() ? 1 : swap.getSizeZ();
int externalT = includeT.isSelected() ? 1 : swap.getSizeT();
int externalC = includeC.isSelected() ? 1 : swap.getEffectiveSizeC();
int zDigits = ("" + externalZ).length();
int tDigits = ("" + externalT).length();
int cDigits = ("" + externalC).length();
progress.setMaximum(2 * swap.getImageCount());
int star = out.lastIndexOf(".");
if (star < 0)
star = out.length();
String pre = out.substring(0, star);
String post = out.substring(star);
// determine appropriate pixel type
int type = swap.getPixelType();
writer.setId(out);
if (force && !writer.isSupportedType(type)) {
int[] types = writer.getPixelTypes();
for (int i = 0; i < types.length; i++) {
if (types[i] > type) {
if (i == 0) {
type = types[i];
break;
} else {
type = types[i - 1];
break;
}
}
if (i == types.length - 1)
type = types[i];
}
} else if (!force && !writer.isSupportedType(type)) {
throw new FormatException("Unsupported pixel type: " + FormatTools.getPixelTypeString(type) + "\nTo write to this format, the \"force\" box must be checked.\n" + "This may result in a loss of precision; for best results, " + "convert to TIFF instead.");
}
long start = System.currentTimeMillis();
int plane = 0;
for (int i = 0; i < externalZ; i++) {
for (int j = 0; j < externalT; j++) {
for (int k = 0; k < externalC; k++) {
// construct the numeric blocks
String zBlock = "";
String tBlock = "";
String cBlock = "";
if (externalZ > 1) {
String num = "" + i;
while (num.length() < zDigits) num = "0" + num;
zBlock = "Z" + num + "_";
}
if (externalT > 1) {
String num = "" + j;
while (num.length() < tDigits) num = "0" + num;
tBlock = "T" + num + "_";
}
if (externalC > 1) {
String num = "" + k;
while (num.length() < cDigits) num = "0" + num;
cBlock = "C" + num;
}
String outFile = pre;
if (zBlock.length() > 1)
outFile += zBlock;
if (tBlock.length() > 1)
outFile += tBlock;
if (cBlock.length() > 1)
outFile += cBlock;
if (outFile.endsWith("_")) {
outFile = outFile.substring(0, outFile.length() - 1);
}
outFile += post;
String outName = new File(outFile).getName();
int planesPerFile = internalZ * internalT * internalC;
int filePlane = 0;
for (int z = 0; z < internalZ; z++) {
for (int t = 0; t < internalT; t++) {
for (int c = 0; c < internalC; c++) {
int zPos = z * externalZ + i;
int tPos = t * externalT + j;
int cPos = c * externalC + k;
progress.setString(outName + " " + (filePlane + 1) + "/" + planesPerFile);
filePlane++;
progress.setValue(2 * (plane + 1));
plane++;
int ndx = swap.getIndex(zPos, cPos, tPos);
BufferedImage img = biReader.openImage(ndx);
writer.setId(out);
if (force && !writer.isSupportedType(swap.getPixelType())) {
int pixelType = 0;
switch(type) {
case FormatTools.INT8:
case FormatTools.UINT8:
pixelType = DataBuffer.TYPE_BYTE;
break;
case FormatTools.INT16:
pixelType = DataBuffer.TYPE_USHORT;
break;
case FormatTools.UINT16:
pixelType = DataBuffer.TYPE_SHORT;
break;
case FormatTools.INT32:
case FormatTools.UINT32:
pixelType = DataBuffer.TYPE_INT;
break;
case FormatTools.FLOAT:
pixelType = DataBuffer.TYPE_FLOAT;
break;
case FormatTools.DOUBLE:
pixelType = DataBuffer.TYPE_DOUBLE;
break;
}
// TODO - come up with another way to do this...
// img = ImageTools.makeType(img, pixelType);
}
writer.setId(outFile);
biWriter.savePlane(filePlane, img);
if (shutdown)
break;
}
}
}
}
}
}
progress.setValue(2 * swap.getImageCount());
progress.setString("Finishing");
if (writer != null)
writer.close();
long end = System.currentTimeMillis();
double time = (end - start) / 1000.0;
long avg = (end - start) / (swap.getImageCount());
progress.setString(time + " s elapsed (" + avg + " ms/plane)");
progress.setValue(0);
if (swap != null)
swap.close();
} catch (FormatException exc) {
LOGGER.info("", exc);
String err = exc.getMessage();
if (err == null)
err = exc.getClass().getName();
msg("Sorry, an error occurred: " + err);
progress.setString("");
progress.setValue(0);
} catch (IOException exc) {
LOGGER.info("", exc);
String err = exc.getMessage();
if (err == null)
err = exc.getClass().getName();
msg("Sorry, an error occurred: " + err);
progress.setString("");
progress.setValue(0);
}
convert.setEnabled(true);
includeZ.setEnabled(true);
includeT.setEnabled(true);
includeC.setEnabled(true);
zChoice.setEnabled(true);
tChoice.setEnabled(true);
cChoice.setEnabled(true);
input.setEditable(true);
output.setEditable(true);
fps.setEnabled(true);
if (series != null)
series.setEnabled(true);
forceType.setEnabled(true);
codec.setEnabled(true);
}
Aggregations