Search in sources :

Example 6 with ImageStack

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

the class ResultsImageSampler method getSample.

/**
	 * Gets the sample image. The image is a stack of the samples with an overlay of the localisation positions. The
	 * info property is set with details of the localisations and the image is calibrated.
	 *
	 * @param nNo
	 *            the number of samples with no localisations
	 * @param nLow
	 *            the number of samples with low localisations
	 * @param nHigh
	 *            the number of samples with high localisations
	 * @return the sample image (could be null if no samples were made)
	 */
public ImagePlus getSample(int nNo, int nLow, int nHigh) {
    ImageStack out = new ImageStack(size, size);
    if (!isValid())
        return null;
    list.clearf();
    // empty
    for (int i : Random.sample(nNo, no.length, r)) list.add(ResultsSample.createEmpty(no[i]));
    // low
    for (int i : Random.sample(nLow, lower, r)) list.add(data[i]);
    // high
    for (int i : Random.sample(nHigh, upper, r)) list.add(data[i + lower]);
    if (list.isEmpty())
        return null;
    double nmPerPixel = 1;
    if (results.getCalibration() != null) {
        Calibration calibration = results.getCalibration();
        if (calibration.hasNmPerPixel()) {
            nmPerPixel = calibration.getNmPerPixel();
        }
    }
    // Sort descending by number in the frame
    ResultsSample[] sample = list.toArray(new ResultsSample[list.size()]);
    Arrays.sort(sample, rcc);
    int[] xyz = new int[3];
    Rectangle stackBounds = new Rectangle(stack.getWidth(), stack.getHeight());
    Overlay overlay = new Overlay();
    float[] ox = new float[10], oy = new float[10];
    StringBuilder sb = new StringBuilder();
    if (nmPerPixel == 1)
        sb.append("Sample X Y Z Signal\n");
    else
        sb.append("Sample X(nm) Y(nm) Z(nm) Signal\n");
    for (ResultsSample s : sample) {
        getXYZ(s.index, xyz);
        // Construct the region to extract
        Rectangle target = new Rectangle(xyz[0], xyz[1], size, size);
        target = target.intersection(stackBounds);
        if (target.width == 0 || target.height == 0)
            continue;
        // Extract the frame
        int slice = xyz[2];
        ImageProcessor ip = stack.getProcessor(slice);
        // Cut out the desired pixels (some may be blank if the block overruns the source image)
        ImageProcessor ip2 = ip.createProcessor(size, size);
        for (int y = 0; y < target.height; y++) for (int x = 0, i = y * size, index = (y + target.y) * ip.getWidth() + target.x; x < target.width; x++, i++, index++) {
            ip2.setf(i, ip.getf(index));
        }
        int size = s.size();
        if (size > 0) {
            int position = out.getSize() + 1;
            // Create an ROI with the localisations
            for (int i = 0; i < size; i++) {
                PeakResult p = s.list.get(i);
                ox[i] = p.getXPosition() - xyz[0];
                oy[i] = p.getYPosition() - xyz[1];
                sb.append(position).append(' ');
                sb.append(Utils.rounded(ox[i] * nmPerPixel)).append(' ');
                sb.append(Utils.rounded(oy[i] * nmPerPixel)).append(' ');
                // Z can be stored in the error field
                sb.append(Utils.rounded(p.error * nmPerPixel)).append(' ');
                sb.append(Utils.rounded(p.getSignal())).append('\n');
            }
            PointRoi roi = new PointRoi(ox, oy, size);
            roi.setPosition(position);
            overlay.add(roi);
        }
        out.addSlice(String.format("Frame=%d @ %d,%d px (n=%d)", slice, xyz[0], xyz[1], size), ip2.getPixels());
    }
    if (out.getSize() == 0)
        return null;
    ImagePlus imp = new ImagePlus("Sample", out);
    imp.setOverlay(overlay);
    // Note: Only the info property can be saved to a TIFF file
    imp.setProperty("Info", sb.toString());
    if (nmPerPixel != 1) {
        ij.measure.Calibration cal = new ij.measure.Calibration();
        cal.setUnit("nm");
        cal.pixelHeight = cal.pixelWidth = nmPerPixel;
        imp.setCalibration(cal);
    }
    return imp;
}
Also used : ImageStack(ij.ImageStack) Rectangle(java.awt.Rectangle) Calibration(gdsc.smlm.results.Calibration) ImagePlus(ij.ImagePlus) PeakResult(gdsc.smlm.results.PeakResult) ImageProcessor(ij.process.ImageProcessor) Overlay(ij.gui.Overlay) PointRoi(ij.gui.PointRoi)

Example 7 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 8 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 9 with ImageStack

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

the class DrawClusters 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
    MemoryPeakResults results = ResultsManager.loadInputResults(inputOption, false);
    if (results == null || results.size() == 0) {
        IJ.error(TITLE, "No results could be loaded");
        return;
    }
    // Get the traces
    Trace[] traces = TraceManager.convert(results);
    if (traces == null || traces.length == 0) {
        IJ.error(TITLE, "No traces could be loaded");
        return;
    }
    // Filter traces to a min size
    int maxFrame = 0;
    int count = 0;
    final int myMaxSize = (maxSize < minSize) ? Integer.MAX_VALUE : maxSize;
    final boolean myDrawLines = (myMaxSize < 2) ? false : drawLines;
    for (int i = 0; i < traces.length; i++) {
        if (expandToSingles)
            traces[i].expandToSingles();
        if (traces[i].size() >= minSize && traces[i].size() <= myMaxSize) {
            traces[count++] = traces[i];
            traces[i].sort();
            if (maxFrame < traces[i].getTail().getFrame())
                maxFrame = traces[i].getTail().getFrame();
        }
    }
    if (count == 0) {
        IJ.error(TITLE, "No traces achieved the size limits");
        return;
    }
    String msg = String.format(TITLE + ": %d / %s (%s)", count, Utils.pleural(traces.length, "trace"), Utils.pleural(results.size(), "localisation"));
    IJ.showStatus(msg);
    //Utils.log(msg);
    Rectangle bounds = results.getBounds(true);
    ImagePlus imp = WindowManager.getImage(title);
    boolean isUseStackPosition = useStackPosition;
    if (imp == null) {
        // Create a default image using 100 pixels as the longest edge
        double maxD = (bounds.width > bounds.height) ? bounds.width : bounds.height;
        int w, h;
        if (maxD == 0) {
            // Note that imageSize can be zero (for auto sizing)
            w = h = (imageSize == 0) ? 20 : imageSize;
        } else {
            // Note that imageSize can be zero (for auto sizing)
            if (imageSize == 0) {
                w = bounds.width;
                h = bounds.height;
            } else {
                w = (int) (imageSize * bounds.width / maxD);
                h = (int) (imageSize * bounds.height / maxD);
            }
        }
        ByteProcessor bp = new ByteProcessor(w, h);
        if (isUseStackPosition) {
            ImageStack stack = new ImageStack(w, h, maxFrame);
            for (int i = 1; i <= maxFrame; i++) // Do not clone as the image is empty
            stack.setPixels(bp.getPixels(), i);
            imp = Utils.display(TITLE, stack);
        } else
            imp = Utils.display(TITLE, bp);
        // Enlarge
        ImageWindow iw = imp.getWindow();
        for (int i = 9; i-- > 0 && iw.getWidth() < 500 && iw.getHeight() < 500; ) {
            iw.getCanvas().zoomIn(imp.getWidth() / 2, imp.getHeight() / 2);
        }
    } else {
        // Check if the image has enough frames for all the traces
        if (maxFrame > imp.getNFrames())
            isUseStackPosition = false;
    }
    final float xScale = (float) (imp.getWidth() / bounds.getWidth());
    final float yScale = (float) (imp.getHeight() / bounds.getHeight());
    // Create ROIs and store data to sort them
    Roi[] rois = new Roi[count];
    int[][] frames = (isUseStackPosition) ? new int[count][] : null;
    int[] indices = Utils.newArray(count, 0, 1);
    double[] values = new double[count];
    for (int i = 0; i < count; i++) {
        Trace trace = traces[i];
        int nPoints = trace.size();
        float[] xPoints = new float[nPoints];
        float[] yPoints = new float[nPoints];
        int j = 0;
        if (isUseStackPosition)
            frames[i] = new int[nPoints];
        for (PeakResult result : trace.getPoints()) {
            xPoints[j] = (result.getXPosition() - bounds.x) * xScale;
            yPoints[j] = (result.getYPosition() - bounds.y) * yScale;
            if (isUseStackPosition)
                frames[i][j] = result.getFrame();
            j++;
        }
        Roi roi;
        if (myDrawLines) {
            roi = new PolygonRoi(xPoints, yPoints, nPoints, Roi.POLYLINE);
            if (splineFit)
                ((PolygonRoi) roi).fitSpline();
        } else {
            roi = new PointRoi(xPoints, yPoints, nPoints);
            ((PointRoi) roi).setShowLabels(false);
        }
        rois[i] = roi;
        switch(sort) {
            case 0:
            default:
                break;
            case // Sort by ID
            1:
                values[i] = traces[i].getId();
                break;
            case // Sort by time
            2:
                values[i] = traces[i].getHead().getFrame();
                break;
            case // Sort by size descending
            3:
                values[i] = -traces[i].size();
                break;
            case // Sort by length descending
            4:
                values[i] = -roi.getLength();
                break;
            case // Mean Square Displacement
            5:
                values[i] = -traces[i].getMSD();
                break;
            case // Mean / Frame
            6:
                values[i] = -traces[i].getMeanPerFrame();
                break;
        }
    }
    if (sort > 0)
        Sort.sort(indices, values);
    // Draw the traces as ROIs on an overlay
    Overlay o = new Overlay();
    LUT lut = LUTHelper.createLUT(DrawClusters.lut);
    final double scale = 256.0 / count;
    if (isUseStackPosition) {
        // Add the tracks on the frames containing the results
        final boolean isHyperStack = imp.isDisplayedHyperStack();
        for (int i = 0; i < count; i++) {
            final int index = indices[i];
            final Color c = LUTHelper.getColour(lut, (int) (i * scale));
            final PolygonRoi roi = (PolygonRoi) rois[index];
            roi.setFillColor(c);
            roi.setStrokeColor(c);
            final FloatPolygon fp = roi.getNonSplineFloatPolygon();
            // For each frame in the track, add the ROI track and a point ROI for the current position
            for (int j = 0; j < frames[index].length; j++) {
                addToOverlay(o, (Roi) roi.clone(), isHyperStack, frames[index][j]);
                //PointRoi pointRoi = new PointRoi(pos.x + fp.xpoints[j], pos.y + fp.ypoints[j]);
                PointRoi pointRoi = new PointRoi(fp.xpoints[j], fp.ypoints[j]);
                pointRoi.setPointType(3);
                pointRoi.setFillColor(c);
                pointRoi.setStrokeColor(Color.black);
                addToOverlay(o, pointRoi, isHyperStack, frames[index][j]);
            }
        }
    } else {
        // Add the tracks as a single overlay
        for (int i = 0; i < count; i++) {
            final Roi roi = rois[indices[i]];
            roi.setStrokeColor(new Color(lut.getRGB((int) (i * scale))));
            o.add(roi);
        }
    }
    imp.setOverlay(o);
    IJ.showStatus(msg);
}
Also used : ByteProcessor(ij.process.ByteProcessor) ImageWindow(ij.gui.ImageWindow) Rectangle(java.awt.Rectangle) PeakResult(gdsc.smlm.results.PeakResult) PolygonRoi(ij.gui.PolygonRoi) MemoryPeakResults(gdsc.smlm.results.MemoryPeakResults) Overlay(ij.gui.Overlay) PointRoi(ij.gui.PointRoi) ImageStack(ij.ImageStack) Color(java.awt.Color) LUT(ij.process.LUT) ImagePlus(ij.ImagePlus) PolygonRoi(ij.gui.PolygonRoi) PointRoi(ij.gui.PointRoi) Roi(ij.gui.Roi) Trace(gdsc.smlm.results.Trace) FloatPolygon(ij.process.FloatPolygon)

Example 10 with ImageStack

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

the class SpotAnalysis method createProfile.

private void createProfile(ImagePlus imp, Rectangle bounds, double psfWidth, double blur) {
    areaBounds = bounds;
    this.imp = imp;
    area = bounds.width * bounds.height;
    clearSelectedFrames();
    // Get a profile through the images
    IJ.showStatus("Calculating raw profile");
    final int nSlices = imp.getStackSize();
    ImageStack rawSpot = new ImageStack(bounds.width, bounds.height, nSlices);
    double[][] profile = extractSpotProfile(imp, bounds, rawSpot);
    // Retain the existing display range
    double min = 0, max = Double.POSITIVE_INFINITY;
    if (rawImp != null) {
        min = rawImp.getDisplayRangeMin();
        max = rawImp.getDisplayRangeMax();
    }
    rawImp = showSpot(rawSpotTitle, rawSpot);
    if (max != Double.POSITIVE_INFINITY) {
        rawImp.setDisplayRange(min, max);
    }
    rawMean = profile[0];
    rawSd = profile[1];
    // Check if there are fitted results in memory
    addCandidateFrames(imp.getTitle());
    updateProfilePlots();
    if (blur > 0) {
        IJ.showStatus("Calculating blur ...");
        ImageStack stack = imp.getImageStack();
        ImageStack newStack = new ImageStack(stack.getWidth(), stack.getHeight(), stack.getSize());
        // Multi-thread the blur stage
        ExecutorService threadPool = Executors.newFixedThreadPool(Prefs.getThreads());
        List<Future<?>> futures = new LinkedList<Future<?>>();
        Utils.setShowProgress(false);
        blurCount = 0;
        // TODO - See if this is faster if processing multiple slices in each worker
        int slices = 5;
        for (int n = 1; n <= nSlices; n += slices) {
            futures.add(threadPool.submit(new BlurWorker(stack, n, slices, bounds, blur * psfWidth, newStack)));
        }
        IJ.showStatus("Calculating blur ... Finishing");
        Utils.waitForCompletion(futures);
        threadPool.shutdown();
        Utils.setShowProgress(false);
        IJ.showStatus("Calculating blur ... Drawing");
        ImageStack blurSpot = new ImageStack(bounds.width, bounds.height, nSlices);
        extractSpotProfile(new ImagePlus("Blur", newStack), bounds, blurSpot);
        // Retain the existing display range
        max = Double.POSITIVE_INFINITY;
        if (blurImp != null) {
            min = blurImp.getDisplayRangeMin();
            max = blurImp.getDisplayRangeMax();
        }
        blurImp = showSpot(blurSpotTitle, blurSpot);
        if (max != Double.POSITIVE_INFINITY) {
            blurImp.setDisplayRange(min, max);
        }
        IJ.showStatus("");
    } else {
        blurImp = null;
    }
    // Add a z-projection of the blur/original image
    ZProjector project = new ZProjector((blurImp == null) ? rawImp : blurImp);
    project.setMethod(ZProjector.AVG_METHOD);
    project.doProjection();
    showSpot(avgSpotTitle, project.getProjection().getImageStack());
    if (!candidateFrames.isEmpty())
        // Set the first candidate frame
        rawImp.setSlice(candidateFrames.get(0));
    else
        updateCurrentSlice(rawImp.getCurrentSlice());
    IJ.showStatus("");
}
Also used : ImageStack(ij.ImageStack) ExecutorService(java.util.concurrent.ExecutorService) Future(java.util.concurrent.Future) ImagePlus(ij.ImagePlus) Point(java.awt.Point) LinkedList(java.util.LinkedList) ZProjector(ij.plugin.ZProjector)

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