Search in sources :

Example 96 with FloatProcessor

use of ij.process.FloatProcessor 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 97 with FloatProcessor

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

the class SmoothImage method run.

/*
	 * (non-Javadoc)
	 * 
	 * @see ij.plugin.filter.PlugInFilter#run(ij.process.ImageProcessor)
	 */
public void run(ImageProcessor ip) {
    Rectangle bounds = ip.getRoi();
    // Crop to the ROI
    FloatProcessor fp = ip.crop().toFloat(0, null);
    float[] data = (float[]) fp.getPixels();
    MaximaSpotFilter filter = createSpotFilter();
    int width = fp.getWidth();
    int height = fp.getHeight();
    data = filter.preprocessData(data, width, height);
    //System.out.println(filter.getDescription());
    fp = new FloatProcessor(width, height, data);
    ip.insert(fp, bounds.x, bounds.y);
    //ip.resetMinAndMax();
    ip.setMinAndMax(fp.getMin(), fp.getMax());
}
Also used : FloatProcessor(ij.process.FloatProcessor) MaximaSpotFilter(gdsc.smlm.filters.MaximaSpotFilter) Rectangle(java.awt.Rectangle)

Example 98 with FloatProcessor

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

the class PCPALMAnalysis method normaliseCorrelation.

private FloatProcessor normaliseCorrelation(FloatProcessor corrIm, FloatProcessor corrW, double density) {
    float[] data = new float[corrIm.getWidth() * corrIm.getHeight()];
    float[] dataIm = (float[]) corrIm.getPixels();
    float[] dataW = (float[]) corrW.getPixels();
    // Square the density for normalisation
    density *= density;
    for (int i = 0; i < data.length; i++) {
        data[i] = (float) ((double) dataIm[i] / (density * dataW[i]));
    }
    FloatProcessor correlation = new FloatProcessor(corrIm.getWidth(), corrIm.getHeight(), data, null);
    return correlation;
}
Also used : FloatProcessor(ij.process.FloatProcessor)

Example 99 with FloatProcessor

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

the class TraceMolecules method buildCombinedImage.

private float[] buildCombinedImage(ImageSource source, Trace trace, float fitWidth, Rectangle bounds, double[] combinedNoise, boolean createStack) {
    final int w = source.getWidth();
    final int h = source.getHeight();
    // Get the coordinates and the spot bounds
    float[] centre = trace.getCentroid(CentroidMethod.SIGNAL_WEIGHTED);
    int minX = (int) Math.floor(centre[0] - fitWidth);
    int maxX = (int) Math.ceil(centre[0] + fitWidth);
    int minY = (int) Math.floor(centre[1] - fitWidth);
    int maxY = (int) Math.ceil(centre[1] + fitWidth);
    // Account for crops at the edge of the image
    minX = FastMath.max(0, minX);
    maxX = FastMath.min(w, maxX);
    minY = FastMath.max(0, minY);
    maxY = FastMath.min(h, maxY);
    int width = maxX - minX;
    int height = maxY - minY;
    if (width <= 0 || height <= 0) {
        // The centre must be outside the image width and height
        return null;
    }
    bounds.x = minX;
    bounds.y = minY;
    bounds.width = width;
    bounds.height = height;
    if (createStack)
        slices = new ImageStack(width, height);
    // Combine the images. Subtract the fitted background to zero the image.
    float[] data = new float[width * height];
    float sumBackground = 0;
    double noise = 0;
    for (PeakResult result : trace.getPoints()) {
        noise += result.noise * result.noise;
        float[] sourceData = source.get(result.getFrame(), bounds);
        final float background = result.getBackground();
        sumBackground += background;
        for (int i = 0; i < data.length; i++) {
            data[i] += sourceData[i] - background;
        }
        if (createStack)
            slices.addSlice(new FloatProcessor(width, height, sourceData, null));
    }
    if (createStack) {
        // Add a final image that is the average of the individual slices. This allows
        // it to be visualised in the same intensity scale.
        float[] data2 = Arrays.copyOf(data, data.length);
        final int size = slices.getSize();
        sumBackground /= size;
        for (int i = 0; i < data2.length; i++) data2[i] = sumBackground + data2[i] / size;
        slices.addSlice(new FloatProcessor(width, height, data2, null));
    }
    // Combined noise is the sqrt of the sum-of-squares
    combinedNoise[0] = Math.sqrt(noise);
    return data;
}
Also used : ImageStack(ij.ImageStack) FloatProcessor(ij.process.FloatProcessor) ClusterPoint(gdsc.core.clustering.ClusterPoint) PeakResult(gdsc.smlm.results.PeakResult)

Example 100 with FloatProcessor

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

the class TraceMolecules method createBilinearPlot.

private FloatProcessor createBilinearPlot(List<double[]> results, int w, int h) {
    FloatProcessor fp = new FloatProcessor(w, h);
    // Create lookup table that map the tested threshold values to a position in the image
    int[] xLookup = createLookup(tThresholds, settings.minTimeThreshold, w);
    int[] yLookup = createLookup(dThresholds, settings.minDistanceThreshold, h);
    origX = (settings.minTimeThreshold != 0) ? xLookup[1] : 0;
    origY = (settings.minDistanceThreshold != 0) ? yLookup[1] : 0;
    int gridWidth = tThresholds.length;
    int gridHeight = dThresholds.length;
    for (int y = 0, prevY = 0; y < gridHeight; y++) {
        for (int x = 0, prevX = 0; x < gridWidth; x++) {
            // Get the 4 flanking values
            double x1y1 = results.get(prevY * gridWidth + prevX)[2];
            double x1y2 = results.get(y * gridWidth + prevX)[2];
            double x2y1 = results.get(prevY * gridWidth + x)[2];
            double x2y2 = results.get(y * gridWidth + x)[2];
            // Pixel range
            int x1 = xLookup[x];
            int x2 = xLookup[x + 1];
            int y1 = yLookup[y];
            int y2 = yLookup[y + 1];
            double xRange = x2 - x1;
            double yRange = y2 - y1;
            for (int yy = y1; yy < y2; yy++) {
                double yFraction = (yy - y1) / yRange;
                for (int xx = x1; xx < x2; xx++) {
                    // Interpolate
                    double xFraction = (xx - x1) / xRange;
                    double v1 = x1y1 * (1 - xFraction) + x2y1 * xFraction;
                    double v2 = x1y2 * (1 - xFraction) + x2y2 * xFraction;
                    double value = v1 * (1 - yFraction) + v2 * yFraction;
                    fp.setf(xx, yy, (float) value);
                }
            }
            prevX = x;
        }
        prevY = y;
    }
    // Convert to absolute for easier visualisation
    float[] data = (float[]) fp.getPixels();
    for (int i = 0; i < data.length; i++) data[i] = Math.abs(data[i]);
    return fp;
}
Also used : FloatProcessor(ij.process.FloatProcessor) ClusterPoint(gdsc.core.clustering.ClusterPoint)

Aggregations

FloatProcessor (ij.process.FloatProcessor)174 ImageProcessor (ij.process.ImageProcessor)30 SeededTest (uk.ac.sussex.gdsc.test.junit5.SeededTest)26 Rectangle (java.awt.Rectangle)23 Test (org.junit.Test)22 ByteProcessor (ij.process.ByteProcessor)21 ShortProcessor (ij.process.ShortProcessor)20 Point (java.awt.Point)20 Test (org.junit.jupiter.api.Test)20 ImagePlus (ij.ImagePlus)19 ImageStack (ij.ImageStack)19 Future (java.util.concurrent.Future)12 ColorProcessor (ij.process.ColorProcessor)11 ArrayList (java.util.ArrayList)9 LinkedList (java.util.LinkedList)8 Fht (uk.ac.sussex.gdsc.core.ij.process.Fht)7 Point (mpicbg.models.Point)6 FHT2 (ij.process.FHT2)5 File (java.io.File)5 UniformRandomProvider (org.apache.commons.rng.UniformRandomProvider)5