Search in sources :

Example 1 with Bureaucrat

use of ini.trakem2.utils.Bureaucrat in project TrakEM2 by trakem2.

the class Segmentation method magicWand.

public static Bureaucrat magicWand(final AreaWrapper aw, final Layer layer, final Rectangle srcRect, final int x_p_w, final int y_p_w, final List<Runnable> post_tasks, final boolean inverse, final boolean subtract) {
    // Capture pointers before they are set to null
    final AreaContainer ac = (AreaContainer) aw.getSource();
    final AffineTransform source_aff = aw.getSource().getAffineTransform();
    final Rectangle box = new Rectangle(x_p_w - Segmentation.fmp.width / 2, y_p_w - Segmentation.fmp.height / 2, Segmentation.fmp.width, Segmentation.fmp.height);
    Bureaucrat burro = Bureaucrat.create(new Worker.Task("Magic Wand") {

        public void exec() {
            // Capture image as large as the fmp width,height centered on x_p_w,y_p_w
            Utils.log2("fmp box is " + box);
            ImageProcessor ip = Patch.makeFlatImage(ImagePlus.GRAY8, layer, box, 1.0, (Collection) layer.getDisplayables(Patch.class, new Area(box), true), Color.black);
            // Apply wand
            Wand wand = new Wand(ip);
            String smode = WandToolOptions.getMode();
            int mode = Wand.LEGACY_MODE;
            if (null == smode) {
            } else if (smode.startsWith("4"))
                mode = Wand.FOUR_CONNECTED;
            else if (smode.startsWith("8"))
                mode = Wand.EIGHT_CONNECTED;
            // 8-bit image
            wand.autoOutline(ip.getWidth() / 2, ip.getHeight() / 2, WandToolOptions.getTolerance(), mode);
            if (wand.npoints > 0) {
                Area area = M.getArea(new PolygonRoi(wand.xpoints, wand.ypoints, wand.npoints, PolygonRoi.FREEROI));
                if (inverse) {
                    Area b = new Area(new Rectangle(0, 0, box.width, box.height));
                    b.subtract(area);
                    area = b;
                }
                // Compose an Area that is local to the AreaWrapper's area
                final AffineTransform aff = new AffineTransform(1, 0, 0, 1, box.x, box.y);
                try {
                    aff.preConcatenate(source_aff.createInverse());
                } catch (NoninvertibleTransformException nite) {
                    IJError.print(nite);
                    return;
                }
                area.transform(aff);
                if (subtract)
                    aw.getArea().subtract(area);
                else
                    aw.getArea().add(area);
                ac.calculateBoundingBox(layer);
                Display.repaint(layer);
            }
        }
    }, layer.getProject());
    if (null != post_tasks)
        for (Runnable task : post_tasks) burro.addPostTask(task);
    burro.goHaveBreakfast();
    return burro;
}
Also used : Rectangle(java.awt.Rectangle) Wand(ij.gui.Wand) Bureaucrat(ini.trakem2.utils.Bureaucrat) NoninvertibleTransformException(java.awt.geom.NoninvertibleTransformException) ImageProcessor(ij.process.ImageProcessor) PolygonRoi(ij.gui.PolygonRoi) Area(java.awt.geom.Area) AreaContainer(ini.trakem2.display.AreaContainer) AffineTransform(java.awt.geom.AffineTransform) Worker(ini.trakem2.utils.Worker) Collection(java.util.Collection) Patch(ini.trakem2.display.Patch)

Example 2 with Bureaucrat

use of ini.trakem2.utils.Bureaucrat in project TrakEM2 by trakem2.

the class Segmentation method fastMarching.

public static Bureaucrat fastMarching(final AreaWrapper aw, final Layer layer, final Rectangle srcRect, final int x_p_w, final int y_p_w, final List<Runnable> post_tasks) {
    // Capture pointers before they are set to null
    final AreaContainer ac = (AreaContainer) aw.getSource();
    final AffineTransform source_aff = aw.getSource().getAffineTransform();
    final Rectangle box = new Rectangle(x_p_w - Segmentation.fmp.width / 2, y_p_w - Segmentation.fmp.height / 2, Segmentation.fmp.width, Segmentation.fmp.height);
    Bureaucrat burro = Bureaucrat.create(new Worker.Task("Fast marching") {

        public void exec() {
            // Capture image as large as the fmp width,height centered on x_p_w,y_p_w
            Utils.log2("fmp box is " + box);
            ImagePlus imp = new ImagePlus("", Patch.makeFlatImage(ImagePlus.GRAY8, layer, box, 1.0, (Collection) layer.getDisplayables(Patch.class, new Area(box), true), Color.black));
            // Bandpass filter
            if (fmp.apply_bandpass_filter) {
                IJ.run(imp, "Bandpass Filter...", "filter_large=" + fmp.low_frequency_threshold + " filter_small=" + fmp.high_frequency_threshold + " suppress=None tolerance=5" + (fmp.autoscale_after_filtering ? " autoscale" : "") + (fmp.saturate_when_autoscaling ? " saturate" : ""));
            }
            // Setup seed point
            PointRoi roi = new PointRoi(box.width / 2, box.height / 2);
            imp.setRoi(roi);
            Utils.log2("imp: " + imp);
            Utils.log2("proi: " + imp.getRoi() + "    " + Utils.toString(new int[] { x_p_w - srcRect.x, y_p_w - srcRect.y }));
            // Setup state
            ImageContainer ic = new ImageContainer(imp);
            StateContainer state = new StateContainer();
            state.setROI(roi, ic.getWidth(), ic.getHeight(), ic.getImageCount(), imp.getCurrentSlice());
            state.setExpansionToInside(false);
            // Run FastMarching
            final FastMarching fm = new FastMarching(ic, null, state, true, fmp.fm_grey, fmp.fm_dist, fmp.apply_grey_value_erosion);
            final int max_iterations = fmp.max_iterations;
            final int iter_inc = fmp.iter_inc;
            for (int i = 0; i < max_iterations; i++) {
                if (Thread.currentThread().isInterrupted()) {
                    return;
                }
                if (!fm.step(iter_inc))
                    break;
            }
            // Extract ROI
            setTaskName("Adding area");
            final ArrayList<Coordinate> vc = fm.getStateContainer().getXYZ(false);
            if (0 == vc.size()) {
                Utils.log("No area growth.");
                return;
            }
            final Area area = new Area();
            Coordinate first = vc.remove(0);
            final Rectangle r = new Rectangle(first.x, first.y, 1, 1);
            int count = 0;
            // Scan and add line-wise
            for (final Coordinate c : vc) {
                count++;
                if (c.y == r.y && c.x == r.x + 1) {
                    // same line:
                    r.width += 1;
                    continue;
                } else {
                    // add previous one
                    area.add(new Area(r));
                }
                // start new line:
                r.x = c.x;
                r.y = c.y;
                r.width = 1;
                if (0 == count % 1024 && Thread.currentThread().isInterrupted()) {
                    return;
                }
            }
            // add last:
            area.add(new Area(r));
            /*
			// Trying from the image mask: JUST AS SLOW
			final byte[] b = (byte[]) fm.getStateContainer().getIPMask()[0].getPixels();
			final int w = imp.getWidth();
			for (int i=0; i<b.length; i++) {
				if (0 == b[i]) {
					r.x = i%w;
					r.y = i/w;
					area.add(new Area(r));
				}
			}
			*/
            /* // DOESN'T FILL?
			// Trying to just get the contour, and then filling holes
			for (final Coordinate c : fm.getStateContainer().getXYZ(true)) {
				r.x = c.x;
				r.y = c.y;
				area.add(new Area(r));
			}
			Polygon pol = new Polygon();
			final float[] coords = new float[6];
			for (PathIterator pit = area.getPathIterator(null); !pit.isDone(); ) {
				switch (pit.currentSegment(coords)) {
					case PathIterator.SEG_MOVETO:
					case PathIterator.SEG_LINETO:
						pol.addPoint((int)coords[0], (int)coords[1]);
						break;
					case PathIterator.SEG_CLOSE:
						area.add(new Area(pol));
						// prepare next:
						pol = new Polygon();
						break;
					default:
						Utils.log2("WARNING: unhandled seg type.");
						break;
				}
				pit.next();
				if (pit.isDone()) {
					break;
				}
			}
			*/
            // / FAILS because by now AreaWrapper's source is null
            // aw.add(area, new AffineTransform(1, 0, 0, 1, box.x, box.y));
            // Instead, compose an Area that is local to the AreaWrapper's area
            final AffineTransform aff = new AffineTransform(1, 0, 0, 1, box.x, box.y);
            try {
                aff.preConcatenate(source_aff.createInverse());
            } catch (NoninvertibleTransformException nite) {
                IJError.print(nite);
                return;
            }
            aw.getArea().add(area.createTransformedArea(aff));
            ac.calculateBoundingBox(layer);
            Display.repaint(layer);
        }
    }, layer.getProject());
    if (null != post_tasks)
        for (Runnable task : post_tasks) burro.addPostTask(task);
    burro.goHaveBreakfast();
    return burro;
}
Also used : FastMarching(levelsets.algorithm.FastMarching) Rectangle(java.awt.Rectangle) ArrayList(java.util.ArrayList) Bureaucrat(ini.trakem2.utils.Bureaucrat) ImagePlus(ij.ImagePlus) ImageContainer(levelsets.ij.ImageContainer) NoninvertibleTransformException(java.awt.geom.NoninvertibleTransformException) Area(java.awt.geom.Area) StateContainer(levelsets.ij.StateContainer) Coordinate(levelsets.algorithm.Coordinate) AreaContainer(ini.trakem2.display.AreaContainer) AffineTransform(java.awt.geom.AffineTransform) Worker(ini.trakem2.utils.Worker) PointRoi(ij.gui.PointRoi)

Example 3 with Bureaucrat

use of ini.trakem2.utils.Bureaucrat in project TrakEM2 by trakem2.

the class AlignTask method alignPatchesTask.

public static final Bureaucrat alignPatchesTask(final List<Patch> patches, final Set<Patch> fixedPatches) {
    if (0 == patches.size()) {
        Utils.log("Can't align zero patches.");
        return null;
    }
    final Worker worker = new Worker("Aligning images", false, true) {

        @Override
        public void run() {
            startedWorking();
            try {
                final int m = chooseAlignmentMode();
                if (-1 == m)
                    return;
                alignPatches(patches, fixedPatches, m);
                Display.repaint();
            } catch (final Throwable e) {
                IJError.print(e);
            } finally {
                finishedWorking();
            }
        }

        @Override
        public void cleanup() {
            patches.get(0).getLayer().getParent().undoOneStep();
        }
    };
    return Bureaucrat.createAndStart(worker, patches.get(0).getProject());
}
Also used : Worker(ini.trakem2.utils.Worker) Point(mpicbg.models.Point)

Example 4 with Bureaucrat

use of ini.trakem2.utils.Bureaucrat in project TrakEM2 by trakem2.

the class AlignTask method montageLayersTask.

/**
 * Montage each layer independently.
 *  Does NOT register layers to each other.
 *  Considers visible Patches only.
 */
public static final Bureaucrat montageLayersTask(final List<Layer> layers) {
    if (null == layers || layers.isEmpty())
        return null;
    return Bureaucrat.createAndStart(new Worker.Task("Montaging layers", true) {

        @Override
        public void exec() {
            final int m = chooseAlignmentMode();
            if (ELASTIC_BLOCK_CORRESPONDENCES == m) {
                final ElasticMontage.Param p = ElasticMontage.setup();
                if (p == null)
                    return;
                else {
                    try {
                        montageLayers(p, layers);
                    } catch (final Exception e) {
                        e.printStackTrace();
                        Utils.log("Exception during montaging layers.  Operation failed.");
                    }
                }
            } else if (LINEAR_PHASE_CORRELATION == m) {
                StitchingTEM.montageWithPhaseCorrelation(layers, this);
            } else if (LINEAR_SIFT_CORRESPONDENCES == m) {
                if (!Align.paramOptimize.setup("Montage Layers"))
                    return;
                final GenericDialog gd = new GenericDialog("Montage Layers: Miscellaneous");
                gd.addCheckbox("tiles are roughly in place", tilesAreInPlace);
                gd.addCheckbox("sloppy overlap test (fast)", sloppyOverlapTest);
                gd.addCheckbox("consider largest graph only", largestGraphOnly);
                gd.addCheckbox("hide tiles from non-largest graph", hideDisconnectedTiles);
                gd.addCheckbox("delete tiles from non-largest graph", deleteDisconnectedTiles);
                gd.showDialog();
                if (gd.wasCanceled())
                    return;
                tilesAreInPlace = gd.getNextBoolean();
                sloppyOverlapTest = gd.getNextBoolean();
                largestGraphOnly = gd.getNextBoolean();
                hideDisconnectedTiles = gd.getNextBoolean();
                deleteDisconnectedTiles = gd.getNextBoolean();
                final Align.ParamOptimize p = Align.paramOptimize.clone();
                montageLayers(p, layers, tilesAreInPlace, largestGraphOnly, hideDisconnectedTiles, deleteDisconnectedTiles, sloppyOverlapTest);
            } else
                Utils.log("Don't know how to align with mode " + m);
        }
    }, layers.get(0).getProject());
}
Also used : GenericDialog(ij.gui.GenericDialog) Worker(ini.trakem2.utils.Worker) NotEnoughDataPointsException(mpicbg.models.NotEnoughDataPointsException) NoninvertibleModelException(mpicbg.models.NoninvertibleModelException) NoninvertibleTransformException(java.awt.geom.NoninvertibleTransformException)

Example 5 with Bureaucrat

use of ini.trakem2.utils.Bureaucrat in project TrakEM2 by trakem2.

the class AlignTask method alignSelectionTask.

public static final Bureaucrat alignSelectionTask(final Selection selection) {
    final Worker worker = new Worker("Aligning selected images", false, true) {

        @Override
        public void run() {
            startedWorking();
            try {
                final int m = chooseAlignmentMode();
                if (-1 == m)
                    return;
                alignSelection(selection, m);
                Display.repaint(selection.getLayer());
            } catch (final Throwable e) {
                IJError.print(e);
            } finally {
                finishedWorking();
            }
        }

        @Override
        public void cleanup() {
            if (!selection.isEmpty())
                selection.getLayer().getParent().undoOneStep();
        }
    };
    return Bureaucrat.createAndStart(worker, selection.getProject());
}
Also used : Worker(ini.trakem2.utils.Worker) Point(mpicbg.models.Point)

Aggregations

Worker (ini.trakem2.utils.Worker)26 ArrayList (java.util.ArrayList)12 GenericDialog (ij.gui.GenericDialog)11 File (java.io.File)11 ImagePlus (ij.ImagePlus)10 Bureaucrat (ini.trakem2.utils.Bureaucrat)8 Rectangle (java.awt.Rectangle)8 Patch (ini.trakem2.display.Patch)7 NoninvertibleTransformException (java.awt.geom.NoninvertibleTransformException)7 IOException (java.io.IOException)7 HashSet (java.util.HashSet)7 Project (ini.trakem2.Project)6 FormatException (loci.formats.FormatException)6 DirectoryChooser (ij.io.DirectoryChooser)5 Layer (ini.trakem2.display.Layer)5 Point (java.awt.Point)5 TreeMap (java.util.TreeMap)5 Future (java.util.concurrent.Future)5 Displayable (ini.trakem2.display.Displayable)4 DBObject (ini.trakem2.persistence.DBObject)4