Search in sources :

Example 16 with ImageStack

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);
}
Also used : MappedImageStack(ij.MappedImageStack) MappedImageStack(ij.MappedImageStack) ImageStack(ij.ImageStack)

Example 17 with ImageStack

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;
}
Also used : ImageStack(ij.ImageStack) Roi(ij.gui.Roi) Point(java.awt.Point)

Example 18 with ImageStack

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("");
}
Also used : ImageStack(ij.ImageStack) Rectangle(java.awt.Rectangle) StoredDataStatistics(gdsc.core.utils.StoredDataStatistics) WindowOrganiser(ij.plugin.WindowOrganiser) StoredDataStatistics(gdsc.core.utils.StoredDataStatistics) Statistics(gdsc.core.utils.Statistics) LinkedList(java.util.LinkedList) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue)

Example 19 with ImageStack

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("");
}
Also used : ImageStack(ij.ImageStack) TIntProcedure(gnu.trove.procedure.TIntProcedure) PeakResultPoint(gdsc.smlm.ij.plugins.ResultsMatchCalculator.PeakResultPoint) LinkedList(java.util.LinkedList) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) FitWorker(gdsc.smlm.engine.FitWorker)

Example 20 with ImageStack

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;
}
Also used : TIntProcedure(gnu.trove.procedure.TIntProcedure) ArrayList(java.util.ArrayList) PeakResult(gdsc.smlm.results.PeakResult) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) MaximaSpotFilter(gdsc.smlm.filters.MaximaSpotFilter) ImageStack(ij.ImageStack) PeakResultPoint(gdsc.smlm.ij.plugins.ResultsMatchCalculator.PeakResultPoint) BasePoint(gdsc.core.match.BasePoint) LinkedList(java.util.LinkedList) TIntObjectHashMap(gnu.trove.map.hash.TIntObjectHashMap)

Aggregations

ImageStack (ij.ImageStack)39 ImagePlus (ij.ImagePlus)13 ImageProcessor (ij.process.ImageProcessor)10 Rectangle (java.awt.Rectangle)9 LinkedList (java.util.LinkedList)8 PeakResult (gdsc.smlm.results.PeakResult)7 BasePoint (gdsc.core.match.BasePoint)6 ArrayBlockingQueue (java.util.concurrent.ArrayBlockingQueue)6 Statistics (gdsc.core.utils.Statistics)5 MemoryPeakResults (gdsc.smlm.results.MemoryPeakResults)5 Point (java.awt.Point)5 ExecutorService (java.util.concurrent.ExecutorService)5 Future (java.util.concurrent.Future)5 StoredDataStatistics (gdsc.core.utils.StoredDataStatistics)4 PeakResultPoint (gdsc.smlm.ij.plugins.ResultsMatchCalculator.PeakResultPoint)4 FloatProcessor (ij.process.FloatProcessor)4 FitWorker (gdsc.smlm.engine.FitWorker)3 IJImageSource (gdsc.smlm.ij.IJImageSource)3 Calibration (gdsc.smlm.results.Calibration)3 WindowOrganiser (ij.plugin.WindowOrganiser)3