Search in sources :

Example 1 with ImageSource

use of uk.ac.sussex.gdsc.smlm.results.ImageSource in project GDSC-SMLM by aherbert.

the class PeakResultTableModelFrame method doSourceShowImage.

private void doSourceShowImage() {
    final PeakResultTableModel model = getModel();
    if (model == null) {
        return;
    }
    final ImageSource source = model.getSource();
    if (source == null) {
        return;
    }
    // Check if already open
    final ImagePlus imp = WindowManager.getImage(source.getName());
    if (imp != null) {
        imp.getWindow().toFront();
        return;
    }
    // Check if an ImageJ image source
    if (source instanceof IJImageSource) {
        final IJImageSource imageSource = (IJImageSource) source;
        final String path = imageSource.getPath();
        if (path != null && new File(path).exists()) {
            IJ.showStatus("Opening image ...");
            IJ.open(path);
            IJ.showStatus("");
        } else {
            IJ.log("Cannot find the image source: " + path);
        }
        return;
    }
    // Open a SeriesImageSource.
    if (source instanceof SeriesImageSource) {
        final SeriesImageSource imageSource = (SeriesImageSource) source;
        // No memory buffer
        imageSource.setBufferLimit(0);
        imageSource.setReadHint(ReadHint.NONSEQUENTIAL);
        if (!source.open()) {
            IJ.log("Cannot open the series image source");
            return;
        }
        new TiffSeriesVirtualStack(imageSource).show();
    }
}
Also used : IJImageSource(uk.ac.sussex.gdsc.smlm.ij.IJImageSource) SeriesImageSource(uk.ac.sussex.gdsc.smlm.ij.SeriesImageSource) ImageSource(uk.ac.sussex.gdsc.smlm.results.ImageSource) IJImageSource(uk.ac.sussex.gdsc.smlm.ij.IJImageSource) SeriesImageSource(uk.ac.sussex.gdsc.smlm.ij.SeriesImageSource) ImagePlus(ij.ImagePlus) File(java.io.File) TiffSeriesVirtualStack(uk.ac.sussex.gdsc.smlm.ij.plugins.TiffSeriesViewer.TiffSeriesVirtualStack)

Example 2 with ImageSource

use of uk.ac.sussex.gdsc.smlm.results.ImageSource in project GDSC-SMLM by aherbert.

the class PeakResultTableModelFrame method doSourceOverlay.

private void doSourceOverlay() {
    final PeakResultTableModel model = getModel();
    if (model == null) {
        return;
    }
    final PeakResult[] list = table.getSelectedData();
    if (list.length == 0) {
        return;
    }
    final ImageSource source = model.getSource();
    if (source == null) {
        return;
    }
    final String title = source.getOriginal().getName();
    final ImagePlus imp = WindowManager.getImage(title);
    if (imp == null) {
        return;
    }
    // Assumes 3D stack (no channel/time)
    if (imp.getNDimensions() > 3) {
        return;
    }
    try {
        final TypeConverter<DistanceUnit> converter = CalibrationHelper.getDistanceConverter(model.getCalibration(), DistanceUnit.PIXEL);
        final Overlay o = new Overlay();
        if (list.length == 1) {
            final PeakResult p = list[0];
            final PointRoi roi = new OffsetPointRoi(converter.convert(p.getXPosition()), converter.convert(p.getYPosition()));
            roi.setPointType(3);
            roi.setPosition(p.getFrame());
            o.add(roi);
        } else {
            Arrays.sort(list, FramePeakResultComparator.INSTANCE);
            final TFloatArrayList ox = new TFloatArrayList(list.length);
            final TFloatArrayList oy = new TFloatArrayList(list.length);
            int frame = list[0].getFrame() - 1;
            for (int i = 0; i < list.length; i++) {
                if (frame != list[i].getFrame()) {
                    if (ox.size() > 0) {
                        final PointRoi roi = new OffsetPointRoi(ox.toArray(), oy.toArray());
                        roi.setPointType(3);
                        roi.setPosition(frame);
                        ox.resetQuick();
                        oy.resetQuick();
                        o.add(roi);
                    }
                    frame = list[i].getFrame();
                }
                ox.add(converter.convert(list[i].getXPosition()));
                oy.add(converter.convert(list[i].getYPosition()));
            }
            if (ox.size() > 0) {
                final PointRoi roi = new OffsetPointRoi(ox.toArray(), oy.toArray());
                roi.setPointType(3);
                roi.setPosition(frame);
                o.add(roi);
            }
        }
        imp.setOverlay(o);
        final PeakResult p = list[0];
        imp.setSlice(p.getFrame());
        ImageJUtils.adjustSourceRect(imp, 0, (int) converter.convert(p.getXPosition()), (int) converter.convert(p.getYPosition()));
        imp.getWindow().toFront();
    } catch (final ConversionException ex) {
    // Ignore
    }
}
Also used : ConversionException(uk.ac.sussex.gdsc.core.data.utils.ConversionException) OffsetPointRoi(uk.ac.sussex.gdsc.core.ij.gui.OffsetPointRoi) ImagePlus(ij.ImagePlus) PeakResult(uk.ac.sussex.gdsc.smlm.results.PeakResult) ReadHint(uk.ac.sussex.gdsc.smlm.results.ImageSource.ReadHint) TFloatArrayList(gnu.trove.list.array.TFloatArrayList) ImageSource(uk.ac.sussex.gdsc.smlm.results.ImageSource) IJImageSource(uk.ac.sussex.gdsc.smlm.ij.IJImageSource) SeriesImageSource(uk.ac.sussex.gdsc.smlm.ij.SeriesImageSource) Overlay(ij.gui.Overlay) DistanceUnit(uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.DistanceUnit) PointRoi(ij.gui.PointRoi) OffsetPointRoi(uk.ac.sussex.gdsc.core.ij.gui.OffsetPointRoi)

Example 3 with ImageSource

use of uk.ac.sussex.gdsc.smlm.results.ImageSource in project GDSC-SMLM by aherbert.

the class PeakFit method setup.

@Override
public int setup(String arg, ImagePlus imp) {
    SmlmUsageTracker.recordPlugin(this.getClass(), arg);
    pluginFlags = FLAGS;
    extraOptions = ImageJUtils.isExtraOptions();
    maximaIdentification = StringUtils.contains(arg, "spot");
    fitMaxima = StringUtils.contains(arg, "maxima");
    simpleFit = StringUtils.contains(arg, "simple");
    final boolean runSeries = StringUtils.contains(arg, "series");
    ImageSource imageSource = null;
    if (fitMaxima) {
        // The image source will be found from the peak results.
        if (!showMaximaDialog()) {
            return DONE;
        }
        final MemoryPeakResults localResults = ResultsManager.loadInputResults(settings.inputOption, false, DistanceUnit.PIXEL);
        if (localResults == null || localResults.size() == 0) {
            IJ.error(TITLE, "No results could be loaded");
            return DONE;
        }
        if (settings.fitAcrossAllFrames) {
            // Allow the user to select a different image. The source will be set as per the
            // main fit routine from the image (imp).
            singleFrame = 0;
        } else {
            // Check for single frame
            singleFrame = getSingleFrame(localResults);
            // Forces the maxima to be used with their original source.
            imp = null;
            imageSource = localResults.getSource();
            pluginFlags |= NO_IMAGE_REQUIRED;
        }
    } else if (runSeries) {
        imp = null;
        // Select input folder
        final String inputDirectory = IJ.getDirectory("Select image series ...");
        if (inputDirectory == null) {
            return DONE;
        }
        // Load input series ...
        SeriesOpener series;
        if (extraOptions) {
            final String helpKey = maximaIdentification ? "spot-finder-series" : "peak-fit-series";
            series = SeriesOpener.create(inputDirectory, true, HelpUrls.getUrl(helpKey));
        } else {
            series = new SeriesOpener(inputDirectory);
        }
        if (series.getNumberOfImages() == 0) {
            IJ.error(TITLE, "No images in the selected directory:\n" + inputDirectory);
            return DONE;
        }
        final SeriesImageSource seriesImageSource = new SeriesImageSource(getName(series.getImageList()), series);
        // TrackProgress logging is very verbose if the series has many images
        // Status is used only when reading TIFF info.
        // seriesImageSource.setTrackProgress(SimpleImageJTrackProgress.getInstance());
        seriesImageSource.setTrackProgress(new TrackProgressAdaptor() {

            @Override
            public void status(String format, Object... args) {
                ImageJUtils.showStatus(() -> String.format(format, args));
            }
        });
        imageSource = seriesImageSource;
        pluginFlags |= NO_IMAGE_REQUIRED;
    }
    // If the image source has not been set then use the input image
    if (imageSource == null) {
        if (imp == null) {
            IJ.noImage();
            return DONE;
        }
        // Check it is not a previous result
        if (imp.getTitle().endsWith(ImageJImagePeakResults.IMAGE_SUFFIX)) {
            IJImageSource ijImageSource = null;
            // Check the image to see if it has an image source XML structure in the info property
            final Object o = imp.getProperty("Info");
            final Pattern pattern = Pattern.compile("Source: (<.*IJImageSource>.*<.*IJImageSource>)", Pattern.DOTALL);
            final Matcher match = pattern.matcher((o == null) ? "" : o.toString());
            if (match.find()) {
                final ImageSource tmpSource = ImageSource.fromXml(match.group(1));
                if (tmpSource instanceof IJImageSource) {
                    ijImageSource = (IJImageSource) tmpSource;
                    if (!ijImageSource.open()) {
                        ijImageSource = null;
                    } else {
                        imp = WindowManager.getImage(ijImageSource.getName());
                    }
                }
            }
            if (ijImageSource == null) {
                // Look for a parent using the title
                final String parentTitle = imp.getTitle().substring(0, imp.getTitle().length() - ImageJImagePeakResults.IMAGE_SUFFIX.length() - 1);
                final ImagePlus parentImp = WindowManager.getImage(parentTitle);
                if (parentImp != null) {
                    ijImageSource = new IJImageSource(parentImp);
                    imp = parentImp;
                }
            }
            String message = "The selected image may be a previous fit result";
            if (ijImageSource != null) {
                if (!TextUtils.isNullOrEmpty(ijImageSource.getName())) {
                    message += " of: \n \n" + ijImageSource.getName();
                }
                message += " \n \nFit the parent?";
            } else {
                message += " \n \nDo you want to continue?";
            }
            final YesNoCancelDialog d = new YesNoCancelDialog(null, TITLE, message);
            if (ijImageSource == null) {
                if (!d.yesPressed()) {
                    return DONE;
                }
            } else {
                if (d.yesPressed()) {
                    imageSource = ijImageSource;
                }
                if (d.cancelPressed()) {
                    return DONE;
                }
            }
        }
        if (imageSource == null) {
            try {
                imageSource = new IJImageSource(imp);
            } catch (final IllegalArgumentException ex) {
                // This can happen if the image has an origin not in integer pixels
                // e.g. the plugin is run on a plot
                IJ.error(TITLE, "Error using image: " + imp.getTitle() + "\n \n" + ex.getMessage());
                return DONE;
            }
        }
    }
    time = -1;
    if (!initialiseImage(imageSource, getBounds(imp), false)) {
        IJ.error(TITLE, "Failed to initialise the source image: " + imageSource.getName());
        return DONE;
    }
    final int flags = showDialog(imp);
    if ((flags & DONE) == 0) {
        initialiseFitting();
    }
    return flags;
}
Also used : Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) SeriesImageSource(uk.ac.sussex.gdsc.smlm.ij.SeriesImageSource) SeriesOpener(uk.ac.sussex.gdsc.core.ij.SeriesOpener) ImagePlus(ij.ImagePlus) TrackProgressAdaptor(uk.ac.sussex.gdsc.core.logging.TrackProgressAdaptor) IJImageSource(uk.ac.sussex.gdsc.smlm.ij.IJImageSource) MemoryPeakResults(uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults) YesNoCancelDialog(ij.gui.YesNoCancelDialog) ImageSource(uk.ac.sussex.gdsc.smlm.results.ImageSource) AggregatedImageSource(uk.ac.sussex.gdsc.smlm.results.AggregatedImageSource) InterlacedImageSource(uk.ac.sussex.gdsc.smlm.results.InterlacedImageSource) SeriesImageSource(uk.ac.sussex.gdsc.smlm.ij.SeriesImageSource) IJImageSource(uk.ac.sussex.gdsc.smlm.ij.IJImageSource)

Example 4 with ImageSource

use of uk.ac.sussex.gdsc.smlm.results.ImageSource in project GDSC-SMLM by aherbert.

the class FailCountManager method createData.

/**
 * Creates the fail count data by running fitting on the current image.
 */
private void createData() {
    final ImagePlus imp = WindowManager.getCurrentImage();
    if (imp == null) {
        IJ.error(TITLE, "No image for fitting");
        return;
    }
    if (!showCreateDataDialog(imp)) {
        return;
    }
    // Get the current fit configuration
    final Configuration c = new Configuration();
    if (!c.showDialog(false)) {
        return;
    }
    final FitEngineConfiguration fitConfig = c.getFitEngineConfiguration();
    // Update stopping criteria.
    fitConfig.resetFailCounter();
    fitConfig.setFailuresLimit(settings.getFailCountLimit());
    final ImageSource source = new IJImageSource(imp);
    final PeakFit peakFit = new PeakFit(fitConfig, ResultsSettings.getDefaultInstance());
    peakFit.setResultsSuffix("(FailCountAnalysis)");
    if (!peakFit.initialise(source, null, false)) {
        IJ.error(TITLE, "Failed to initialise the fit engine");
        return;
    }
    final FitEngine engine = peakFit.createFitEngine();
    final Rectangle bounds = new Rectangle(source.getWidth(), source.getHeight());
    // Run
    final int totalFrames = Math.min(source.getFrames(), settings.getMaxFrames());
    final int step = ImageJUtils.getProgressInterval(totalFrames);
    IJ.showProgress(0);
    boolean shutdown = false;
    int slice = 0;
    final LocalList<ParameterisedFitJob> jobs = new LocalList<>(totalFrames);
    while (!shutdown && slice < totalFrames) {
        final float[] data = source.next();
        if (data == null) {
            break;
        }
        if (slice++ % step == 0) {
            final int frames = slice;
            if (ImageJUtils.showStatus(() -> "Fitting slice: " + frames + " / " + totalFrames)) {
                IJ.showProgress(slice, totalFrames);
            }
        }
        final ParameterisedFitJob job = createJob(source.getStartFrameNumber(), data, bounds);
        jobs.push(job);
        engine.run(job);
        shutdown = escapePressed();
    }
    ImageJUtils.showStatus("Extracting fail count data");
    engine.end(shutdown);
    IJ.showProgress(1);
    source.close();
    // Extract the fail count data
    final LocalList<FailCountData> failCountData = new LocalList<>(jobs.size());
    for (int i = 0; i < jobs.size(); i++) {
        final ParameterisedFitJob job = jobs.unsafeGet(i);
        if (job.getStatus() == Status.FINISHED) {
            final FitParameters fitParams = job.getFitParameters();
            // Find the last success
            boolean[] results = fitParams.pass;
            int end = results.length - 1;
            while (end > 0 && !results[end]) {
                end--;
            }
            // Add on the configured fail count limit
            end = Math.min(end + 1 + settings.getFailCountLimit(), results.length);
            results = Arrays.copyOf(results, end);
            failCountData.add(new FailCountData(job.getSlice(), results));
        }
    }
    failCountDataRef.set(failCountData);
    ImageJUtils.showStatus("");
    // Save for the future
    if (settings.getSaveAfterFitting()) {
        saveData();
    }
}
Also used : FitParameters(uk.ac.sussex.gdsc.smlm.engine.FitParameters) ParameterisedFitJob(uk.ac.sussex.gdsc.smlm.engine.ParameterisedFitJob) FitEngineConfiguration(uk.ac.sussex.gdsc.smlm.engine.FitEngineConfiguration) FitEngineConfiguration(uk.ac.sussex.gdsc.smlm.engine.FitEngineConfiguration) Rectangle(java.awt.Rectangle) ImagePlus(ij.ImagePlus) IJImageSource(uk.ac.sussex.gdsc.smlm.ij.IJImageSource) LocalList(uk.ac.sussex.gdsc.core.utils.LocalList) FitEngine(uk.ac.sussex.gdsc.smlm.engine.FitEngine) ImageSource(uk.ac.sussex.gdsc.smlm.results.ImageSource) IJImageSource(uk.ac.sussex.gdsc.smlm.ij.IJImageSource)

Example 5 with ImageSource

use of uk.ac.sussex.gdsc.smlm.results.ImageSource in project GDSC-SMLM by aherbert.

the class CameraModelManager method runFilterImage.

private void runFilterImage() {
    // Select an image
    GenericDialog gd = new GenericDialog(TITLE);
    final String[] list = ImageJUtils.getImageList(ImageJUtils.GREY_SCALE);
    gd.addChoice("Image", list, pluginSettings.getImage());
    gd.showDialog();
    if (gd.wasCanceled()) {
        return;
    }
    final String image = gd.getNextChoice();
    pluginSettings.setImage(image);
    final ImagePlus imp = WindowManager.getImage(image);
    if (imp == null) {
        IJ.error(TITLE, "Failed to find image: " + image);
        return;
    }
    // Select the model
    gd = new GenericDialog(TITLE);
    final String[] models = listCameraModels(false);
    gd.addChoice("Model", models, pluginSettings.getSelected());
    gd.addHelp(HelpUrls.getUrl("camera-model-manager-filter"));
    gd.showDialog();
    if (gd.wasCanceled()) {
        return;
    }
    final String name = gd.getNextChoice();
    pluginSettings.setSelected(name);
    CameraModel cameraModel = load(name);
    if (cameraModel == null) {
        IJ.error(TITLE, "Failed to find camera data for model: " + name);
        return;
    }
    // Crop the model if appropriate
    try {
        Rectangle bounds;
        try {
            bounds = IJImageSource.getBounds(imp);
        } catch (final IllegalArgumentException ex) {
            bounds = new Rectangle(pluginSettings.getOriginX(), pluginSettings.getOriginY(), imp.getWidth(), imp.getHeight());
        }
        cameraModel = PeakFit.cropCameraModel(cameraModel, bounds, null, false);
    } catch (final IllegalArgumentException ex) {
        IJ.error(TITLE, ex.getMessage());
        return;
    }
    final Rectangle bounds = cameraModel.getBounds();
    pluginSettings.setOriginX(bounds.x);
    pluginSettings.setOriginY(bounds.y);
    // Reset origin for fast filtering
    cameraModel = cameraModel.copy();
    cameraModel.setOrigin(0, 0);
    // Filter all the frames
    final ImageSource source = new IJImageSource(imp);
    if (!source.open()) {
        IJ.error(TITLE, "Cannot open image: " + image);
    }
    final ImageStack stack = new ImageStack(imp.getWidth(), imp.getHeight());
    for (float[] data = source.next(); data != null; data = source.next()) {
        cameraModel.removeBiasAndGain(data);
        stack.addSlice(null, data);
    }
    final ImagePlus imp2 = new ImagePlus(imp.getTitle() + " Filtered", stack);
    imp2.copyScale(imp);
    imp2.show();
}
Also used : IJImageSource(uk.ac.sussex.gdsc.smlm.ij.IJImageSource) CameraModel(uk.ac.sussex.gdsc.smlm.model.camera.CameraModel) PerPixelCameraModel(uk.ac.sussex.gdsc.smlm.model.camera.PerPixelCameraModel) ImageStack(ij.ImageStack) GenericDialog(ij.gui.GenericDialog) ExtendedGenericDialog(uk.ac.sussex.gdsc.core.ij.gui.ExtendedGenericDialog) Rectangle(java.awt.Rectangle) ImageSource(uk.ac.sussex.gdsc.smlm.results.ImageSource) IJImageSource(uk.ac.sussex.gdsc.smlm.ij.IJImageSource) ImagePlus(ij.ImagePlus)

Aggregations

ImageSource (uk.ac.sussex.gdsc.smlm.results.ImageSource)8 IJImageSource (uk.ac.sussex.gdsc.smlm.ij.IJImageSource)7 ImagePlus (ij.ImagePlus)6 Rectangle (java.awt.Rectangle)4 SeriesImageSource (uk.ac.sussex.gdsc.smlm.ij.SeriesImageSource)4 ImageStack (ij.ImageStack)3 PointRoi (ij.gui.PointRoi)2 ImageProcessor (ij.process.ImageProcessor)2 HistogramPlotBuilder (uk.ac.sussex.gdsc.core.ij.HistogramPlot.HistogramPlotBuilder)2 ExtendedGenericDialog (uk.ac.sussex.gdsc.core.ij.gui.ExtendedGenericDialog)2 OffsetPointRoi (uk.ac.sussex.gdsc.core.ij.gui.OffsetPointRoi)2 StoredDataStatistics (uk.ac.sussex.gdsc.core.utils.StoredDataStatistics)2 DistanceUnit (uk.ac.sussex.gdsc.smlm.data.config.UnitProtos.DistanceUnit)2 FitConfiguration (uk.ac.sussex.gdsc.smlm.engine.FitConfiguration)2 FitEngine (uk.ac.sussex.gdsc.smlm.engine.FitEngine)2 TFloatArrayList (gnu.trove.list.array.TFloatArrayList)1 IJ (ij.IJ)1 WindowManager (ij.WindowManager)1 GenericDialog (ij.gui.GenericDialog)1 Overlay (ij.gui.Overlay)1