use of ij.ImagePlus in project GDSC-SMLM by aherbert.
the class FolderOpenerDialog method filterImageList.
private void filterImageList() {
String[] list = imageList;
ImagePlus imp = nextImage();
// Reset image list
currentImage = 0;
imageList = new String[0];
if (imp != null && showDialog(imp, list)) {
// Filter by name
if (filter != null && (filter.equals("") || filter.equals("*")))
filter = null;
if (filter != null) {
int filteredImages = 0;
for (int i = 0; i < list.length; i++) {
if (isRegex && list[i].matches(filter))
filteredImages++;
else if (list[i].indexOf(filter) >= 0)
filteredImages++;
else
list[i] = null;
}
if (filteredImages == 0) {
if (isRegex)
IJ.error("Import Sequence", "None of the file names match the regular expression.");
else
IJ.error("Import Sequence", "None of the " + list.length + " files contain\n the string '" + filter + "' in their name.");
return;
}
String[] list2 = new String[filteredImages];
int j = 0;
for (int i = 0; i < list.length; i++) {
if (list[i] != null)
list2[j++] = list[i];
}
list = list2;
}
// Process only the requested number of images
if (n < 1)
n = list.length;
if (start < 1 || start > list.length)
start = 1;
imageList = new String[list.length];
int count = 0;
for (int i = start - 1; i < list.length && count < n; i += increment, count++) {
imageList[count] = list[i];
}
imageList = Arrays.copyOf(imageList, count);
}
}
use of ij.ImagePlus in project GDSC-SMLM by aherbert.
the class FIRE method showQEstimationInputDialog.
private boolean showQEstimationInputDialog() {
ExtendedGenericDialog gd = new ExtendedGenericDialog(TITLE);
gd.addHelp(About.HELP_URL);
// Build a list of all images with a region ROI
List<String> titles = new LinkedList<String>();
if (WindowManager.getWindowCount() > 0) {
for (int imageID : WindowManager.getIDList()) {
ImagePlus imp = WindowManager.getImage(imageID);
if (imp != null && imp.getRoi() != null && imp.getRoi().isArea())
titles.add(imp.getTitle());
}
}
gd.addMessage("Estimate the blinking correction parameter Q for Fourier Ring Correlation");
ResultsManager.addInput(gd, inputOption, InputSource.MEMORY);
if (!titles.isEmpty())
gd.addCheckbox((titles.size() == 1) ? "Use_ROI" : "Choose_ROI", chooseRoi);
gd.addMessage("Image construction options:");
//gd.addCheckbox("Use_signal (if present)", useSignal);
gd.addChoice("Image_scale", SCALE_ITEMS, SCALE_ITEMS[imageScaleIndex]);
gd.addChoice("Auto_image_size", IMAGE_SIZE_ITEMS, IMAGE_SIZE_ITEMS[imageSizeIndex]);
gd.addNumericField("Block_size", blockSize, 0);
gd.addCheckbox("Random_split", randomSplit);
gd.addNumericField("Max_per_bin", maxPerBin, 0);
gd.addMessage("Fourier options:");
String[] fourierMethodNames = SettingsManager.getNames((Object[]) FRC.FourierMethod.values());
gd.addChoice("Fourier_method", fourierMethodNames, fourierMethodNames[fourierMethodIndex]);
String[] samplingMethodNames = SettingsManager.getNames((Object[]) FRC.SamplingMethod.values());
gd.addChoice("Sampling_method", samplingMethodNames, samplingMethodNames[samplingMethodIndex]);
gd.addSlider("Sampling_factor", 0.2, 4, perimeterSamplingFactor);
gd.addMessage("Estimation options:");
String[] thresholdMethodNames = SettingsManager.getNames((Object[]) FRC.ThresholdMethod.values());
gd.addChoice("Threshold_method", thresholdMethodNames, thresholdMethodNames[thresholdMethodIndex]);
String[] precisionMethodNames = SettingsManager.getNames((Object[]) PrecisionMethod.values());
gd.addChoice("Precision_method", precisionMethodNames, precisionMethodNames[precisionMethodIndex]);
gd.addNumericField("Precision_Mean", mean, 2, 6, "nm");
gd.addNumericField("Precision_Sigma", sigma, 2, 6, "nm");
gd.addCheckbox("Sample_decay", sampleDecay);
gd.addCheckbox("LOESS_smoothing", loessSmoothing);
gd.addCheckbox("Fit_precision", fitPrecision);
gd.addSlider("MinQ", 0, 0.4, minQ);
gd.addSlider("MaxQ", 0.1, 0.5, maxQ);
gd.showDialog();
if (gd.wasCanceled())
return false;
inputOption = ResultsManager.getInputSource(gd);
if (!titles.isEmpty())
chooseRoi = gd.getNextBoolean();
//useSignal = gd.getNextBoolean();
imageScaleIndex = gd.getNextChoiceIndex();
imageSizeIndex = gd.getNextChoiceIndex();
blockSize = Math.max(1, (int) gd.getNextNumber());
randomSplit = gd.getNextBoolean();
maxPerBin = Math.abs((int) gd.getNextNumber());
fourierMethodIndex = gd.getNextChoiceIndex();
fourierMethod = FourierMethod.values()[fourierMethodIndex];
samplingMethodIndex = gd.getNextChoiceIndex();
samplingMethod = SamplingMethod.values()[samplingMethodIndex];
perimeterSamplingFactor = gd.getNextNumber();
thresholdMethodIndex = gd.getNextChoiceIndex();
thresholdMethod = FRC.ThresholdMethod.values()[thresholdMethodIndex];
precisionMethodIndex = gd.getNextChoiceIndex();
precisionMethod = PrecisionMethod.values()[precisionMethodIndex];
mean = Math.abs(gd.getNextNumber());
sigma = Math.abs(gd.getNextNumber());
sampleDecay = gd.getNextBoolean();
loessSmoothing = gd.getNextBoolean();
fitPrecision = gd.getNextBoolean();
minQ = Maths.clip(0, 0.5, gd.getNextNumber());
maxQ = Maths.clip(0, 0.5, gd.getNextNumber());
// Check arguments
try {
Parameters.isAboveZero("Perimeter sampling factor", perimeterSamplingFactor);
if (precisionMethod == PrecisionMethod.FIXED) {
Parameters.isAboveZero("Precision Mean", mean);
Parameters.isAboveZero("Precision Sigma", sigma);
}
Parameters.isAbove("MaxQ", maxQ, minQ);
} catch (IllegalArgumentException e) {
IJ.error(TITLE, e.getMessage());
return false;
}
if (!titles.isEmpty() && chooseRoi) {
if (titles.size() == 1) {
roiImage = titles.get(0);
Recorder.recordOption("Image", roiImage);
} else {
String[] items = titles.toArray(new String[titles.size()]);
gd = new ExtendedGenericDialog(TITLE);
gd.addMessage("Select the source image for the ROI");
gd.addChoice("Image", items, roiImage);
gd.showDialog();
if (gd.wasCanceled())
return false;
roiImage = gd.getNextChoice();
}
ImagePlus imp = WindowManager.getImage(roiImage);
roiBounds = imp.getRoi().getBounds();
roiImageWidth = imp.getWidth();
roiImageHeight = imp.getHeight();
} else {
roiBounds = null;
}
return true;
}
use of ij.ImagePlus in project GDSC-SMLM by aherbert.
the class BenchmarkFilterAnalysis method showOverlay.
/**
* Show overlay.
*
* @param allAssignments
* The assignments generated from running the filter (or null)
* @param filter
* the filter
* @return The results from running the filter (or null)
*/
private PreprocessedPeakResult[] showOverlay(ArrayList<FractionalAssignment[]> allAssignments, DirectFilter filter) {
ImagePlus imp = CreateData.getImage();
if (imp == null)
return null;
// Run the filter manually to get the results that pass.
if (allAssignments == null)
allAssignments = getAssignments(filter);
final Overlay o = new Overlay();
// Do TP
final TIntHashSet actual = new TIntHashSet();
final TIntHashSet predicted = new TIntHashSet();
//int tp = 0, fp = 0, fn = 0;
for (FractionalAssignment[] assignments : allAssignments) {
if (assignments == null || assignments.length == 0)
continue;
float[] tx = null, ty = null;
int t = 0;
//tp += assignments.length;
if (showTP) {
tx = new float[assignments.length];
ty = new float[assignments.length];
}
int frame = 0;
for (int i = 0; i < assignments.length; i++) {
CustomFractionalAssignment c = (CustomFractionalAssignment) assignments[i];
IdPeakResult peak = (IdPeakResult) c.peak;
BasePreprocessedPeakResult spot = (BasePreprocessedPeakResult) c.peakResult;
actual.add(peak.uniqueId);
predicted.add(spot.getUniqueId());
frame = spot.getFrame();
if (showTP) {
tx[t] = spot.getX();
ty[t++] = spot.getY();
}
}
if (showTP)
SpotFinderPreview.addRoi(frame, o, tx, ty, t, Color.green);
}
float[] x = new float[10];
float[] y = new float[x.length];
float[] x2 = new float[10];
float[] y2 = new float[x2.length];
// Do FP (all remaining results that are not a TP)
PreprocessedPeakResult[] filterResults = null;
if (showFP) {
final MultiPathFilter multiPathFilter = createMPF(filter, minimalFilter);
//multiPathFilter.setDebugFile("/tmp/filter.txt");
filterResults = filterResults(multiPathFilter);
int frame = 0;
int c = 0;
int c2 = 0;
for (int i = 0; i < filterResults.length; i++) {
if (frame != filterResults[i].getFrame()) {
if (c != 0)
SpotFinderPreview.addRoi(frame, o, x, y, c, Color.red);
if (c2 != 0)
SpotFinderPreview.addRoi(frame, o, x2, y2, c2, Color.magenta);
c = c2 = 0;
}
frame = filterResults[i].getFrame();
if (predicted.contains(filterResults[i].getUniqueId()))
continue;
if (filterResults[i].ignore()) {
if (x2.length == c2) {
x2 = Arrays.copyOf(x2, c2 * 2);
y2 = Arrays.copyOf(y2, c2 * 2);
}
x2[c2] = filterResults[i].getX();
y2[c2++] = filterResults[i].getY();
} else {
if (x.length == c) {
x = Arrays.copyOf(x, c * 2);
y = Arrays.copyOf(y, c * 2);
}
x[c] = filterResults[i].getX();
y[c++] = filterResults[i].getY();
}
}
//fp += c;
if (c != 0)
SpotFinderPreview.addRoi(frame, o, x, y, c, Color.red);
if (c2 != 0)
SpotFinderPreview.addRoi(frame, o, x2, y2, c2, Color.magenta);
}
// Do TN (all remaining peaks that have not been matched)
if (showFN) {
final boolean checkBorder = (BenchmarkSpotFilter.lastAnalysisBorder != null && BenchmarkSpotFilter.lastAnalysisBorder.x != 0);
final float border, xlimit, ylimit;
if (checkBorder) {
final Rectangle lastAnalysisBorder = BenchmarkSpotFilter.lastAnalysisBorder;
border = lastAnalysisBorder.x;
xlimit = lastAnalysisBorder.x + lastAnalysisBorder.width;
ylimit = lastAnalysisBorder.y + lastAnalysisBorder.height;
} else
border = xlimit = ylimit = 0;
// Add the results to the lists
actualCoordinates.forEachEntry(new CustomTIntObjectProcedure(x, y, x2, y2) {
public boolean execute(int frame, IdPeakResult[] results) {
int c = 0, c2 = 0;
if (x.length <= results.length) {
x = new float[results.length];
y = new float[results.length];
}
if (x2.length <= results.length) {
x2 = new float[results.length];
y2 = new float[results.length];
}
for (int i = 0; i < results.length; i++) {
// Ignore those that were matched by TP
if (actual.contains(results[i].uniqueId))
continue;
if (checkBorder && outsideBorder(results[i], border, xlimit, ylimit)) {
x2[c2] = results[i].getXPosition();
y2[c2++] = results[i].getYPosition();
} else {
x[c] = results[i].getXPosition();
y[c++] = results[i].getYPosition();
}
}
//fn += c;
if (c != 0)
SpotFinderPreview.addRoi(frame, o, x, y, c, Color.yellow);
if (c2 != 0)
SpotFinderPreview.addRoi(frame, o, x2, y2, c2, Color.orange);
return true;
}
});
}
//System.out.printf("TP=%d, FP=%d, FN=%d, N=%d (%d)\n", tp, fp, fn, tp + fn, results.size());
imp.setOverlay(o);
return filterResults;
}
use of ij.ImagePlus in project GDSC-SMLM by aherbert.
the class BenchmarkFilterAnalysis method saveTemplate.
/**
* Save PeakFit configuration template using the current benchmark settings.
*
* @param topFilterSummary
*/
private void saveTemplate(String topFilterSummary) {
FitEngineConfiguration config = new FitEngineConfiguration(new FitConfiguration());
if (!updateAllConfiguration(config, true)) {
IJ.log("Unable to create the template configuration");
return;
}
// Remove the PSF width to make the template generic
config.getFitConfiguration().setInitialPeakStdDev(0);
String filename = getFilename("Template_File", templateFilename);
if (filename != null) {
templateFilename = filename;
Prefs.set(KEY_TEMPLATE_FILENAME, filename);
GlobalSettings settings = new GlobalSettings();
settings.setNotes(getNotes(topFilterSummary));
settings.setFitEngineConfiguration(config);
if (!SettingsManager.saveSettings(settings, filename, true)) {
IJ.log("Unable to save the template configuration");
return;
}
// Save some random frames from the test image data
ImagePlus imp = CreateData.getImage();
if (imp == null)
return;
// Get the number of frames
final ImageStack stack = imp.getImageStack();
if (sampler == null || sampler.getResults() != results) {
sampler = new ResultsImageSampler(results, stack, 32);
sampler.analyse();
}
if (!sampler.isValid())
return;
// Iteratively show the example until the user is happy.
// Yes = OK, No = Repeat, Cancel = Do not save
String keyNo = "nNo";
String keyLow = "nLower";
String keyHigh = "nHigher";
if (Utils.isMacro()) {
// Collect the options if running in a macro
String options = Macro.getOptions();
nNo = Integer.parseInt(Macro.getValue(options, keyNo, Integer.toString(nNo)));
nLow = Integer.parseInt(Macro.getValue(options, keyLow, Integer.toString(nLow)));
nHigh = Integer.parseInt(Macro.getValue(options, keyHigh, Integer.toString(nHigh)));
} else {
if (nLow + nHigh == 0)
nLow = nHigh = 1;
}
final ImagePlus[] out = new ImagePlus[1];
out[0] = sampler.getSample(nNo, nLow, nHigh);
if (!Utils.isMacro()) {
// Show the template results
final ConfigurationTemplate configTemplate = new ConfigurationTemplate();
// Interactively show the sample image data
final boolean[] close = new boolean[1];
final ImagePlus[] outImp = new ImagePlus[1];
if (out[0] != null) {
outImp[0] = display(out[0]);
if (Utils.isNewWindow()) {
close[0] = true;
// Zoom a bit
ImageWindow iw = outImp[0].getWindow();
for (int i = 7; i-- > 0 && Math.max(iw.getWidth(), iw.getHeight()) < 512; ) {
iw.getCanvas().zoomIn(0, 0);
}
}
configTemplate.createResults(outImp[0]);
}
// TODO - fix this when a second sample is made as the results are not updated.
ImageListener listener = new ImageListener() {
public void imageOpened(ImagePlus imp) {
}
public void imageClosed(ImagePlus imp) {
}
public void imageUpdated(ImagePlus imp) {
if (imp != null && imp == outImp[0]) {
configTemplate.updateResults(imp.getCurrentSlice());
}
}
};
ImagePlus.addImageListener(listener);
// For the dialog
String msg = String.format("Showing image data for the template example.\n \nSample Frames:\nEmpty = %d\nLower density = %d\nHigher density = %d\n", sampler.getNumberOfEmptySamples(), sampler.getNumberOfLowDensitySamples(), sampler.getNumberOfHighDensitySamples());
// Turn off the recorder when the dialog is showing
boolean record = Recorder.record;
Recorder.record = false;
NonBlockingGenericDialog gd = new NonBlockingGenericDialog(TITLE);
gd.addMessage(msg);
//gd.enableYesNoCancel(" Save ", " Resample ");
gd.addSlider(keyNo, 0, 10, nNo);
gd.addSlider(keyLow, 0, 10, nLow);
gd.addSlider(keyHigh, 0, 10, nHigh);
gd.addDialogListener(new DialogListener() {
public boolean dialogItemChanged(GenericDialog gd, AWTEvent e) {
// image the user has not seen.
if (e == null)
return true;
nNo = (int) gd.getNextNumber();
nLow = (int) gd.getNextNumber();
nHigh = (int) gd.getNextNumber();
out[0] = sampler.getSample(nNo, nLow, nHigh);
if (out[0] != null) {
outImp[0] = display(out[0]);
if (Utils.isNewWindow()) {
close[0] = true;
// Zoom a bit
ImageWindow iw = outImp[0].getWindow();
for (int i = 7; i-- > 0 && Math.max(iw.getWidth(), iw.getHeight()) < 512; ) {
iw.getCanvas().zoomIn(0, 0);
}
}
configTemplate.createResults(outImp[0]);
}
return true;
}
});
gd.showDialog();
if (gd.wasCanceled()) {
out[0] = null;
// For the recorder
nNo = nLow = nHigh = 0;
}
if (close[0]) {
// Because closing the image sets the stack pixels array to null
if (out[0] != null)
out[0] = out[0].duplicate();
outImp[0].close();
}
configTemplate.closeResults();
ImagePlus.removeImageListener(listener);
if (record) {
Recorder.record = true;
Recorder.recordOption(keyNo, Integer.toString(nNo));
Recorder.recordOption(keyLow, Integer.toString(nLow));
Recorder.recordOption(keyHigh, Integer.toString(nHigh));
}
}
if (out[0] == null)
return;
ImagePlus example = out[0];
filename = Utils.replaceExtension(filename, ".tif");
IJ.save(example, filename);
}
}
use of ij.ImagePlus in project GDSC-SMLM by aherbert.
the class PSFCombiner method selectNextImage.
private boolean selectNextImage() {
// Show a dialog allowing the user to select an input image
if (titles.isEmpty())
return false;
GenericDialog gd = new GenericDialog(TITLE);
gd.addMessage("Select the next input PSF image.\n(Each PSF must have the nm/pixel scale)");
int n = (input.size() + 1);
if (IJ.isMacro())
gd.addStringField("PSF_" + n, "");
else
gd.addChoice("PSF_" + n, titles.toArray(new String[titles.size()]), "");
gd.addMessage("Cancel to finish");
gd.showDialog();
if (gd.wasCanceled())
return false;
String title;
if (IJ.isMacro())
title = gd.getNextString();
else
title = gd.getNextChoice();
// Check the image exists. If not then exit. This is mainly relevant for Macro mode since
// the
// loop will continue otherwise since the titles list is not empty.
ImagePlus imp = WindowManager.getImage(title);
if (imp == null)
return false;
titles.remove(title);
input.add(new PSF(title));
return true;
}
Aggregations