Search in sources :

Example 26 with ImageProcessor

use of ij.process.ImageProcessor in project GDSC-SMLM by aherbert.

the class PulseActivationAnalysis method displayComposite.

private void displayComposite(ImageProcessor[] images, String name) {
    // We do not yet know the size
    ImageStack stack = null;
    for (int i = 0; i < images.length; i++) {
        ImageProcessor ip = images[i];
        if (stack == null)
            stack = new ImageStack(ip.getWidth(), ip.getHeight());
        ip.setColorModel(null);
        stack.addSlice("C" + (i + 1), ip);
    }
    // Create a composite
    ImagePlus imp = new ImagePlus(name, stack);
    imp.setDimensions(images.length, 1, 1);
    CompositeImage ci = new CompositeImage(imp, IJ.COMPOSITE);
    // Make it easier to see
    //ij.plugin.ContrastEnhancerce = new ij.plugin.ContrastEnhancer();
    //double saturated = 0.35;
    //ce.stretchHistogram(ci, saturated);
    autoAdjust(ci, ci.getProcessor());
    imp = WindowManager.getImage(name);
    if (imp != null && imp.isComposite()) {
        ci.setMode(imp.getCompositeMode());
        imp.setImage(ci);
        imp.getWindow().toFront();
    } else {
        ci.show();
        imp = ci;
    }
    if (WindowManager.getWindow("Channels") == null) {
        IJ.run("Channels Tool...");
        Window w = WindowManager.getWindow("Channels");
        if (w == null)
            return;
        Window w2 = imp.getWindow();
        if (w2 == null)
            return;
        java.awt.Point p = w2.getLocation();
        p.x += w2.getWidth();
        w.setLocation(p);
    }
}
Also used : Window(java.awt.Window) ImageProcessor(ij.process.ImageProcessor) ImageStack(ij.ImageStack) CompositeImage(ij.CompositeImage) ImagePlus(ij.ImagePlus)

Example 27 with ImageProcessor

use of ij.process.ImageProcessor in project GDSC-SMLM by aherbert.

the class FRCTest method canComputeMirrored.

@Test
public void canComputeMirrored() {
    // Sample lines through an image to create a structure.
    int size = 1024;
    double[][] data = new double[size * 2][];
    RandomGenerator r = new Well19937c(30051977);
    for (int x = 0, y = 0, y2 = size, i = 0; x < size; x++, y++, y2--) {
        data[i++] = new double[] { x + r.nextGaussian() * 5, y + r.nextGaussian() * 5 };
        data[i++] = new double[] { x + r.nextGaussian() * 5, y2 + r.nextGaussian() * 5 };
    }
    // Create 2 images
    Rectangle bounds = new Rectangle(0, 0, size, size);
    IJImagePeakResults i1 = createImage(bounds);
    IJImagePeakResults i2 = createImage(bounds);
    int[] indices = Utils.newArray(data.length, 0, 1);
    MathArrays.shuffle(indices, r);
    for (int i : indices) {
        IJImagePeakResults image = i1;
        i1 = i2;
        i2 = image;
        image.add((float) data[i][0], (float) data[i][1], 1);
    }
    i1.end();
    i2.end();
    ImageProcessor ip1 = i1.getImagePlus().getProcessor();
    ImageProcessor ip2 = i2.getImagePlus().getProcessor();
    // Test
    FRC frc = new FRC();
    FloatProcessor[] fft1, fft2;
    fft1 = frc.getComplexFFT(ip1);
    fft2 = frc.getComplexFFT(ip2);
    float[] dataA1 = (float[]) fft1[0].getPixels();
    float[] dataB1 = (float[]) fft1[1].getPixels();
    float[] dataA2 = (float[]) fft2[0].getPixels();
    float[] dataB2 = (float[]) fft2[1].getPixels();
    float[] numeratorE = new float[dataA1.length];
    float[] absFFT1E = new float[dataA1.length];
    float[] absFFT2E = new float[dataA1.length];
    FRC.compute(numeratorE, absFFT1E, absFFT2E, dataA1, dataB1, dataA2, dataB2);
    Assert.assertTrue("numeratorE", FRC.checkSymmetry(numeratorE, size));
    Assert.assertTrue("absFFT1E", FRC.checkSymmetry(absFFT1E, size));
    Assert.assertTrue("absFFT2E", FRC.checkSymmetry(absFFT2E, size));
    float[] numeratorA = new float[dataA1.length];
    float[] absFFT1A = new float[dataA1.length];
    float[] absFFT2A = new float[dataA1.length];
    FRC.computeMirrored(size, numeratorA, absFFT1A, absFFT2A, dataA1, dataB1, dataA2, dataB2);
    //for (int y=0, i=0; y<size; y++)
    //	for (int x=0; x<size; x++, i++)
    //	{
    //		System.out.printf("[%d,%d = %d] %f ?= %f\n", x, y, i, numeratorE[i], numeratorA[i]);
    //	}
    Assert.assertArrayEquals("numerator", numeratorE, numeratorA, 0);
    Assert.assertArrayEquals("absFFT1", absFFT1E, absFFT1A, 0);
    Assert.assertArrayEquals("absFFT2", absFFT2E, absFFT2A, 0);
    FRC.computeMirroredFast(size, numeratorA, absFFT1A, absFFT2A, dataA1, dataB1, dataA2, dataB2);
    // Check this.
    for (int y = 1; y < size; y++) for (int x = 1, i = y * size + 1; x < size; x++, i++) {
        Assert.assertEquals("numerator", numeratorE[i], numeratorA[i], 0);
        Assert.assertEquals("absFFT1", absFFT1E[i], absFFT1A[i], 0);
        Assert.assertEquals("absFFT2", absFFT2E[i], absFFT2A[i], 0);
    }
}
Also used : ImageProcessor(ij.process.ImageProcessor) FloatProcessor(ij.process.FloatProcessor) Rectangle(java.awt.Rectangle) Well19937c(org.apache.commons.math3.random.Well19937c) IJImagePeakResults(gdsc.smlm.ij.results.IJImagePeakResults) RandomGenerator(org.apache.commons.math3.random.RandomGenerator) Test(org.junit.Test)

Example 28 with ImageProcessor

use of ij.process.ImageProcessor in project GDSC-SMLM by aherbert.

the class FRCTest method computeMirroredIsFaster.

@Test
public void computeMirroredIsFaster() {
    // Sample lines through an image to create a structure.
    final int size = 2048;
    double[][] data = new double[size * 2][];
    RandomGenerator r = new Well19937c(30051977);
    for (int x = 0, y = 0, y2 = size, i = 0; x < size; x++, y++, y2--) {
        data[i++] = new double[] { x + r.nextGaussian() * 5, y + r.nextGaussian() * 5 };
        data[i++] = new double[] { x + r.nextGaussian() * 5, y2 + r.nextGaussian() * 5 };
    }
    // Create 2 images
    Rectangle bounds = new Rectangle(0, 0, size, size);
    IJImagePeakResults i1 = createImage(bounds);
    IJImagePeakResults i2 = createImage(bounds);
    int[] indices = Utils.newArray(data.length, 0, 1);
    MathArrays.shuffle(indices, r);
    for (int i : indices) {
        IJImagePeakResults image = i1;
        i1 = i2;
        i2 = image;
        image.add((float) data[i][0], (float) data[i][1], 1);
    }
    i1.end();
    i2.end();
    ImageProcessor ip1 = i1.getImagePlus().getProcessor();
    ImageProcessor ip2 = i2.getImagePlus().getProcessor();
    // Test
    FRC frc = new FRC();
    FloatProcessor[] fft1, fft2;
    fft1 = frc.getComplexFFT(ip1);
    fft2 = frc.getComplexFFT(ip2);
    final float[] dataA1 = (float[]) fft1[0].getPixels();
    final float[] dataB1 = (float[]) fft1[1].getPixels();
    final float[] dataA2 = (float[]) fft2[0].getPixels();
    final float[] dataB2 = (float[]) fft2[1].getPixels();
    final float[] numerator = new float[dataA1.length];
    final float[] absFFT1 = new float[dataA1.length];
    final float[] absFFT2 = new float[dataA1.length];
    TimingService ts = new TimingService(10);
    ts.execute(new MyTimingTask("compute") {

        public Object run(Object data) {
            FRC.compute(numerator, absFFT1, absFFT2, dataA1, dataB1, dataA2, dataB2);
            return null;
        }
    });
    ts.execute(new MyTimingTask("computeMirrored") {

        public Object run(Object data) {
            FRC.computeMirrored(size, numerator, absFFT1, absFFT2, dataA1, dataB1, dataA2, dataB2);
            return null;
        }
    });
    ts.execute(new MyTimingTask("computeMirroredFast") {

        public Object run(Object data) {
            FRC.computeMirroredFast(size, numerator, absFFT1, absFFT2, dataA1, dataB1, dataA2, dataB2);
            return null;
        }
    });
    ts.repeat(ts.getSize());
    ts.report();
}
Also used : FloatProcessor(ij.process.FloatProcessor) Rectangle(java.awt.Rectangle) Well19937c(org.apache.commons.math3.random.Well19937c) IJImagePeakResults(gdsc.smlm.ij.results.IJImagePeakResults) RandomGenerator(org.apache.commons.math3.random.RandomGenerator) ImageProcessor(ij.process.ImageProcessor) TimingService(gdsc.core.test.TimingService) Test(org.junit.Test)

Example 29 with ImageProcessor

use of ij.process.ImageProcessor in project GDSC-SMLM by aherbert.

the class SpotInspector method run.

/*
	 * (non-Javadoc)
	 * 
	 * @see ij.plugin.PlugIn#run(java.lang.String)
	 */
public void run(String arg) {
    SMLMUsageTracker.recordPlugin(this.getClass(), arg);
    if (MemoryPeakResults.isMemoryEmpty()) {
        IJ.error(TITLE, "No localisations in memory");
        return;
    }
    if (!showDialog())
        return;
    // Load the results
    results = ResultsManager.loadInputResults(inputOption, false);
    if (results == null || results.size() == 0) {
        IJ.error(TITLE, "No results could be loaded");
        IJ.showStatus("");
        return;
    }
    // Check if the original image is open
    ImageSource source = results.getSource();
    if (source == null) {
        IJ.error(TITLE, "Unknown original source image");
        return;
    }
    source = source.getOriginal();
    if (!source.open()) {
        IJ.error(TITLE, "Cannot open original source image: " + source.toString());
        return;
    }
    final float stdDevMax = getStandardDeviation(results);
    if (stdDevMax < 0) {
        // TODO - Add dialog to get the initial peak width
        IJ.error(TITLE, "Fitting configuration (for initial peak width) is not available");
        return;
    }
    // Rank spots
    rankedResults = new ArrayList<PeakResultRank>(results.size());
    final double a = results.getNmPerPixel();
    final double gain = results.getGain();
    final boolean emCCD = results.isEMCCD();
    for (PeakResult r : results.getResults()) {
        float[] score = getScore(r, a, gain, emCCD, stdDevMax);
        rankedResults.add(new PeakResultRank(r, score[0], score[1]));
    }
    Collections.sort(rankedResults);
    // Prepare results table. Get bias if necessary
    if (showCalibratedValues) {
        // Get a bias if required
        Calibration calibration = results.getCalibration();
        if (calibration.getBias() == 0) {
            ExtendedGenericDialog gd = new ExtendedGenericDialog(TITLE);
            gd.addMessage("Calibrated results requires a camera bias");
            gd.addNumericField("Camera_bias (ADUs)", calibration.getBias(), 2);
            gd.showDialog();
            if (!gd.wasCanceled()) {
                calibration.setBias(Math.abs(gd.getNextNumber()));
            }
        }
    }
    IJTablePeakResults table = new IJTablePeakResults(false, results.getName(), true);
    table.copySettings(results);
    table.setTableTitle(TITLE);
    table.setAddCounter(true);
    table.setShowCalibratedValues(showCalibratedValues);
    table.begin();
    // Add a mouse listener to jump to the frame for the clicked line
    textPanel = table.getResultsWindow().getTextPanel();
    // We must ignore old instances of this class from the mouse listeners
    id = ++currentId;
    textPanel.addMouseListener(this);
    // Add results to the table
    int n = 0;
    for (PeakResultRank rank : rankedResults) {
        rank.rank = n++;
        PeakResult r = rank.peakResult;
        table.add(r.getFrame(), r.origX, r.origY, r.origValue, r.error, r.noise, r.params, r.paramsStdDev);
    }
    table.end();
    if (plotScore || plotHistogram) {
        // Get values for the plots
        float[] xValues = null, yValues = null;
        double yMin, yMax;
        int spotNumber = 0;
        xValues = new float[rankedResults.size()];
        yValues = new float[xValues.length];
        for (PeakResultRank rank : rankedResults) {
            xValues[spotNumber] = spotNumber + 1;
            yValues[spotNumber++] = recoverScore(rank.score);
        }
        // Set the min and max y-values using 1.5 x IQR 
        DescriptiveStatistics stats = new DescriptiveStatistics();
        for (float v : yValues) stats.addValue(v);
        if (removeOutliers) {
            double lower = stats.getPercentile(25);
            double upper = stats.getPercentile(75);
            double iqr = upper - lower;
            yMin = FastMath.max(lower - iqr, stats.getMin());
            yMax = FastMath.min(upper + iqr, stats.getMax());
            IJ.log(String.format("Data range: %f - %f. Plotting 1.5x IQR: %f - %f", stats.getMin(), stats.getMax(), yMin, yMax));
        } else {
            yMin = stats.getMin();
            yMax = stats.getMax();
            IJ.log(String.format("Data range: %f - %f", yMin, yMax));
        }
        plotScore(xValues, yValues, yMin, yMax);
        plotHistogram(yValues, yMin, yMax);
    }
    // Extract spots into a stack
    final int w = source.getWidth();
    final int h = source.getHeight();
    final int size = 2 * radius + 1;
    ImageStack spots = new ImageStack(size, size, rankedResults.size());
    // To assist the extraction of data from the image source, process them in time order to allow 
    // frame caching. Then set the appropriate slice in the result stack
    Collections.sort(rankedResults, new Comparator<PeakResultRank>() {

        public int compare(PeakResultRank o1, PeakResultRank o2) {
            if (o1.peakResult.getFrame() < o2.peakResult.getFrame())
                return -1;
            if (o1.peakResult.getFrame() > o2.peakResult.getFrame())
                return 1;
            return 0;
        }
    });
    for (PeakResultRank rank : rankedResults) {
        PeakResult r = rank.peakResult;
        // Extract image
        // Note that the coordinates are relative to the middle of the pixel (0.5 offset)
        // so do not round but simply convert to int
        final int x = (int) (r.params[Gaussian2DFunction.X_POSITION]);
        final int y = (int) (r.params[Gaussian2DFunction.Y_POSITION]);
        // Extract a region but crop to the image bounds
        int minX = x - radius;
        int minY = y - radius;
        int maxX = FastMath.min(x + radius + 1, w);
        int maxY = FastMath.min(y + radius + 1, h);
        int padX = 0, padY = 0;
        if (minX < 0) {
            padX = -minX;
            minX = 0;
        }
        if (minY < 0) {
            padY = -minY;
            minY = 0;
        }
        int sizeX = maxX - minX;
        int sizeY = maxY - minY;
        float[] data = source.get(r.getFrame(), new Rectangle(minX, minY, sizeX, sizeY));
        // Prevent errors with missing data
        if (data == null)
            data = new float[sizeX * sizeY];
        ImageProcessor spotIp = new FloatProcessor(sizeX, sizeY, data, null);
        // Pad if necessary, i.e. the crop is too small for the stack
        if (padX > 0 || padY > 0 || sizeX < size || sizeY < size) {
            ImageProcessor spotIp2 = spotIp.createProcessor(size, size);
            spotIp2.insert(spotIp, padX, padY);
            spotIp = spotIp2;
        }
        int slice = rank.rank + 1;
        spots.setPixels(spotIp.getPixels(), slice);
        spots.setSliceLabel(Utils.rounded(rank.originalScore), slice);
    }
    source.close();
    ImagePlus imp = Utils.display(TITLE, spots);
    imp.setRoi((PointRoi) null);
    // Make bigger		
    for (int i = 10; i-- > 0; ) imp.getWindow().getCanvas().zoomIn(imp.getWidth() / 2, imp.getHeight() / 2);
}
Also used : DescriptiveStatistics(org.apache.commons.math3.stat.descriptive.DescriptiveStatistics) ImageStack(ij.ImageStack) FloatProcessor(ij.process.FloatProcessor) Rectangle(java.awt.Rectangle) Calibration(gdsc.smlm.results.Calibration) ExtendedGenericDialog(ij.gui.ExtendedGenericDialog) ImagePlus(ij.ImagePlus) PeakResult(gdsc.smlm.results.PeakResult) ImageProcessor(ij.process.ImageProcessor) IJTablePeakResults(gdsc.smlm.ij.results.IJTablePeakResults) ImageSource(gdsc.smlm.results.ImageSource)

Example 30 with ImageProcessor

use of ij.process.ImageProcessor in project GDSC-SMLM by aherbert.

the class SplitResults method splitResults.

private void splitResults(MemoryPeakResults results, ImageProcessor ip) {
    IJ.showStatus("Splitting " + Utils.pleural(results.size(), "result"));
    // Create an object mask
    ObjectAnalyzer objectAnalyzer = new ObjectAnalyzer(ip, false);
    final int maxx = ip.getWidth();
    final int maxy = ip.getHeight();
    final float scaleX = (float) results.getBounds().width / maxx;
    final float scaleY = (float) results.getBounds().height / maxy;
    // Create a results set for each object
    final int maxObject = objectAnalyzer.getMaxObject();
    MemoryPeakResults[] resultsSet = new MemoryPeakResults[maxObject + 1];
    for (int object = 0; object <= maxObject; object++) {
        MemoryPeakResults newResults = new MemoryPeakResults();
        newResults.copySettings(results);
        newResults.setName(results.getName() + " " + object);
        resultsSet[object] = newResults;
    }
    final int[] mask = objectAnalyzer.getObjectMask();
    if (showObjectMask) {
        ImageProcessor objectIp = (maxObject <= 255) ? new ByteProcessor(maxx, maxy) : new ShortProcessor(maxx, maxy);
        for (int i = 0; i < mask.length; i++) objectIp.set(i, mask[i]);
        ImagePlus imp = Utils.display(objectMask + " Objects", objectIp);
        imp.setDisplayRange(0, maxObject);
        imp.updateAndDraw();
    }
    // Process the results mapping them to their objects
    int i = 0;
    final int size = results.size();
    final int step = Utils.getProgressInterval(size);
    for (PeakResult result : results.getResults()) {
        if (++i % step == 0)
            IJ.showProgress(i, size);
        // Map to the mask objects
        final int object;
        int x = (int) (result.getXPosition() / scaleX);
        int y = (int) (result.getYPosition() / scaleY);
        if (x < 0 || x >= maxx || y < 0 || y >= maxy) {
            object = 0;
        } else {
            final int index = y * maxx + x;
            if (index < 0 || index >= mask.length)
                object = 0;
            else
                object = mask[index];
        }
        resultsSet[object].add(result);
    }
    IJ.showProgress(1);
    // Add the new results sets to memory
    i = 0;
    for (int object = (nonMaskDataset) ? 0 : 1; object <= maxObject; object++) {
        if (!resultsSet[object].isEmpty()) {
            MemoryPeakResults.addResults(resultsSet[object]);
            i++;
        }
    }
    IJ.showStatus("Split " + Utils.pleural(results.size(), "result") + " into " + Utils.pleural(i, "set"));
}
Also used : ByteProcessor(ij.process.ByteProcessor) ImageProcessor(ij.process.ImageProcessor) ObjectAnalyzer(gdsc.smlm.ij.utils.ObjectAnalyzer) MemoryPeakResults(gdsc.smlm.results.MemoryPeakResults) ImagePlus(ij.ImagePlus) PeakResult(gdsc.smlm.results.PeakResult) ShortProcessor(ij.process.ShortProcessor)

Aggregations

ImageProcessor (ij.process.ImageProcessor)33 FloatProcessor (ij.process.FloatProcessor)11 ImageStack (ij.ImageStack)10 ImagePlus (ij.ImagePlus)9 Rectangle (java.awt.Rectangle)9 IJImagePeakResults (gdsc.smlm.ij.results.IJImagePeakResults)5 PeakResult (gdsc.smlm.results.PeakResult)5 Point (java.awt.Point)5 LinkedList (java.util.LinkedList)4 Future (java.util.concurrent.Future)4 Calibration (gdsc.smlm.results.Calibration)3 ByteProcessor (ij.process.ByteProcessor)3 BasePoint (gdsc.core.match.BasePoint)2 ImageSource (gdsc.smlm.results.ImageSource)2 MemoryPeakResults (gdsc.smlm.results.MemoryPeakResults)2 MappedImageStack (ij.MappedImageStack)2 Plot2 (ij.gui.Plot2)2 Calibration (ij.measure.Calibration)2 LutLoader (ij.plugin.LutLoader)2 WindowOrganiser (ij.plugin.WindowOrganiser)2