Search in sources :

Example 21 with ImageStack

use of ij.ImageStack in project GDSC-SMLM by aherbert.

the class YeastMask method createNucleusSphere.

/**
	 * Create a sphere using the given pixel width and stack depth using a fraction of the original cell radius
	 * 
	 * @param width
	 * @param depth
	 * @return A sphere
	 */
private ImageStack createNucleusSphere(int width, int depth) {
    // Create a sphere. This could be done exploiting symmetry to be more efficient
    // but is left as a simple implementation
    final double centreX = width * 0.5;
    final double centreZ = depth * 0.5;
    // Precompute squares for the width
    double[] s = new double[width];
    for (int iy = 0; iy < width; iy++) {
        final double y = (centreX - (iy + 0.5)) * nmPerPixel;
        s[iy] = y * y;
    }
    ImageStack stack = new ImageStack(width, width, depth);
    final byte on = (byte) 255;
    final double r = radius * 1000 * nucleus;
    final double r2 = r * r;
    for (int iz = 0; iz < depth; iz++) {
        final double z = (centreZ - (iz + 0.5)) * nmPerSlice;
        final double z2 = z * z;
        byte[] mask = new byte[width * width];
        for (int iy = 0, i = 0; iy < width; iy++) {
            final double y2z2 = s[iy] + z2;
            for (int ix = 0; ix < width; ix++, i++) {
                final double d2 = s[ix] + y2z2;
                if (d2 < r2)
                    mask[i] = on;
            }
        }
        stack.setPixels(mask, iz + 1);
    }
    return stack;
}
Also used : ImageStack(ij.ImageStack)

Example 22 with ImageStack

use of ij.ImageStack in project GDSC-SMLM by aherbert.

the class BenchmarkSpotFit 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
    final int width = (config.isIncludeNeighbours()) ? config.getRelativeFitting() : 0;
    final Settings settings = new Settings(BenchmarkSpotFilter.filterResult.id, fractionPositives, fractionNegativesAfterAllPositives, negativesAfterAllPositives, width);
    if (refresh || !settings.equals(lastSettings)) {
        filterCandidates = subsetFilterResults(BenchmarkSpotFilter.filterResult.filterResults, width);
        lastSettings = settings;
        lastFilterId = BenchmarkSpotFilter.filterResult.id;
    }
    stopWatch = StopWatch.createStarted();
    final ImageStack stack = imp.getImageStack();
    clearFitResults();
    // Save results to memory
    MemoryPeakResults peakResults = new MemoryPeakResults();
    peakResults.copySettings(this.results);
    peakResults.setName(TITLE);
    MemoryPeakResults.addResults(peakResults);
    // 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, actualCoordinates, filterCandidates, peakResults);
        Thread t = new Thread(worker);
        workers.add(worker);
        threads.add(t);
        t.start();
    }
    // Fit the frames
    long runTime = System.nanoTime();
    totalProgress = stack.getSize();
    stepProgress = Utils.getProgressInterval(totalProgress);
    progress = 0;
    for (int i = 1; i <= totalProgress; 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();
    IJ.showProgress(1);
    runTime = System.nanoTime() - runTime;
    if (Utils.isInterrupted()) {
        return;
    }
    stopWatch.stop();
    final String timeString = stopWatch.toString();
    IJ.log("Spot fit time : " + timeString);
    IJ.showStatus("Collecting results ...");
    fitResultsId++;
    fitResults = new TIntObjectHashMap<FilterCandidates>();
    for (Worker w : workers) {
        fitResults.putAll(w.results);
    }
    // Assign a unique ID to each result
    int count = 0;
    // Materialise into an array since we use it twice
    FilterCandidates[] candidates = fitResults.values(new FilterCandidates[fitResults.size()]);
    for (FilterCandidates result : candidates) {
        for (int i = 0; i < result.fitResult.length; i++) {
            final MultiPathFitResult fitResult = result.fitResult[i];
            count += count(fitResult.getSingleFitResult());
            count += count(fitResult.getMultiFitResult());
            count += count(fitResult.getDoubletFitResult());
            count += count(fitResult.getMultiDoubletFitResult());
        }
    }
    PreprocessedPeakResult[] preprocessedPeakResults = new PreprocessedPeakResult[count];
    count = 0;
    for (FilterCandidates result : candidates) {
        for (int i = 0; i < result.fitResult.length; i++) {
            final MultiPathFitResult fitResult = result.fitResult[i];
            count = store(fitResult.getSingleFitResult(), count, preprocessedPeakResults);
            count = store(fitResult.getMultiFitResult(), count, preprocessedPeakResults);
            count = store(fitResult.getDoubletFitResult(), count, preprocessedPeakResults);
            count = store(fitResult.getMultiDoubletFitResult(), count, preprocessedPeakResults);
        }
    }
    summariseResults(fitResults, runTime, preprocessedPeakResults, count);
    IJ.showStatus("");
}
Also used : ImageStack(ij.ImageStack) PeakResultPoint(gdsc.smlm.ij.plugins.ResultsMatchCalculator.PeakResultPoint) BasePoint(gdsc.core.match.BasePoint) LinkedList(java.util.LinkedList) MultiPathFitResult(gdsc.smlm.results.filter.MultiPathFitResult) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) BasePreprocessedPeakResult(gdsc.smlm.results.filter.BasePreprocessedPeakResult) PreprocessedPeakResult(gdsc.smlm.results.filter.PreprocessedPeakResult) FitWorker(gdsc.smlm.engine.FitWorker) MemoryPeakResults(gdsc.smlm.results.MemoryPeakResults) FilterSettings(gdsc.smlm.ij.settings.FilterSettings) Settings(gdsc.core.utils.Settings) GlobalSettings(gdsc.smlm.ij.settings.GlobalSettings)

Example 23 with ImageStack

use of ij.ImageStack 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);
    }
}
Also used : ResultsImageSampler(gdsc.smlm.ij.results.ResultsImageSampler) ImageWindow(ij.gui.ImageWindow) ImageStack(ij.ImageStack) ImageListener(ij.ImageListener) FitEngineConfiguration(gdsc.smlm.engine.FitEngineConfiguration) GlobalSettings(gdsc.smlm.ij.settings.GlobalSettings) NonBlockingGenericDialog(ij.gui.NonBlockingGenericDialog) ImagePlus(ij.ImagePlus) FitConfiguration(gdsc.smlm.fitting.FitConfiguration) DialogListener(ij.gui.DialogListener) GenericDialog(ij.gui.GenericDialog) NonBlockingGenericDialog(ij.gui.NonBlockingGenericDialog) AWTEvent(java.awt.AWTEvent)

Example 24 with ImageStack

use of ij.ImageStack in project GDSC-SMLM by aherbert.

the class PSFCombiner method combineImages.

private void combineImages() {
    double nmPerPixel = getNmPerPixel();
    if (nmPerPixel <= 0)
        return;
    double nmPerSlice = getNmPerSlice();
    if (nmPerPixel <= 0)
        return;
    // Find the lowest start point
    int min = 0;
    for (PSF psf : input) {
        if (min > psf.start)
            min = psf.start;
    }
    // Shift all stacks and find the dimensions
    final int shift = -min;
    int max = 0, size = 0;
    int totalImages = 0;
    for (PSF psf : input) {
        psf.start += shift;
        totalImages += psf.psfSettings.nImages;
        if (max < psf.getEnd())
            max = psf.getEnd();
        if (size < psf.getSize())
            size = psf.getSize();
    }
    // Create a stack to hold all the images
    ImageStack stack = new ImageStack(size, size, max);
    for (int n = 1; n <= max; n++) stack.setPixels(new float[size * size], n);
    // Insert all the PSFs
    IJ.showStatus("Creating combined image ...");
    int imageNo = 0;
    double fraction = 1.0 / input.size();
    for (PSF psf : input) {
        double progress = imageNo * fraction;
        ImageStack psfStack = psf.psfStack;
        final int offsetXY = (psf.getSize() - size) / 2;
        final int offsetZ = psf.start;
        final int w = psf.getSize();
        final double weight = (1.0 * psf.psfSettings.nImages) / totalImages;
        final double increment = fraction / psfStack.getSize();
        for (int n = 1; n <= psfStack.getSize(); n++) {
            IJ.showProgress(progress += increment);
            // Get the data and adjust using the weight
            float[] psfData = ImageConverter.getData(psfStack.getProcessor(n));
            for (int i = 0; i < psfData.length; i++) psfData[i] *= weight;
            // Insert into the combined PSF
            ImageProcessor ip = stack.getProcessor(n + offsetZ);
            ip.copyBits(new FloatProcessor(w, w, psfData, null), offsetXY, offsetXY, Blitter.ADD);
        }
        imageNo++;
    }
    // IJ.showStatus("Normalising ...");
    // PSFCreator.normalise(stack, 1 + shift);
    IJ.showProgress(1);
    IJ.showStatus("");
    ImagePlus imp = Utils.display("Combined PSF", stack);
    imp.setSlice(1 + shift);
    imp.resetDisplayRange();
    imp.updateAndDraw();
    final double fwhm = getFWHM();
    imp.setProperty("Info", XmlUtils.toXML(new PSFSettings(imp.getSlice(), nmPerPixel, nmPerSlice, totalImages, fwhm)));
    Utils.log("%s : z-centre = %d, nm/Pixel = %s, nm/Slice = %s, %d images, FWHM = %s\n", imp.getTitle(), imp.getSlice(), Utils.rounded(nmPerPixel), Utils.rounded(nmPerSlice), totalImages, Utils.rounded(fwhm));
}
Also used : ImageProcessor(ij.process.ImageProcessor) ImageStack(ij.ImageStack) FloatProcessor(ij.process.FloatProcessor) ImagePlus(ij.ImagePlus) PSFSettings(gdsc.smlm.ij.settings.PSFSettings)

Example 25 with ImageStack

use of ij.ImageStack in project GDSC-SMLM by aherbert.

the class MedianFilter method run.

public void run(ImageProcessor ip) {
    long start = System.currentTimeMillis();
    ImageStack stack = imp.getImageStack();
    final int width = stack.getWidth();
    final int height = stack.getHeight();
    size = width * height;
    float[][] imageStack = new float[stack.getSize()][];
    float[] mean = new float[imageStack.length];
    // Get the mean for each frame and normalise the data using the mean
    ExecutorService threadPool = Executors.newFixedThreadPool(Prefs.getThreads());
    List<Future<?>> futures = new LinkedList<Future<?>>();
    counter = 0;
    IJ.showStatus("Calculating means...");
    for (int n = 1; n <= stack.getSize(); n++) {
        futures.add(threadPool.submit(new ImageNormaliser(stack, imageStack, mean, n)));
    }
    // Finish processing data
    Utils.waitForCompletion(futures);
    futures = new LinkedList<Future<?>>();
    counter = 0;
    IJ.showStatus("Calculating medians...");
    for (int i = 0; i < size; i += blockSize) {
        futures.add(threadPool.submit(new ImageGenerator(imageStack, mean, i, FastMath.min(i + blockSize, size))));
    }
    // Finish processing data
    Utils.waitForCompletion(futures);
    if (Utils.isInterrupted())
        return;
    if (subtract) {
        counter = 0;
        IJ.showStatus("Subtracting medians...");
        for (int n = 1; n <= stack.getSize(); n++) {
            futures.add(threadPool.submit(new ImageFilter(stack, imageStack, n)));
        }
        // Finish processing data
        Utils.waitForCompletion(futures);
    }
    // Update the image
    ImageStack outputStack = new ImageStack(stack.getWidth(), stack.getHeight(), stack.getSize());
    for (int n = 1; n <= stack.getSize(); n++) {
        outputStack.setPixels(imageStack[n - 1], n);
    }
    imp.setStack(outputStack);
    imp.updateAndDraw();
    IJ.showTime(imp, start, "Completed");
    long milliseconds = System.currentTimeMillis() - start;
    Utils.log(TITLE + " : Radius %d, Interval %d, Block size %d = %s, %s / frame", radius, interval, blockSize, Utils.timeToString(milliseconds), Utils.timeToString((double) milliseconds / imp.getStackSize()));
}
Also used : ImageStack(ij.ImageStack) LinkedList(java.util.LinkedList) ExecutorService(java.util.concurrent.ExecutorService) Future(java.util.concurrent.Future)

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