use of uk.ac.sussex.gdsc.smlm.ij.IJImageSource in project GDSC-SMLM by aherbert.
the class PeakFit method setup.
@Override
public int setup(String arg, ImagePlus imp) {
SmlmUsageTracker.recordPlugin(this.getClass(), arg);
pluginFlags = FLAGS;
extraOptions = ImageJUtils.isExtraOptions();
maximaIdentification = StringUtils.contains(arg, "spot");
fitMaxima = StringUtils.contains(arg, "maxima");
simpleFit = StringUtils.contains(arg, "simple");
final boolean runSeries = StringUtils.contains(arg, "series");
ImageSource imageSource = null;
if (fitMaxima) {
// The image source will be found from the peak results.
if (!showMaximaDialog()) {
return DONE;
}
final MemoryPeakResults localResults = ResultsManager.loadInputResults(settings.inputOption, false, DistanceUnit.PIXEL);
if (localResults == null || localResults.size() == 0) {
IJ.error(TITLE, "No results could be loaded");
return DONE;
}
if (settings.fitAcrossAllFrames) {
// Allow the user to select a different image. The source will be set as per the
// main fit routine from the image (imp).
singleFrame = 0;
} else {
// Check for single frame
singleFrame = getSingleFrame(localResults);
// Forces the maxima to be used with their original source.
imp = null;
imageSource = localResults.getSource();
pluginFlags |= NO_IMAGE_REQUIRED;
}
} else if (runSeries) {
imp = null;
// Select input folder
final String inputDirectory = IJ.getDirectory("Select image series ...");
if (inputDirectory == null) {
return DONE;
}
// Load input series ...
SeriesOpener series;
if (extraOptions) {
final String helpKey = maximaIdentification ? "spot-finder-series" : "peak-fit-series";
series = SeriesOpener.create(inputDirectory, true, HelpUrls.getUrl(helpKey));
} else {
series = new SeriesOpener(inputDirectory);
}
if (series.getNumberOfImages() == 0) {
IJ.error(TITLE, "No images in the selected directory:\n" + inputDirectory);
return DONE;
}
final SeriesImageSource seriesImageSource = new SeriesImageSource(getName(series.getImageList()), series);
// TrackProgress logging is very verbose if the series has many images
// Status is used only when reading TIFF info.
// seriesImageSource.setTrackProgress(SimpleImageJTrackProgress.getInstance());
seriesImageSource.setTrackProgress(new TrackProgressAdaptor() {
@Override
public void status(String format, Object... args) {
ImageJUtils.showStatus(() -> String.format(format, args));
}
});
imageSource = seriesImageSource;
pluginFlags |= NO_IMAGE_REQUIRED;
}
// If the image source has not been set then use the input image
if (imageSource == null) {
if (imp == null) {
IJ.noImage();
return DONE;
}
// Check it is not a previous result
if (imp.getTitle().endsWith(ImageJImagePeakResults.IMAGE_SUFFIX)) {
IJImageSource ijImageSource = null;
// Check the image to see if it has an image source XML structure in the info property
final Object o = imp.getProperty("Info");
final Pattern pattern = Pattern.compile("Source: (<.*IJImageSource>.*<.*IJImageSource>)", Pattern.DOTALL);
final Matcher match = pattern.matcher((o == null) ? "" : o.toString());
if (match.find()) {
final ImageSource tmpSource = ImageSource.fromXml(match.group(1));
if (tmpSource instanceof IJImageSource) {
ijImageSource = (IJImageSource) tmpSource;
if (!ijImageSource.open()) {
ijImageSource = null;
} else {
imp = WindowManager.getImage(ijImageSource.getName());
}
}
}
if (ijImageSource == null) {
// Look for a parent using the title
final String parentTitle = imp.getTitle().substring(0, imp.getTitle().length() - ImageJImagePeakResults.IMAGE_SUFFIX.length() - 1);
final ImagePlus parentImp = WindowManager.getImage(parentTitle);
if (parentImp != null) {
ijImageSource = new IJImageSource(parentImp);
imp = parentImp;
}
}
String message = "The selected image may be a previous fit result";
if (ijImageSource != null) {
if (!TextUtils.isNullOrEmpty(ijImageSource.getName())) {
message += " of: \n \n" + ijImageSource.getName();
}
message += " \n \nFit the parent?";
} else {
message += " \n \nDo you want to continue?";
}
final YesNoCancelDialog d = new YesNoCancelDialog(null, TITLE, message);
if (ijImageSource == null) {
if (!d.yesPressed()) {
return DONE;
}
} else {
if (d.yesPressed()) {
imageSource = ijImageSource;
}
if (d.cancelPressed()) {
return DONE;
}
}
}
if (imageSource == null) {
try {
imageSource = new IJImageSource(imp);
} catch (final IllegalArgumentException ex) {
// This can happen if the image has an origin not in integer pixels
// e.g. the plugin is run on a plot
IJ.error(TITLE, "Error using image: " + imp.getTitle() + "\n \n" + ex.getMessage());
return DONE;
}
}
}
time = -1;
if (!initialiseImage(imageSource, getBounds(imp), false)) {
IJ.error(TITLE, "Failed to initialise the source image: " + imageSource.getName());
return DONE;
}
final int flags = showDialog(imp);
if ((flags & DONE) == 0) {
initialiseFitting();
}
return flags;
}
use of uk.ac.sussex.gdsc.smlm.ij.IJImageSource in project GDSC-SMLM by aherbert.
the class FailCountManager method createData.
/**
* Creates the fail count data by running fitting on the current image.
*/
private void createData() {
final ImagePlus imp = WindowManager.getCurrentImage();
if (imp == null) {
IJ.error(TITLE, "No image for fitting");
return;
}
if (!showCreateDataDialog(imp)) {
return;
}
// Get the current fit configuration
final Configuration c = new Configuration();
if (!c.showDialog(false)) {
return;
}
final FitEngineConfiguration fitConfig = c.getFitEngineConfiguration();
// Update stopping criteria.
fitConfig.resetFailCounter();
fitConfig.setFailuresLimit(settings.getFailCountLimit());
final ImageSource source = new IJImageSource(imp);
final PeakFit peakFit = new PeakFit(fitConfig, ResultsSettings.getDefaultInstance());
peakFit.setResultsSuffix("(FailCountAnalysis)");
if (!peakFit.initialise(source, null, false)) {
IJ.error(TITLE, "Failed to initialise the fit engine");
return;
}
final FitEngine engine = peakFit.createFitEngine();
final Rectangle bounds = new Rectangle(source.getWidth(), source.getHeight());
// Run
final int totalFrames = Math.min(source.getFrames(), settings.getMaxFrames());
final int step = ImageJUtils.getProgressInterval(totalFrames);
IJ.showProgress(0);
boolean shutdown = false;
int slice = 0;
final LocalList<ParameterisedFitJob> jobs = new LocalList<>(totalFrames);
while (!shutdown && slice < totalFrames) {
final float[] data = source.next();
if (data == null) {
break;
}
if (slice++ % step == 0) {
final int frames = slice;
if (ImageJUtils.showStatus(() -> "Fitting slice: " + frames + " / " + totalFrames)) {
IJ.showProgress(slice, totalFrames);
}
}
final ParameterisedFitJob job = createJob(source.getStartFrameNumber(), data, bounds);
jobs.push(job);
engine.run(job);
shutdown = escapePressed();
}
ImageJUtils.showStatus("Extracting fail count data");
engine.end(shutdown);
IJ.showProgress(1);
source.close();
// Extract the fail count data
final LocalList<FailCountData> failCountData = new LocalList<>(jobs.size());
for (int i = 0; i < jobs.size(); i++) {
final ParameterisedFitJob job = jobs.unsafeGet(i);
if (job.getStatus() == Status.FINISHED) {
final FitParameters fitParams = job.getFitParameters();
// Find the last success
boolean[] results = fitParams.pass;
int end = results.length - 1;
while (end > 0 && !results[end]) {
end--;
}
// Add on the configured fail count limit
end = Math.min(end + 1 + settings.getFailCountLimit(), results.length);
results = Arrays.copyOf(results, end);
failCountData.add(new FailCountData(job.getSlice(), results));
}
}
failCountDataRef.set(failCountData);
ImageJUtils.showStatus("");
// Save for the future
if (settings.getSaveAfterFitting()) {
saveData();
}
}
use of uk.ac.sussex.gdsc.smlm.ij.IJImageSource in project GDSC-SMLM by aherbert.
the class OverlayResults method run.
@Override
public void run(String arg) {
SmlmUsageTracker.recordPlugin(this.getClass(), arg);
if (MemoryPeakResults.isMemoryEmpty()) {
IJ.error(TITLE, "There are no fitting results in memory");
return;
}
names = new String[MemoryPeakResults.getResultNames().size() + 1];
ids = new int[names.length];
int count = 0;
names[count++] = "(None)";
for (final MemoryPeakResults results : MemoryPeakResults.getAllResults()) {
if (results.getSource() != null && results.getSource().getOriginal() instanceof IJImageSource) {
final IJImageSource source = (IJImageSource) (results.getSource().getOriginal());
final ImagePlus imp = WindowManager.getImage(source.getName());
if (imp != null) {
ids[count] = imp.getID();
names[count++] = results.getName();
}
}
}
if (count == 1) {
IJ.error(TITLE, "There are no result images available");
return;
}
names = Arrays.copyOf(names, count);
Thread thread = null;
Worker worker = null;
final NonBlockingGenericDialog gd = new NonBlockingGenericDialog(TITLE);
settings = Settings.load();
settings.save();
gd.addMessage("Overlay results on current image frame");
gd.addChoice("Results", names, (settings.name == null) ? "" : settings.name);
gd.addCheckbox("Show_table", settings.showTable);
gd.addMessage("");
gd.addHelp(HelpUrls.getUrl("overlay-results"));
gd.hideCancelButton();
gd.setOKLabel("Close");
if (!(IJ.isMacro() || java.awt.GraphicsEnvironment.isHeadless())) {
worker = new Worker();
choice = (Choice) gd.getChoices().get(0);
choice.addItemListener(worker);
checkbox = (Checkbox) gd.getCheckboxes().get(0);
checkbox.addItemListener(worker);
label = (Label) gd.getMessage();
// Initialise
worker.refresh();
// Listen for changes to an image
ImagePlus.addImageListener(worker);
thread = new Thread(worker);
thread.setDaemon(true);
thread.start();
}
gd.showDialog();
if (worker != null) {
ImagePlus.removeImageListener(worker);
}
if (!gd.wasCanceled()) {
settings.name = gd.getNextChoice();
settings.showTable = gd.getNextBoolean();
}
if (thread != null && worker != null) {
worker.running = false;
inbox.close(true);
try {
thread.join(0);
} catch (final InterruptedException ex) {
Logger.getLogger(getClass().getName()).log(Level.WARNING, "Unexpected interruption", ex);
Thread.currentThread().interrupt();
}
}
}
use of uk.ac.sussex.gdsc.smlm.ij.IJImageSource in project GDSC-SMLM by aherbert.
the class SpotAnalysis method extractSpotProfile.
private double[][] extractSpotProfile(ImagePlus imp, Rectangle bounds, ImageStack rawSpot) {
final int nSlices = imp.getStackSize();
final IJImageSource rawSource = new IJImageSource(imp);
final double[][] profile = new double[2][nSlices];
for (int n = 0; n < nSlices; n++) {
IJ.showProgress(n, nSlices);
final float[] data = rawSource.next(bounds);
rawSpot.setPixels(data, n + 1);
final Statistics stats = Statistics.create(data);
profile[0][n] = stats.getMean() / gain;
profile[1][n] = stats.getStandardDeviation() / gain;
}
return profile;
}
use of uk.ac.sussex.gdsc.smlm.ij.IJImageSource in project GDSC-SMLM by aherbert.
the class SpotAnalysis method addCandidateFrames.
private void addCandidateFrames(String title) {
for (final MemoryPeakResults r : MemoryPeakResults.getAllResults()) {
if (r.getSource() instanceof IJImageSource && r.getSource().getName().equals(title)) {
final float minx = areaBounds.x;
final float maxx = minx + areaBounds.width;
final float miny = areaBounds.y;
final float maxy = miny + areaBounds.height;
r.forEach(DistanceUnit.PIXEL, (XyrResultProcedure) (x, y, result) -> {
if (result.getXPosition() >= minx && result.getXPosition() <= maxx && result.getYPosition() >= miny && result.getYPosition() <= maxy) {
candidateFrames.add(result.getFrame());
}
});
}
}
}
Aggregations