Search in sources :

Example 21 with Filter

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

the class Loader method scaleImage.

public static ImageProcessor scaleImage(final ImagePlus imp, double mag, final boolean quality) {
    if (mag > 1)
        mag = 1;
    ImageProcessor ip = imp.getProcessor();
    if (Math.abs(mag - 1) < 0.000001)
        return ip;
    // else, make a properly scaled image:
    // - gaussian blurred for best quality when resizing with nearest neighbor
    // - direct nearest neighbor otherwise
    final int w = ip.getWidth();
    final int h = ip.getHeight();
    // TODO releseToFit !
    if (quality) {
        // apply proper gaussian filter
        // sigma = sqrt(level^2 - 0.5^2)
        final double sigma = Math.sqrt(Math.pow(2, getMipMapLevel(mag, Math.max(imp.getWidth(), imp.getHeight()))) - 0.25);
        ip = new FloatProcessorT2(w, h, ImageFilter.computeGaussianFastMirror(new FloatArray2D((float[]) ip.convertToFloat().getPixels(), w, h), (float) sigma).data, ip.getDefaultColorModel(), ip.getMin(), ip.getMax());
        // better while float
        ip = ip.resize((int) (w * mag), (int) (h * mag));
        return Utils.convertTo(ip, imp.getType(), false);
    } else {
        return ip.resize((int) (w * mag), (int) (h * mag));
    }
}
Also used : ImageProcessor(ij.process.ImageProcessor) FloatArray2D(mpi.fruitfly.math.datastructures.FloatArray2D) FloatProcessorT2(ini.trakem2.imaging.FloatProcessorT2)

Example 22 with Filter

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

the class TMLHandler method makeLayerThing.

private LayerThing makeLayerThing(String type, final HashMap<String, String> ht_attributes) {
    try {
        type = type.toLowerCase();
        if (0 == type.indexOf("t2_")) {
            type = type.substring(3);
        }
        // long id = -1;
        // final String sid = ht_attributes.get("id");
        // if (null != sid) id = Long.parseLong(sid);
        long oid = -1;
        final String soid = ht_attributes.get("oid");
        if (null != soid)
            oid = Long.parseLong(soid);
        if (type.equals("node")) {
            if (null == last_tree) {
                throw new NullPointerException("Can't create a node for null last_tree!");
            }
            final Node<?> node = last_tree.newNode(ht_attributes);
            taggables.add(node);
            // Put node into the list of nodes with that layer id, to update to proper Layer pointer later
            final long ndlid = Long.parseLong(ht_attributes.get("lid"));
            List<Node<?>> list = node_layer_table.get(ndlid);
            if (null == list) {
                list = new ArrayList<Node<?>>();
                node_layer_table.put(ndlid, list);
            }
            list.add(node);
            // Set node as root node or add as child to last node in the stack
            if (null == last_root_node) {
                last_root_node = node;
            } else {
                final String sconf = ht_attributes.get("c");
                nodes.getLast().add((Node) node, null == sconf ? Node.MAX_EDGE_CONFIDENCE : Byte.parseByte(sconf));
            }
            // color?
            final String scolor = ht_attributes.get("color");
            if (null != scolor) {
                final Color color = Utils.getRGBColorFromHex(scolor);
                Collection<Node<?>> nodes = node_colors.get(color);
                if (null == nodes) {
                    nodes = new ArrayList<Node<?>>();
                    node_colors.put(color, nodes);
                }
                nodes.add(node);
            }
            // Put node into stack of nodes (to be removed on closing the tag)
            nodes.add(node);
        } else if (type.equals("profile")) {
            Profile profile = new Profile(this.project, oid, ht_attributes, ht_links);
            profile.addToDatabase();
            ht_displayables.put(oid, profile);
            addToLastOpenLayer(profile);
            last_displayable = profile;
            return null;
        } else if (type.equals("pipe")) {
            Pipe pipe = new Pipe(this.project, oid, ht_attributes, ht_links);
            pipe.addToDatabase();
            ht_displayables.put(new Long(oid), pipe);
            ht_zdispl.put(new Long(oid), pipe);
            last_displayable = pipe;
            addToLastOpenLayerSet(pipe);
            return null;
        } else if (type.equals("polyline")) {
            Polyline pline = new Polyline(this.project, oid, ht_attributes, ht_links);
            pline.addToDatabase();
            last_displayable = pline;
            ht_displayables.put(new Long(oid), pline);
            ht_zdispl.put(new Long(oid), pline);
            addToLastOpenLayerSet(pline);
            return null;
        } else if (type.equals("connector")) {
            final Connector con = new Connector(this.project, oid, ht_attributes, ht_links);
            if (ht_attributes.containsKey("origin")) {
                legacy.add(new Runnable() {

                    public void run() {
                        con.readLegacyXML(al_layer_sets.get(al_layer_sets.size() - 1), ht_attributes, ht_links);
                    }
                });
            }
            con.addToDatabase();
            last_connector = con;
            last_tree = con;
            last_displayable = con;
            ht_displayables.put(new Long(oid), con);
            ht_zdispl.put(new Long(oid), con);
            addToLastOpenLayerSet(con);
            return null;
        } else if (type.equals("path")) {
            if (null != reca) {
                reca.add(ht_attributes.get("d"));
                return null;
            }
            return null;
        } else if (type.equals("area")) {
            reca = new ReconstructArea();
            if (null != last_area_list) {
                last_area_list_layer_id = Long.parseLong(ht_attributes.get("layer_id"));
            }
            return null;
        } else if (type.equals("area_list")) {
            AreaList area = new AreaList(this.project, oid, ht_attributes, ht_links);
            // why? This looks like an onion
            area.addToDatabase();
            last_area_list = area;
            last_displayable = area;
            ht_displayables.put(new Long(oid), area);
            ht_zdispl.put(new Long(oid), area);
            addToLastOpenLayerSet(area);
            return null;
        } else if (type.equals("tag")) {
            Taggable t = taggables.getLast();
            if (null != t) {
                Object ob = ht_attributes.get("key");
                // defaults to 't'
                int keyCode = KeyEvent.VK_T;
                // KeyEvent.VK_U is char U, not u
                if (null != ob)
                    keyCode = (int) ((String) ob).toUpperCase().charAt(0);
                Tag tag = al_layer_sets.get(al_layer_sets.size() - 1).putTag(ht_attributes.get("name"), keyCode);
                // could be null if name is not found
                if (null != tag)
                    t.addTag(tag);
            }
        } else if (type.equals("ball_ob")) {
            // add a ball to the last open Ball
            if (null != last_ball) {
                last_ball.addBall(Double.parseDouble(ht_attributes.get("x")), Double.parseDouble(ht_attributes.get("y")), Double.parseDouble(ht_attributes.get("r")), Long.parseLong(ht_attributes.get("layer_id")));
            }
            return null;
        } else if (type.equals("ball")) {
            Ball ball = new Ball(this.project, oid, ht_attributes, ht_links);
            ball.addToDatabase();
            last_ball = ball;
            last_displayable = ball;
            ht_displayables.put(new Long(oid), ball);
            ht_zdispl.put(new Long(oid), ball);
            addToLastOpenLayerSet(ball);
            return null;
        } else if (type.equals("stack")) {
            Stack stack = new Stack(this.project, oid, ht_attributes, ht_links);
            stack.addToDatabase();
            last_stack = stack;
            last_displayable = stack;
            ht_displayables.put(new Long(oid), stack);
            ht_zdispl.put(new Long(oid), stack);
            addToLastOpenLayerSet(stack);
        } else if (type.equals("treeline")) {
            Treeline tline = new Treeline(this.project, oid, ht_attributes, ht_links);
            tline.addToDatabase();
            last_treeline = tline;
            last_tree = tline;
            last_treeline_data = new StringBuilder();
            last_displayable = tline;
            ht_displayables.put(oid, tline);
            ht_zdispl.put(oid, tline);
            addToLastOpenLayerSet(tline);
        } else if (type.equals("areatree")) {
            AreaTree art = new AreaTree(this.project, oid, ht_attributes, ht_links);
            art.addToDatabase();
            last_areatree = art;
            last_tree = art;
            last_displayable = art;
            ht_displayables.put(oid, art);
            ht_zdispl.put(oid, art);
            addToLastOpenLayerSet(art);
        } else if (type.equals("dd_item")) {
            if (null != last_dissector) {
                last_dissector.addItem(Integer.parseInt(ht_attributes.get("tag")), Integer.parseInt(ht_attributes.get("radius")), ht_attributes.get("points"));
            }
        } else if (type.equals("label")) {
            DLabel label = new DLabel(project, oid, ht_attributes, ht_links);
            label.addToDatabase();
            ht_displayables.put(new Long(oid), label);
            addToLastOpenLayer(label);
            last_displayable = label;
            return null;
        } else if (type.equals("annot")) {
            last_annotation = new StringBuilder();
            return null;
        } else if (type.equals("patch")) {
            Patch patch = new Patch(project, oid, ht_attributes, ht_links);
            patch.addToDatabase();
            ht_displayables.put(new Long(oid), patch);
            addToLastOpenLayer(patch);
            last_patch = patch;
            last_displayable = patch;
            checkAlphaMasks(patch);
            return null;
        } else if (type.equals("filter")) {
            last_patch_filters.add(newFilter(ht_attributes));
        } else if (type.equals("dissector")) {
            Dissector dissector = new Dissector(this.project, oid, ht_attributes, ht_links);
            dissector.addToDatabase();
            last_dissector = dissector;
            last_displayable = dissector;
            ht_displayables.put(new Long(oid), dissector);
            ht_zdispl.put(new Long(oid), dissector);
            addToLastOpenLayerSet(dissector);
        } else if (type.equals("layer")) {
            // find last open LayerSet, if any
            for (int i = al_layer_sets.size() - 1; i > -1; ) {
                LayerSet set = al_layer_sets.get(i);
                Layer layer = new Layer(project, oid, ht_attributes);
                layer.addToDatabase();
                set.addSilently(layer);
                al_layers.add(layer);
                Object ot = ht_attributes.get("title");
                return new LayerThing(template_layer_thing, project, -1, (null == ot ? null : (String) ot), layer, null);
            }
        } else if (type.equals("layer_set")) {
            LayerSet set = new LayerSet(project, oid, ht_attributes, ht_links);
            last_displayable = set;
            set.addToDatabase();
            ht_displayables.put(new Long(oid), set);
            al_layer_sets.add(set);
            addToLastOpenLayer(set);
            Object ot = ht_attributes.get("title");
            return new LayerThing(template_layer_set_thing, project, -1, (null == ot ? null : (String) ot), set, null);
        } else if (type.equals("calibration")) {
            // find last open LayerSet if any
            for (int i = al_layer_sets.size() - 1; i > -1; ) {
                LayerSet set = al_layer_sets.get(i);
                set.restoreCalibration(ht_attributes);
                return null;
            }
        } else if (type.equals("prop")) {
            // Add property to last created Displayable
            if (null != last_displayable) {
                last_displayable.setProperty(ht_attributes.get("key"), ht_attributes.get("value"));
            }
        } else if (type.equals("linked_prop")) {
            // Add linked property to last created Displayable. Has to wait until the Displayable ids have been resolved to instances.
            if (null != last_displayable) {
                putLinkedProperty(last_displayable, ht_attributes);
            }
        } else {
            Utils.log2("TMLHandler Unknown type: " + type);
        }
    } catch (Exception e) {
        IJError.print(e);
    }
    // default:
    return null;
}
Also used : Ball(ini.trakem2.display.Ball) Connector(ini.trakem2.display.Connector) Node(ini.trakem2.display.Node) Profile(ini.trakem2.display.Profile) AreaTree(ini.trakem2.display.AreaTree) ReconstructArea(ini.trakem2.utils.ReconstructArea) Dissector(ini.trakem2.display.Dissector) LayerSet(ini.trakem2.display.LayerSet) LayerThing(ini.trakem2.tree.LayerThing) Color(java.awt.Color) Pipe(ini.trakem2.display.Pipe) AreaList(ini.trakem2.display.AreaList) Layer(ini.trakem2.display.Layer) SAXException(org.xml.sax.SAXException) SAXParseException(org.xml.sax.SAXParseException) Stack(ini.trakem2.display.Stack) Treeline(ini.trakem2.display.Treeline) DLabel(ini.trakem2.display.DLabel) Polyline(ini.trakem2.display.Polyline) Tag(ini.trakem2.display.Tag) Taggable(ini.trakem2.display.Taggable) Patch(ini.trakem2.display.Patch)

Example 23 with Filter

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

the class AlignmentUtils method extractAndSaveLayerFeatures.

/**
 * Extract SIFT features and save them into the project folder.
 *
 * @param layerRange the list of layers to be aligned
 * @param box a rectangular region of interest that will be used for alignment
 * @param scale scale factor &lt;= 1.0
 * @param filter a name based filter for Patches (can be null)
 * @param siftParam SIFT extraction parameters
 * @param clearCache
 * @param numThreads
 * @throws ExecutionException
 * @throws InterruptedException
 */
protected static final void extractAndSaveLayerFeatures(final List<Layer> layerRange, final Rectangle box, final double scale, final Filter<Patch> filter, final FloatArray2DSIFT.Param siftParam, final boolean clearCache, final int numThreads) throws ExecutionException, InterruptedException {
    final long sTime = System.currentTimeMillis();
    final ExecutorService exec = ExecutorProvider.getExecutorService(1.0f / (float) numThreads);
    /* extract features for all slices and store them to disk */
    final AtomicInteger counter = new AtomicInteger(0);
    final ArrayList<Future<ArrayList<Feature>>> siftTasks = new ArrayList<Future<ArrayList<Feature>>>();
    for (final Layer layer : layerRange) {
        siftTasks.add(exec.submit(new LayerFeatureCallable(layer, box, scale, filter, siftParam, clearCache)));
    }
    /* join */
    try {
        for (final Future<ArrayList<Feature>> fu : siftTasks) {
            IJ.showProgress(counter.getAndIncrement(), layerRange.size() - 1);
            fu.get();
        }
    } catch (final InterruptedException e) {
        Utils.log("Feature extraction interrupted.");
        IJError.print(e);
        siftTasks.clear();
        // exec.shutdownNow();
        throw e;
    } catch (final ExecutionException e) {
        Utils.log("Execution exception during feature extraction.");
        IJError.print(e);
        siftTasks.clear();
        // exec.shutdownNow();
        throw e;
    }
    siftTasks.clear();
    IJ.log("Extracted features in " + (System.currentTimeMillis() - sTime) + "ms");
// exec.shutdown();
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ExecutorService(java.util.concurrent.ExecutorService) ArrayList(java.util.ArrayList) Future(java.util.concurrent.Future) ExecutionException(java.util.concurrent.ExecutionException) Feature(mpicbg.imagefeatures.Feature) Layer(ini.trakem2.display.Layer)

Example 24 with Filter

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

the class Align method alignLayersLinearly.

/**
 * Align a range of layers by accumulating pairwise alignments of contiguous layers.
 *
 * @param layers The range of layers to align pairwise.
 * @param numThreads The number of threads to use.
 * @param filter The {@link Filter} to decide which {@link Patch} instances to use in each {@link Layer}. Can be null.
 */
public static final void alignLayersLinearly(final List<Layer> layers, final int numThreads, final Filter<Patch> filter) {
    param.sift.maxOctaveSize = 1600;
    if (!param.setup("Align layers linearly"))
        return;
    final Rectangle box = layers.get(0).getParent().getMinimalBoundingBox(Patch.class);
    final double scale = Math.min(1.0, Math.min((double) param.sift.maxOctaveSize / box.width, (double) param.sift.maxOctaveSize / box.height));
    final Param p = param.clone();
    p.maxEpsilon *= scale;
    final FloatArray2DSIFT sift = new FloatArray2DSIFT(p.sift);
    final SIFT ijSIFT = new SIFT(sift);
    Rectangle box1 = null;
    Rectangle box2 = null;
    final Collection<Feature> features1 = new ArrayList<Feature>();
    final Collection<Feature> features2 = new ArrayList<Feature>();
    final List<PointMatch> candidates = new ArrayList<PointMatch>();
    final List<PointMatch> inliers = new ArrayList<PointMatch>();
    final AffineTransform a = new AffineTransform();
    int i = 0;
    for (final Layer l : layers) {
        long s = System.currentTimeMillis();
        features1.clear();
        features1.addAll(features2);
        features2.clear();
        final Rectangle box3 = l.getMinimalBoundingBox(Patch.class);
        if (box3 == null)
            continue;
        box1 = box2;
        box2 = box3;
        final List<Patch> patches = l.getAll(Patch.class);
        if (null != filter) {
            for (final Iterator<Patch> it = patches.iterator(); it.hasNext(); ) {
                if (!filter.accept(it.next()))
                    it.remove();
            }
        }
        ijSIFT.extractFeatures(l.getProject().getLoader().getFlatImage(l, box2, scale, 0xffffffff, ImagePlus.GRAY8, Patch.class, patches, true).getProcessor(), features2);
        Utils.log(features2.size() + " features extracted in layer \"" + l.getTitle() + "\" (took " + (System.currentTimeMillis() - s) + " ms).");
        if (features1.size() > 0) {
            s = System.currentTimeMillis();
            candidates.clear();
            FeatureTransform.matchFeatures(features2, features1, candidates, p.rod);
            final AbstractAffineModel2D<?> model;
            switch(p.expectedModelIndex) {
                case 0:
                    model = new TranslationModel2D();
                    break;
                case 1:
                    model = new RigidModel2D();
                    break;
                case 2:
                    model = new SimilarityModel2D();
                    break;
                case 3:
                    model = new AffineModel2D();
                    break;
                default:
                    return;
            }
            boolean modelFound;
            boolean again = false;
            try {
                do {
                    again = false;
                    modelFound = model.filterRansac(candidates, inliers, 1000, p.maxEpsilon, p.minInlierRatio, p.minNumInliers, 3);
                    if (modelFound && p.rejectIdentity) {
                        final ArrayList<Point> points = new ArrayList<Point>();
                        PointMatch.sourcePoints(inliers, points);
                        if (Transforms.isIdentity(model, points, p.identityTolerance)) {
                            Utils.log("Identity transform for " + inliers.size() + " matches rejected.");
                            candidates.removeAll(inliers);
                            inliers.clear();
                            again = true;
                        }
                    }
                } while (again);
            } catch (final NotEnoughDataPointsException e) {
                modelFound = false;
            }
            if (modelFound) {
                Utils.log("Model found for layer \"" + l.getTitle() + "\" and its predecessor:\n  correspondences  " + inliers.size() + " of " + candidates.size() + "\n  average residual error  " + (model.getCost() / scale) + " px\n  took " + (System.currentTimeMillis() - s) + " ms");
                final AffineTransform b = new AffineTransform();
                b.translate(box1.x, box1.y);
                b.scale(1.0f / scale, 1.0f / scale);
                b.concatenate(model.createAffine());
                b.scale(scale, scale);
                b.translate(-box2.x, -box2.y);
                a.concatenate(b);
                l.apply(Displayable.class, a);
                Display.repaint(l);
            } else {
                Utils.log("No model found for layer \"" + l.getTitle() + "\" and its predecessor:\n  correspondence candidates  " + candidates.size() + "\n  took " + (System.currentTimeMillis() - s) + " ms");
                a.setToIdentity();
            }
        }
        IJ.showProgress(++i, layers.size());
    }
}
Also used : NotEnoughDataPointsException(mpicbg.models.NotEnoughDataPointsException) SIFT(mpicbg.ij.SIFT) FloatArray2DSIFT(mpicbg.imagefeatures.FloatArray2DSIFT) Rectangle(java.awt.Rectangle) ArrayList(java.util.ArrayList) Feature(mpicbg.imagefeatures.Feature) RigidModel2D(mpicbg.trakem2.transform.RigidModel2D) AbstractAffineModel2D(mpicbg.models.AbstractAffineModel2D) AffineModel2D(mpicbg.models.AffineModel2D) InterpolatedAffineModel2D(mpicbg.models.InterpolatedAffineModel2D) SimilarityModel2D(mpicbg.models.SimilarityModel2D) Point(mpicbg.models.Point) Layer(ini.trakem2.display.Layer) Point(mpicbg.models.Point) FloatArray2DSIFT(mpicbg.imagefeatures.FloatArray2DSIFT) PointMatch(mpicbg.models.PointMatch) AffineTransform(java.awt.geom.AffineTransform) TranslationModel2D(mpicbg.trakem2.transform.TranslationModel2D) Patch(ini.trakem2.display.Patch)

Example 25 with Filter

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

the class AlignLayersTask method alignLayersLinearlyJob.

public static final void alignLayersLinearlyJob(final LayerSet layerSet, final int first, final int last, final boolean propagateTransform, final Rectangle fov, final Filter<Patch> filter) {
    // will reverse order if necessary
    final List<Layer> layerRange = layerSet.getLayers(first, last);
    final Align.Param p = Align.param.clone();
    // find the first non-empty layer, and remove all empty layers
    Rectangle box = fov;
    for (final Iterator<Layer> it = layerRange.iterator(); it.hasNext(); ) {
        final Layer la = it.next();
        if (!la.contains(Patch.class, true)) {
            it.remove();
            continue;
        }
        if (null == box) {
            // The first layer:
            // Only for visible patches
            box = la.getMinimalBoundingBox(Patch.class, true);
        }
    }
    if (0 == layerRange.size()) {
        Utils.log("All layers in range are empty!");
        return;
    }
    /* do not work if there is only one layer selected */
    if (layerRange.size() < 2)
        return;
    final double scale = Math.min(1.0, Math.min((double) p.sift.maxOctaveSize / (double) box.width, (double) p.sift.maxOctaveSize / (double) box.height));
    p.maxEpsilon *= scale;
    p.identityTolerance *= scale;
    // Utils.log2("scale: " + scale + "  maxOctaveSize: " + p.sift.maxOctaveSize + "  box: " + box.width + "," + box.height);
    final FloatArray2DSIFT sift = new FloatArray2DSIFT(p.sift);
    final SIFT ijSIFT = new SIFT(sift);
    Rectangle box1 = fov;
    Rectangle box2 = fov;
    final Collection<Feature> features1 = new ArrayList<Feature>();
    final Collection<Feature> features2 = new ArrayList<Feature>();
    final List<PointMatch> candidates = new ArrayList<PointMatch>();
    final List<PointMatch> inliers = new ArrayList<PointMatch>();
    final AffineTransform a = new AffineTransform();
    int s = 0;
    for (final Layer layer : layerRange) {
        if (Thread.currentThread().isInterrupted())
            return;
        final long t0 = System.currentTimeMillis();
        features1.clear();
        features1.addAll(features2);
        features2.clear();
        final Rectangle box3 = layer.getMinimalBoundingBox(Patch.class, true);
        // skipping empty layer
        if (box3 == null || (box3.width == 0 && box3.height == 0))
            continue;
        box1 = null == fov ? box2 : fov;
        box2 = null == fov ? box3 : fov;
        final List<Patch> patches = layer.getAll(Patch.class);
        if (null != filter) {
            for (final Iterator<Patch> it = patches.iterator(); it.hasNext(); ) {
                if (!filter.accept(it.next()))
                    it.remove();
            }
        }
        final ImageProcessor flatImage = layer.getProject().getLoader().getFlatImage(layer, box2, scale, 0xffffffff, ImagePlus.GRAY8, Patch.class, patches, true).getProcessor();
        ijSIFT.extractFeatures(flatImage, features2);
        IJ.log(features2.size() + " features extracted in layer \"" + layer.getTitle() + "\" (took " + (System.currentTimeMillis() - t0) + " ms).");
        if (features1.size() > 0) {
            final long t1 = System.currentTimeMillis();
            candidates.clear();
            FeatureTransform.matchFeatures(features2, features1, candidates, p.rod);
            final AbstractAffineModel2D<?> model;
            switch(p.expectedModelIndex) {
                case 0:
                    model = new TranslationModel2D();
                    break;
                case 1:
                    model = new RigidModel2D();
                    break;
                case 2:
                    model = new SimilarityModel2D();
                    break;
                case 3:
                    model = new AffineModel2D();
                    break;
                default:
                    return;
            }
            final AbstractAffineModel2D<?> desiredModel;
            switch(p.desiredModelIndex) {
                case 0:
                    desiredModel = new TranslationModel2D();
                    break;
                case 1:
                    desiredModel = new RigidModel2D();
                    break;
                case 2:
                    desiredModel = new SimilarityModel2D();
                    break;
                case 3:
                    desiredModel = new AffineModel2D();
                    break;
                default:
                    return;
            }
            boolean modelFound;
            boolean again = false;
            try {
                do {
                    again = false;
                    modelFound = model.filterRansac(candidates, inliers, 1000, p.maxEpsilon, p.minInlierRatio, p.minNumInliers, 3);
                    if (modelFound && p.rejectIdentity) {
                        final ArrayList<Point> points = new ArrayList<Point>();
                        PointMatch.sourcePoints(inliers, points);
                        if (Transforms.isIdentity(model, points, p.identityTolerance)) {
                            IJ.log("Identity transform for " + inliers.size() + " matches rejected.");
                            candidates.removeAll(inliers);
                            inliers.clear();
                            again = true;
                        }
                    }
                } while (again);
                if (modelFound)
                    desiredModel.fit(inliers);
            } catch (final NotEnoughDataPointsException e) {
                modelFound = false;
            } catch (final IllDefinedDataPointsException e) {
                modelFound = false;
            }
            if (Thread.currentThread().isInterrupted())
                return;
            if (modelFound) {
                IJ.log("Model found for layer \"" + layer.getTitle() + "\" and its predecessor:\n  correspondences  " + inliers.size() + " of " + candidates.size() + "\n  average residual error  " + (model.getCost() / scale) + " px\n  took " + (System.currentTimeMillis() - t1) + " ms");
                final AffineTransform b = new AffineTransform();
                b.translate(box1.x, box1.y);
                b.scale(1.0f / scale, 1.0f / scale);
                b.concatenate(desiredModel.createAffine());
                b.scale(scale, scale);
                b.translate(-box2.x, -box2.y);
                a.concatenate(b);
                AlignTask.transformPatchesAndVectorData(patches, a);
                Display.repaint(layer);
            } else {
                IJ.log("No model found for layer \"" + layer.getTitle() + "\" and its predecessor:\n  correspondence candidates  " + candidates.size() + "\n  took " + (System.currentTimeMillis() - s) + " ms");
                a.setToIdentity();
            }
        }
        IJ.showProgress(++s, layerRange.size());
    }
    if (Thread.currentThread().isInterrupted())
        return;
    if (propagateTransform) {
        if (last > first && last < layerSet.size() - 2)
            for (final Layer la : layerSet.getLayers(last + 1, layerSet.size() - 1)) {
                if (Thread.currentThread().isInterrupted())
                    return;
                AlignTask.transformPatchesAndVectorData(la, a);
            }
        else if (first > last && last > 0)
            for (final Layer la : layerSet.getLayers(0, last - 1)) {
                if (Thread.currentThread().isInterrupted())
                    return;
                AlignTask.transformPatchesAndVectorData(la, a);
            }
    }
}
Also used : NotEnoughDataPointsException(mpicbg.models.NotEnoughDataPointsException) SIFT(mpicbg.ij.SIFT) FloatArray2DSIFT(mpicbg.imagefeatures.FloatArray2DSIFT) Rectangle(java.awt.Rectangle) ArrayList(java.util.ArrayList) Feature(mpicbg.imagefeatures.Feature) ImageProcessor(ij.process.ImageProcessor) RigidModel2D(mpicbg.trakem2.transform.RigidModel2D) AbstractAffineModel2D(mpicbg.models.AbstractAffineModel2D) AffineModel2D(mpicbg.models.AffineModel2D) SimilarityModel2D(mpicbg.models.SimilarityModel2D) IllDefinedDataPointsException(mpicbg.models.IllDefinedDataPointsException) Point(mpicbg.models.Point) Layer(ini.trakem2.display.Layer) Point(mpicbg.models.Point) FloatArray2DSIFT(mpicbg.imagefeatures.FloatArray2DSIFT) PointMatch(mpicbg.models.PointMatch) AffineTransform(java.awt.geom.AffineTransform) TranslationModel2D(mpicbg.trakem2.transform.TranslationModel2D) Patch(ini.trakem2.display.Patch)

Aggregations

Layer (ini.trakem2.display.Layer)18 ArrayList (java.util.ArrayList)15 Patch (ini.trakem2.display.Patch)14 Point (mpicbg.models.Point)13 Rectangle (java.awt.Rectangle)11 HashSet (java.util.HashSet)10 NotEnoughDataPointsException (mpicbg.models.NotEnoughDataPointsException)9 ImagePlus (ij.ImagePlus)8 AffineTransform (java.awt.geom.AffineTransform)7 Future (java.util.concurrent.Future)7 PointMatch (mpicbg.models.PointMatch)7 ExecutorService (java.util.concurrent.ExecutorService)6 AffineModel2D (mpicbg.models.AffineModel2D)6 SimilarityModel2D (mpicbg.models.SimilarityModel2D)6 GenericDialog (ij.gui.GenericDialog)5 Area (java.awt.geom.Area)5 ImageProcessor (ij.process.ImageProcessor)4 Collection (java.util.Collection)4 HashMap (java.util.HashMap)4 Project (ini.trakem2.Project)3