use of ij.ImageStack in project GDSC-SMLM by aherbert.
the class IJImagePeakResults method createNewImageStack.
private ImageStack createNewImageStack(int w, int h) {
if ((displayFlags & DISPLAY_MAPPED) != 0) {
MappedImageStack stack = new MappedImageStack(w, h);
stack.setMapZero((displayFlags & DISPLAY_MAP_ZERO) != 0);
return stack;
}
return new ImageStack(w, h);
}
use of ij.ImageStack in project GDSC-SMLM by aherbert.
the class EMGainAnalysis method buildHistogram.
/**
* Build a histogram using pixels within the image ROI
*
* @param image
* The image
* @return The image histogram
*/
private static int[] buildHistogram(ImagePlus imp) {
ImageStack stack = imp.getImageStack();
Roi roi = imp.getRoi();
int[] data = getHistogram(stack.getProcessor(1), roi);
for (int n = 2; n <= stack.getSize(); n++) {
int[] tmp = getHistogram(stack.getProcessor(n), roi);
for (int i = 0; i < tmp.length; i++) data[i] += tmp[i];
}
// Avoid super-saturated pixels by using 98% of histogram
long sum = 0;
for (int i = 0; i < data.length; i++) {
sum += data[i];
}
final long sum2 = (long) (sum * 0.99);
sum = 0;
for (int i = 0; i < data.length; i++) {
sum += data[i];
if (sum > sum2) {
for (; i < data.length; i++) data[i] = 0;
break;
}
}
return data;
}
use of ij.ImageStack in project GDSC-SMLM by aherbert.
the class BenchmarkFit method run.
private void run() {
// Initialise the answer. Convert to units of the image (ADUs and pixels)
answer[Gaussian2DFunction.BACKGROUND] = benchmarkParameters.getBackground() * benchmarkParameters.gain;
answer[Gaussian2DFunction.SIGNAL] = benchmarkParameters.getSignal() * benchmarkParameters.gain;
answer[Gaussian2DFunction.X_POSITION] = benchmarkParameters.x;
answer[Gaussian2DFunction.Y_POSITION] = benchmarkParameters.y;
answer[Gaussian2DFunction.X_SD] = benchmarkParameters.s / benchmarkParameters.a;
answer[Gaussian2DFunction.Y_SD] = benchmarkParameters.s / benchmarkParameters.a;
// Set up the fit region. Always round down since 0.5 is the centre of the pixel.
int x = (int) benchmarkParameters.x;
int y = (int) benchmarkParameters.y;
region = new Rectangle(x - regionSize, y - regionSize, 2 * regionSize + 1, 2 * regionSize + 1);
if (!new Rectangle(0, 0, imp.getWidth(), imp.getHeight()).contains(region)) {
// Check if it is incorrect by only 1 pixel
if (region.width <= imp.getWidth() + 1 && region.height <= imp.getHeight() + 1) {
Utils.log("Adjusting region %s to fit within image bounds (%dx%d)", region.toString(), imp.getWidth(), imp.getHeight());
region = new Rectangle(0, 0, imp.getWidth(), imp.getHeight());
} else {
IJ.error(TITLE, "Fit region does not fit within the image");
return;
}
}
// Adjust the centre & account for 0.5 pixel offset during fitting
x -= region.x;
y -= region.y;
answer[Gaussian2DFunction.X_POSITION] -= (region.x + 0.5);
answer[Gaussian2DFunction.Y_POSITION] -= (region.y + 0.5);
// Configure for fitting
fitConfig.setBackgroundFitting(backgroundFitting);
fitConfig.setNotSignalFitting(!signalFitting);
fitConfig.setComputeDeviations(false);
final ImageStack stack = imp.getImageStack();
// Create a pool of workers
int nThreads = Prefs.getThreads();
BlockingQueue<Integer> jobs = new ArrayBlockingQueue<Integer>(nThreads * 2);
List<Worker> workers = new LinkedList<Worker>();
List<Thread> threads = new LinkedList<Thread>();
for (int i = 0; i < nThreads; i++) {
Worker worker = new Worker(jobs, stack, region, fitConfig);
Thread t = new Thread(worker);
workers.add(worker);
threads.add(t);
t.start();
}
final int totalFrames = benchmarkParameters.frames;
// Store all the fitting results
results = new double[totalFrames * getNumberOfStartPoints()][];
resultsTime = new long[results.length];
// Fit the frames
totalProgress = totalFrames;
stepProgress = Utils.getProgressInterval(totalProgress);
progress = 0;
for (int i = 0; i < totalFrames; i++) {
// Only fit if there were simulated photons
if (benchmarkParameters.p[i] > 0) {
put(jobs, i);
}
}
// Finish all the worker threads by passing in a null job
for (int i = 0; i < threads.size(); i++) {
put(jobs, -1);
}
// Wait for all to finish
for (int i = 0; i < threads.size(); i++) {
try {
threads.get(i).join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
threads.clear();
if (comFitting)
Utils.log(TITLE + ": CoM within start offset = %d / %d (%s%%)", comValid.intValue(), totalFrames, Utils.rounded((100.0 * comValid.intValue()) / totalFrames));
IJ.showProgress(1);
IJ.showStatus("Collecting results ...");
// Collect the results
Statistics[] stats = new Statistics[NAMES.length];
for (int i = 0; i < workers.size(); i++) {
Statistics[] next = workers.get(i).stats;
for (int j = 0; j < next.length; j++) {
if (stats[j] == null)
stats[j] = next[j];
else
stats[j].add(next[j]);
}
}
workers.clear();
// Show a table of the results
summariseResults(stats);
// Optionally show histograms
if (showHistograms) {
IJ.showStatus("Calculating histograms ...");
int[] idList = new int[NAMES.length];
int count = 0;
double[] convert = getConversionFactors();
boolean requireRetile = false;
for (int i = 0; i < NAMES.length; i++) {
if (displayHistograms[i] && convert[i] != 0) {
// We will have to convert the values...
double[] tmp = ((StoredDataStatistics) stats[i]).getValues();
for (int j = 0; j < tmp.length; j++) tmp[j] *= convert[i];
StoredDataStatistics tmpStats = new StoredDataStatistics(tmp);
idList[count++] = Utils.showHistogram(TITLE, tmpStats, NAMES[i], 0, 0, histogramBins, String.format("%s +/- %s", Utils.rounded(tmpStats.getMean()), Utils.rounded(tmpStats.getStandardDeviation())));
requireRetile = requireRetile || Utils.isNewWindow();
}
}
if (count > 0 && requireRetile) {
idList = Arrays.copyOf(idList, count);
new WindowOrganiser().tileWindows(idList);
}
}
if (saveRawData) {
String dir = Utils.getDirectory("Data_directory", rawDataDirectory);
if (dir != null)
saveData(stats, dir);
}
IJ.showStatus("");
}
use of ij.ImageStack in project GDSC-SMLM by aherbert.
the class BenchmarkSmartSpotRanking method run.
private void run() {
// Extract all the results in memory into a list per frame. This can be cached
boolean refresh = false;
if (lastId != simulationParameters.id) {
// Do not get integer coordinates
// The Coordinate objects will be PeakResultPoint objects that store the original PeakResult
// from the MemoryPeakResults
actualCoordinates = ResultsMatchCalculator.getCoordinates(results.getResults(), false);
lastId = simulationParameters.id;
refresh = true;
}
// Extract all the candidates into a list per frame. This can be cached if the settings have not changed
if (refresh || lastFilterId != BenchmarkSpotFilter.filterResult.id || lastFractionPositives != fractionPositives || lastFractionNegativesAfterAllPositives != fractionNegativesAfterAllPositives || lastNegativesAfterAllPositives != negativesAfterAllPositives) {
filterCandidates = subsetFilterResults(BenchmarkSpotFilter.filterResult.filterResults);
lastFilterId = BenchmarkSpotFilter.filterResult.id;
lastFractionPositives = fractionPositives;
lastFractionNegativesAfterAllPositives = fractionNegativesAfterAllPositives;
lastNegativesAfterAllPositives = negativesAfterAllPositives;
}
final ImageStack stack = imp.getImageStack();
// Create a pool of workers
final int nThreads = Prefs.getThreads();
final BlockingQueue<Integer> jobs = new ArrayBlockingQueue<Integer>(nThreads * 2);
List<Worker> workers = new LinkedList<Worker>();
List<Thread> threads = new LinkedList<Thread>();
for (int i = 0; i < nThreads; i++) {
Worker worker = new Worker(jobs, stack, actualCoordinates, filterCandidates);
Thread t = new Thread(worker);
workers.add(worker);
threads.add(t);
t.start();
}
// Process the frames
totalProgress = filterCandidates.size();
stepProgress = Utils.getProgressInterval(totalProgress);
progress = 0;
filterCandidates.forEachKey(new TIntProcedure() {
public boolean execute(int value) {
put(jobs, value);
return true;
}
});
// Finish all the worker threads by passing in a null job
for (int i = 0; i < threads.size(); i++) {
put(jobs, -1);
}
// Wait for all to finish
for (int i = 0; i < threads.size(); i++) {
try {
threads.get(i).join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
threads.clear();
IJ.showProgress(1);
if (Utils.isInterrupted()) {
IJ.showStatus("Aborted");
return;
}
IJ.showStatus("Collecting results ...");
rankResultsId++;
rankResults = new TIntObjectHashMap<RankResults>();
for (Worker w : workers) {
rankResults.putAll(w.results);
}
summariseResults(rankResults);
IJ.showStatus("");
}
use of ij.ImageStack in project GDSC-SMLM by aherbert.
the class BenchmarkSpotFilter method run.
private BenchmarkFilterResult run(FitEngineConfiguration config, boolean relativeDistances, boolean batchSummary) {
if (Utils.isInterrupted())
return null;
MaximaSpotFilter spotFilter = config.createSpotFilter(relativeDistances);
// Extract all the results in memory into a list per frame. This can be cached
if (// || lastRelativeDistances != relativeDistances)
lastId != simulationParameters.id) {
// Always use float coordinates.
// The Worker adds a pixel offset for the spot coordinates.
TIntObjectHashMap<ArrayList<Coordinate>> coordinates = ResultsMatchCalculator.getCoordinates(results.getResults(), false);
actualCoordinates = new TIntObjectHashMap<PSFSpot[]>();
lastId = simulationParameters.id;
//lastRelativeDistances = relativeDistances;
// Store these so we can reset them
final int total = totalProgress;
final String prefix = progressPrefix;
// Spot PSFs may overlap so we must determine the amount of signal overlap and amplitude effect
// for each spot...
IJ.showStatus("Computing PSF overlap ...");
final int nThreads = Prefs.getThreads();
final BlockingQueue<Integer> jobs = new ArrayBlockingQueue<Integer>(nThreads * 2);
List<OverlapWorker> workers = new LinkedList<OverlapWorker>();
List<Thread> threads = new LinkedList<Thread>();
for (int i = 0; i < nThreads; i++) {
OverlapWorker worker = new OverlapWorker(jobs, coordinates);
Thread t = new Thread(worker);
workers.add(worker);
threads.add(t);
t.start();
}
// Process the frames
totalProgress = coordinates.size();
stepProgress = Utils.getProgressInterval(totalProgress);
progress = 0;
coordinates.forEachKey(new TIntProcedure() {
public boolean execute(int value) {
put(jobs, value);
return true;
}
});
// Finish all the worker threads by passing in a null job
for (int i = 0; i < threads.size(); i++) {
put(jobs, -1);
}
// Wait for all to finish
for (int i = 0; i < threads.size(); i++) {
try {
threads.get(i).join();
} catch (InterruptedException e) {
e.printStackTrace();
}
actualCoordinates.putAll(workers.get(i).coordinates);
}
threads.clear();
IJ.showProgress(-1);
IJ.showStatus("");
setupProgress(total, prefix);
}
if (!batchMode)
IJ.showStatus("Computing results ...");
final ImageStack stack = imp.getImageStack();
float background = 0;
if (spotFilter.isAbsoluteIntensity()) {
// To allow the signal factor to be computed we need to lower the image by the background so
// that the intensities correspond to the results amplitude.
// Just assume the background is uniform.
double sum = 0;
for (PeakResult r : results) sum += r.getBackground();
background = (float) (sum / results.size());
}
// Create a pool of workers
final int nThreads = Prefs.getThreads();
BlockingQueue<Integer> jobs = new ArrayBlockingQueue<Integer>(nThreads * 2);
List<Worker> workers = new LinkedList<Worker>();
List<Thread> threads = new LinkedList<Thread>();
for (int i = 0; i < nThreads; i++) {
Worker worker = new Worker(jobs, stack, spotFilter, background);
Thread t = new Thread(worker);
workers.add(worker);
threads.add(t);
t.start();
}
// Fit the frames
for (int i = 1; i <= stack.getSize(); i++) {
put(jobs, i);
}
// Finish all the worker threads by passing in a null job
for (int i = 0; i < threads.size(); i++) {
put(jobs, -1);
}
// Wait for all to finish
for (int i = 0; i < threads.size(); i++) {
try {
threads.get(i).join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
threads.clear();
if (Utils.isInterrupted())
return null;
if (!batchMode) {
IJ.showProgress(-1);
IJ.showStatus("Collecting results ...");
}
TIntObjectHashMap<FilterResult> filterResults = new TIntObjectHashMap<FilterResult>();
time = 0;
for (Worker w : workers) {
time += w.time;
filterResults.putAll(w.results);
}
// Show a table of the results
BenchmarkFilterResult filterResult = summariseResults(filterResults, config, spotFilter, relativeDistances, batchSummary);
if (!batchMode)
IJ.showStatus("");
return filterResult;
}
Aggregations