use of ij.process.ImageProcessor in project GDSC-SMLM by aherbert.
the class PulseActivationAnalysis method runSimulation.
private void runSimulation() {
TITLE += " Simulation";
if (!showSimulationDialog())
return;
long start = System.currentTimeMillis();
RandomDataGenerator rdg = getRandomDataGenerator();
// Draw the molecule positions
Utils.showStatus("Simulating molecules ...");
float[][][] molecules = new float[3][][];
MemoryPeakResults[] results = new MemoryPeakResults[3];
Rectangle bounds = new Rectangle(0, 0, sim_size, sim_size);
for (int c = 0; c < 3; c++) {
molecules[c] = simulateMolecules(rdg, c);
// Create a dataset to store the activations
MemoryPeakResults r = new MemoryPeakResults();
r.setCalibration(new Calibration(sim_nmPerPixel, 1, 100));
r.setBounds(bounds);
r.setName(TITLE + " C" + (c + 1));
results[c] = r;
}
// Simulate activation
Utils.showStatus("Simulating activations ...");
for (int c = 0; c < 3; c++) simulateActivations(rdg, molecules, c, results);
// Combine
Utils.showStatus("Producing simulation output ...");
MemoryPeakResults r = new MemoryPeakResults();
r.setCalibration(new Calibration(sim_nmPerPixel, 1, 100));
r.setBounds(new Rectangle(0, 0, sim_size, sim_size));
r.setName(TITLE);
ImageProcessor[] images = new ImageProcessor[3];
for (int c = 0; c < 3; c++) {
ArrayList<PeakResult> list = (ArrayList<PeakResult>) results[c].getResults();
r.addAllf(list);
// Draw the unmixed activations
IJImagePeakResults image = ImagePeakResultsFactory.createPeakResultsImage(ResultsImage.LOCALISATIONS, true, true, TITLE, bounds, sim_nmPerPixel, 1, 1024.0 / sim_size, 0, ResultsMode.ADD);
image.setLiveImage(false);
image.setDisplayImage(false);
image.begin();
image.addAll(list);
image.end();
images[c] = image.getImagePlus().getProcessor();
}
displayComposite(images, TITLE);
// Add to memory. Set the composite dataset first.
MemoryPeakResults.addResults(r);
for (int c = 0; c < 3; c++) MemoryPeakResults.addResults(results[c]);
// TODO:
// Show an image of what it looks like with no unmixing, i.e. colours allocated
// from the frame
Utils.showStatus("Simulation complete: " + Utils.timeToString(System.currentTimeMillis() - start));
}
use of ij.process.ImageProcessor in project GDSC-SMLM by aherbert.
the class DriftCalculator method calculateDriftUsingFrames.
/**
* Calculate the drift by aligning N consecutive frames with the overall image. Update the current drift parameters.
*
* @param blocks
* @param blockT
* @param bounds
* @param scale
* @param dx
* @param dy
* @param smoothing
* @param iterations
* @return
*/
private double calculateDriftUsingFrames(ArrayList<ArrayList<Localisation>> blocks, int[] blockT, Rectangle bounds, float scale, double[] dx, double[] dy, double[] originalDriftTimePoints, double smoothing, int iterations) {
// Construct images using the current drift
tracker.status("Constructing images");
// Built an image for each block of results.
final ImageProcessor[] images = new ImageProcessor[blocks.size()];
List<Future<?>> futures = new LinkedList<Future<?>>();
progressCounter = 0;
totalCounter = images.length * 2;
for (int i = 0; i < images.length; i++) {
futures.add(threadPool.submit(new ImageBuilder(blocks.get(i), images, i, bounds, scale, dx, dy)));
}
Utils.waitForCompletion(futures);
for (int i = 0; i < blocks.size(); i++) {
tracker.progress(i, blocks.size());
IJImagePeakResults blockImage = newImage(bounds, scale);
for (Localisation r : blocks.get(i)) {
blockImage.add(r.t, (float) (r.x + dx[r.t]), (float) (r.y + dy[r.t]), r.s);
}
images[i] = getImage(blockImage);
}
// Build an image with all results.
FloatProcessor allIp = new FloatProcessor(images[0].getWidth(), images[0].getHeight());
for (ImageProcessor ip : images) allIp.copyBits(ip, 0, 0, Blitter.ADD);
return calculateDrift(blockT, scale, dx, dy, originalDriftTimePoints, smoothing, iterations, images, allIp, true);
}
use of ij.process.ImageProcessor in project GDSC-SMLM by aherbert.
the class BackgroundEstimator method drawPlot.
/**
* Build a plot of the noise estimate from the current frame.
* Limit the preview to 100 frames.
*/
private void drawPlot() {
IJ.showStatus("Estimating background ...");
int start = imp.getCurrentSlice();
int end = FastMath.min(imp.getStackSize(), start + 100);
int size = end - start + 1;
double[] xValues = new double[size];
double[] noise1 = new double[size];
double[] noise2 = new double[size];
double[] background = new double[size];
double[] threshold = new double[size];
double[] percentile = new double[size];
ImageStack stack = imp.getImageStack();
Rectangle bounds = imp.getProcessor().getRoi();
float[] buffer = null;
for (int slice = start, i = 0; slice <= end; slice++, i++) {
IJ.showProgress(i, size);
final ImageProcessor ip = stack.getProcessor(slice);
buffer = ImageConverter.getData(ip.getPixels(), ip.getWidth(), ip.getHeight(), bounds, buffer);
final DataEstimator de = new DataEstimator(buffer, bounds.width, bounds.height);
de.setFraction(fraction);
de.setHistogramSize(histogramSize);
de.setThresholdMethod(thresholdMethod);
xValues[i] = slice;
try {
noise1[i] = de.getNoise();
noise2[i] = de.getNoise(noiseMethod);
background[i] = de.getBackground();
threshold[i] = de.getThreshold();
percentile[i] = de.getPercentile(BackgroundEstimator.percentile);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
IJ.showProgress(1);
IJ.showStatus("Plotting background ...");
WindowOrganiser wo = new WindowOrganiser();
plot(wo, xValues, noise1, noise2, null, "Noise", "Background Noise", "Global Noise", null);
plot(wo, xValues, background, threshold, percentile, "Background", "Background", "Threshold", "Percentile");
wo.tile();
IJ.showStatus("");
}
use of ij.process.ImageProcessor in project GDSC-SMLM by aherbert.
the class PSFEstimator method calculateStatistics.
private boolean calculateStatistics(PeakFit fitter, double[] params, double[] params_dev) {
debug(" Fitting PSF");
swapStatistics();
// Create the fit engine using the PeakFit plugin
FitConfiguration fitConfig = config.getFitConfiguration();
fitConfig.setInitialAngle((float) params[0]);
fitConfig.setInitialPeakStdDev0((float) params[1]);
fitConfig.setInitialPeakStdDev1((float) params[2]);
ImageStack stack = imp.getImageStack();
Rectangle roi = stack.getProcessor(1).getRoi();
ImageSource source = new IJImageSource(imp);
// Allow interlaced data by wrapping the image source
if (interlacedData) {
source = new InterlacedImageSource(source, dataStart, dataBlock, dataSkip);
}
// Allow frame aggregation by wrapping the image source
if (integrateFrames > 1) {
source = new AggregatedImageSource(source, integrateFrames);
}
fitter.initialiseImage(source, roi, true);
fitter.addPeakResults(this);
fitter.initialiseFitting();
FitEngine engine = fitter.createFitEngine();
// Use random slices
int[] slices = new int[stack.getSize()];
for (int i = 0; i < slices.length; i++) slices[i] = i + 1;
Random rand = new Random();
rand.shuffle(slices);
IJ.showStatus("Fitting ...");
// Use multi-threaded code for speed
int i;
for (i = 0; i < slices.length; i++) {
int slice = slices[i];
//debug(" Processing slice = %d\n", slice);
IJ.showProgress(size(), settings.numberOfPeaks);
ImageProcessor ip = stack.getProcessor(slice);
// stack processor does not set the bounds required by ImageConverter
ip.setRoi(roi);
FitJob job = new FitJob(slice, ImageConverter.getData(ip), roi);
engine.run(job);
if (sampleSizeReached() || Utils.isInterrupted()) {
break;
}
}
if (Utils.isInterrupted()) {
IJ.showProgress(1);
engine.end(true);
return false;
}
// Wait until we have enough results
while (!sampleSizeReached() && !engine.isQueueEmpty()) {
IJ.showProgress(size(), settings.numberOfPeaks);
try {
Thread.sleep(50);
} catch (InterruptedException e) {
break;
}
}
// End now if we have enough samples
engine.end(sampleSizeReached());
IJ.showStatus("");
IJ.showProgress(1);
// This count will be an over-estimate given that the provider is ahead of the consumer
// in this multi-threaded system
debug(" Processed %d/%d slices (%d peaks)", i, slices.length, size());
setParams(ANGLE, params, params_dev, sampleNew[ANGLE]);
setParams(X, params, params_dev, sampleNew[X]);
setParams(Y, params, params_dev, sampleNew[Y]);
if (settings.showHistograms) {
int[] idList = new int[NAMES.length];
int count = 0;
boolean requireRetile = false;
for (int ii = 0; ii < 3; ii++) {
if (sampleNew[ii].getN() == 0)
continue;
StoredDataStatistics stats = new StoredDataStatistics(sampleNew[ii].getValues());
idList[count++] = Utils.showHistogram(TITLE, stats, NAMES[ii], 0, 0, settings.histogramBins, "Mean = " + Utils.rounded(stats.getMean()) + ". Median = " + Utils.rounded(sampleNew[ii].getPercentile(50)));
requireRetile = requireRetile || Utils.isNewWindow();
}
if (requireRetile && count > 0) {
new WindowOrganiser().tileWindows(Arrays.copyOf(idList, count));
}
}
if (size() < 2) {
log("ERROR: Insufficient number of fitted peaks, terminating ...");
return false;
}
return true;
}
use of ij.process.ImageProcessor in project GDSC-SMLM by aherbert.
the class Noise method drawPlot.
/**
* Build a plot of the noise estimate from the current frame.
* Limit the preview to 100 frames.
*/
private void drawPlot() {
NoiseEstimator.Method method1 = NoiseEstimator.Method.values()[algorithm];
NoiseEstimator.Method method2 = NoiseEstimator.Method.values()[algorithm2];
IJ.showStatus("Estimating noise ...");
boolean twoMethods = method1 != method2;
boolean preserveResiduals = method1.name().contains("Residuals") && method2.name().contains("Residuals") && twoMethods;
int start = imp.getCurrentSlice();
int end = FastMath.min(imp.getStackSize(), start + 100);
int size = end - start + 1;
double[] xValues = new double[size];
double[] yValues1 = new double[size];
double[] yValues2 = (twoMethods) ? new double[size] : null;
ImageStack stack = imp.getImageStack();
Rectangle bounds = imp.getProcessor().getRoi();
float[] buffer = null;
for (int slice = start, i = 0; slice <= end; slice++, i++) {
IJ.showProgress(i, size);
final ImageProcessor ip = stack.getProcessor(slice);
buffer = ImageConverter.getData(ip.getPixels(), ip.getWidth(), ip.getHeight(), bounds, buffer);
final NoiseEstimator ne = new NoiseEstimator(buffer, bounds.width, bounds.height);
ne.preserveResiduals = preserveResiduals;
ne.setRange(lowestPixelsRange);
xValues[i] = slice;
yValues1[i] = ne.getNoise(method1);
if (twoMethods)
yValues2[i] = ne.getNoise(method2);
}
IJ.showProgress(1);
IJ.showStatus("Plotting noise ...");
// Get limits
double[] a = Tools.getMinMax(xValues);
double[] b1 = Tools.getMinMax(yValues1);
if (twoMethods) {
double[] b2 = Tools.getMinMax(yValues2);
b1[0] = FastMath.min(b1[0], b2[0]);
b1[1] = FastMath.max(b1[1], b2[1]);
}
String title = imp.getTitle() + " Noise";
Plot2 plot = new Plot2(title, "Slice", "Noise", xValues, yValues1);
double range = b1[1] - b1[0];
if (range == 0)
range = 1;
plot.setLimits(a[0], a[1], b1[0] - 0.05 * range, b1[1] + 0.05 * range);
plot.setColor(Color.blue);
plot.draw();
String label = String.format("Blue = %s", Utils.rounded(new Statistics(yValues1).getMean()));
if (twoMethods) {
plot.setColor(Color.red);
plot.addPoints(xValues, yValues2, Plot2.LINE);
label += String.format(", Red = %s", Utils.rounded(new Statistics(yValues2).getMean()));
}
plot.addLabel(0, 0, label);
Utils.display(title, plot);
IJ.showStatus("");
}
Aggregations