Search in sources :

Example 11 with AreaList

use of ini.trakem2.display.AreaList in project TrakEM2 by trakem2.

the class AreaList method exportAsLabels.

/**
 * Export all given AreaLists as one per pixel value, what is called a "labels" file; a file dialog is offered to save the image as a tiff stack.
 */
public static void exportAsLabels(final List<Displayable> listToPaint, final ij.gui.Roi roi, final float scale, int first_layer, int last_layer, final boolean visible_only, final boolean to_file, final boolean as_amira_labels) {
    // survive everything:
    if (null == listToPaint || 0 == listToPaint.size()) {
        Utils.log("Null or empty list.");
        return;
    }
    if (scale < 0 || scale > 1) {
        Utils.log("Improper scale value. Must be 0 < scale <= 1");
        return;
    }
    // Select the subset to paint
    final ArrayList<AreaList> list = new ArrayList<AreaList>();
    for (final Displayable d : listToPaint) {
        if (visible_only && !d.isVisible())
            continue;
        if (d instanceof AreaList)
            list.add((AreaList) d);
    }
    Utils.log2("exportAsLabels: list.size() is " + list.size());
    // Current AmiraMeshEncoder supports ByteProcessor only: 256 labels max, including background at zero.
    if (as_amira_labels && list.size() > 255) {
        Utils.log("Saving ONLY first 255 AreaLists!\nDiscarded:");
        final StringBuilder sb = new StringBuilder();
        for (final Displayable d : list.subList(255, list.size())) {
            sb.append("    ").append(d.getProject().getShortMeaningfulTitle(d)).append('\n');
        }
        Utils.log(sb.toString());
        final ArrayList<AreaList> li = new ArrayList<AreaList>(list);
        list.clear();
        list.addAll(li.subList(0, 255));
    }
    String path = null;
    if (to_file) {
        final String ext = as_amira_labels ? ".am" : ".tif";
        final File f = Utils.chooseFile("labels", ext);
        if (null == f)
            return;
        path = f.getAbsolutePath().replace('\\', '/');
    }
    final LayerSet layer_set = list.get(0).getLayerSet();
    if (first_layer > last_layer) {
        final int tmp = first_layer;
        first_layer = last_layer;
        last_layer = tmp;
        if (first_layer < 0)
            first_layer = 0;
        if (last_layer >= layer_set.size())
            last_layer = layer_set.size() - 1;
    }
    // Create image according to roi and scale
    final int width, height;
    final Rectangle broi;
    if (null == roi) {
        broi = null;
        width = (int) (layer_set.getLayerWidth() * scale);
        height = (int) (layer_set.getLayerHeight() * scale);
    } else {
        broi = roi.getBounds();
        width = (int) (broi.width * scale);
        height = (int) (broi.height * scale);
    }
    // Compute highest label value, which affects of course the stack image type
    final TreeSet<Integer> label_values = new TreeSet<Integer>();
    for (final Displayable d : list) {
        final String label = d.getProperty("label");
        if (null != label)
            label_values.add(Integer.parseInt(label));
    }
    int lowest = 0, highest = 0;
    if (label_values.size() > 0) {
        lowest = label_values.first();
        highest = label_values.last();
    }
    final int n_non_labeled = list.size() - label_values.size();
    final int max_label_value = highest + n_non_labeled;
    int type_ = ImagePlus.GRAY8;
    if (max_label_value > 255) {
        type_ = ImagePlus.GRAY16;
        if (max_label_value > 65535) {
            type_ = ImagePlus.GRAY32;
        }
    }
    final int type = type_;
    final ImageStack stack = new ImageStack(width, height);
    final Calibration cal = layer_set.getCalibration();
    String amira_params = null;
    if (as_amira_labels) {
        final StringBuilder sb = new StringBuilder("CoordType \"uniform\"\nMaterials {\nExterior {\n Id 0,\nColor 0 0 0\n}\n");
        final float[] c = new float[3];
        int value = 0;
        for (final Displayable d : list) {
            // 0 is background
            value++;
            d.getColor().getRGBColorComponents(c);
            String s = d.getProject().getShortMeaningfulTitle(d);
            s = s.replace('-', '_').replaceAll(" #", " id");
            sb.append(Utils.makeValidIdentifier(s)).append(" {\n").append("Id ").append(value).append(",\n").append("Color ").append(c[0]).append(' ').append(c[1]).append(' ').append(c[2]).append("\n}\n");
        }
        sb.append("}\n");
        amira_params = sb.toString();
    }
    final float len = last_layer - first_layer + 1;
    // Assign labels
    final HashMap<AreaList, Integer> labels = new HashMap<AreaList, Integer>();
    for (final AreaList d : list) {
        final String slabel = d.getProperty("label");
        int label;
        if (null != slabel) {
            label = Integer.parseInt(slabel);
        } else {
            // 0 is background
            label = (++highest);
        }
        labels.put(d, label);
    }
    final ExecutorService exec = Utils.newFixedThreadPool("labels");
    final Map<Integer, ImageProcessor> slices = Collections.synchronizedMap(new TreeMap<Integer, ImageProcessor>());
    final List<Future<?>> fus = new ArrayList<Future<?>>();
    final List<Layer> layers = layer_set.getLayers().subList(first_layer, last_layer + 1);
    for (int k = 0; k < layers.size(); k++) {
        final Layer la = layers.get(k);
        final int slice = k;
        fus.add(exec.submit(new Runnable() {

            @Override
            public void run() {
                Utils.showProgress(slice / len);
                final ImageProcessor ip;
                if (ImagePlus.GRAY8 == type) {
                    final BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
                    final Graphics2D g = bi.createGraphics();
                    for (final AreaList ali : list) {
                        final Area area = ali.getArea(la);
                        if (null == area || area.isEmpty())
                            continue;
                        // Transform: the scale and the roi
                        final AffineTransform aff = new AffineTransform();
                        /* 3 - To scale: */
                        if (1 != scale)
                            aff.scale(scale, scale);
                        /* 2 - To roi coordinates: */
                        if (null != broi)
                            aff.translate(-broi.x, -broi.y);
                        /* 1 - To world coordinates: */
                        aff.concatenate(ali.at);
                        g.setTransform(aff);
                        final int label = labels.get(ali);
                        g.setColor(new Color(label, label, label));
                        g.fill(area);
                    }
                    g.dispose();
                    ip = new ByteProcessor(bi);
                    bi.flush();
                } else if (ImagePlus.GRAY16 == type) {
                    final USHORTPaint paint = new USHORTPaint((short) 0);
                    final BufferedImage bi = new BufferedImage(paint.getComponentColorModel(), paint.getComponentColorModel().createCompatibleWritableRaster(width, height), false, null);
                    final Graphics2D g = bi.createGraphics();
                    // final ColorSpace ugray = ColorSpace.getInstance(ColorSpace.CS_GRAY);
                    int painted = 0;
                    for (final AreaList ali : list) {
                        final Area area = ali.getArea(la);
                        if (null == area || area.isEmpty())
                            continue;
                        // Transform: the scale and the roi
                        final AffineTransform aff = new AffineTransform();
                        /* 3 - To scale: */
                        if (1 != scale)
                            aff.scale(scale, scale);
                        /* 2 - To roi coordinates: */
                        if (null != broi)
                            aff.translate(-broi.x, -broi.y);
                        /* 1 - To world coordinates: */
                        aff.concatenate(ali.at);
                        // Fill
                        g.setTransform(aff);
                        // The color doesn't work: paints in a stretched 8-bit mode
                        // g.setColor(new Color(ugray, new float[]{((float)labels.get(d)) / range}, 1));
                        Utils.log2("value: " + labels.get(ali).shortValue());
                        paint.setValue(labels.get(ali).shortValue());
                        g.setPaint(paint);
                        // .createTransformedArea(aff));
                        g.fill(area);
                        painted += 1;
                    }
                    g.dispose();
                    ip = new ShortProcessor(bi);
                    bi.flush();
                    Utils.log2("painted: " + painted);
                } else {
                    // Option 1: could use the same as above, but shifted by 65536, so that 65537 is 1, 65538 is 2, etc.
                    // and keep doing it until no more need to be shifted.
                    // The PROBLEM: cannot keep the order without complicated gymnastics to remember
                    // which label in which image has to be merged to the final image, which prevent
                    // a simple one-pass blitter.
                    // 
                    // Option 2: paint each arealist, extract the image, use it as a mask for filling:
                    final FloatProcessor fp = new FloatProcessor(width, height);
                    final float[] fpix = (float[]) fp.getPixels();
                    ip = fp;
                    final BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
                    final Graphics2D gbi = bi.createGraphics();
                    for (final AreaList ali : list) {
                        final Area area = ali.getArea(la);
                        if (null == area || area.isEmpty()) {
                            continue;
                        }
                        // Transform: the scale and the roi
                        // reverse order of transformations:
                        final AffineTransform aff = new AffineTransform();
                        /* 3 - To scale: */
                        if (1 != scale)
                            aff.scale(scale, scale);
                        /* 2 - To ROI coordinates: */
                        if (null != broi)
                            aff.translate(-broi.x, -broi.y);
                        /* 1 - To world coordinates: */
                        aff.concatenate(ali.at);
                        final Area s = area.createTransformedArea(aff);
                        final Rectangle sBounds = s.getBounds();
                        // Need to paint at all?
                        if (0 == sBounds.width || 0 == sBounds.height || !sBounds.intersects(0, 0, width, height))
                            continue;
                        // Paint shape
                        gbi.setColor(Color.white);
                        gbi.fill(s);
                        // Read out painted region
                        final int x0 = Math.max(0, sBounds.x);
                        final int y0 = Math.max(0, sBounds.y);
                        final int xN = Math.min(width, sBounds.x + sBounds.width);
                        final int yN = Math.min(height, sBounds.y + sBounds.height);
                        // Get the array
                        final byte[] bpix = ((DataBufferByte) bi.getRaster().getDataBuffer()).getData();
                        final float value = labels.get(ali);
                        // For every non-black pixel, set a 'value' pixel in the FloatProcessor
                        for (int y = y0; y < yN; ++y) {
                            for (int x = x0; x < xN; ++x) {
                                final int pos = y * width + x;
                                // black
                                if (0 == bpix[pos])
                                    continue;
                                fpix[pos] = value;
                            }
                        }
                        // Clear image region
                        gbi.setColor(Color.black);
                        gbi.fill(s);
                    }
                    gbi.dispose();
                    bi.flush();
                }
                slices.put(slice, ip);
            }
        }));
    }
    Utils.wait(fus);
    exec.shutdownNow();
    for (final Map.Entry<Integer, ImageProcessor> e : slices.entrySet()) {
        final Layer la = layers.get(e.getKey());
        stack.addSlice(la.getZ() * cal.pixelWidth + "", e.getValue());
        if (ImagePlus.GRAY8 != type) {
            e.getValue().setMinAndMax(lowest, highest);
        }
    }
    Utils.showProgress(1);
    // Save via file dialog:
    final ImagePlus imp = new ImagePlus("Labels", stack);
    if (as_amira_labels)
        imp.setProperty("Info", amira_params);
    imp.setCalibration(layer_set.getCalibrationCopy());
    if (to_file) {
        if (as_amira_labels) {
            final AmiraMeshEncoder ame = new AmiraMeshEncoder(path);
            if (!ame.open()) {
                Utils.log("Could not write to file " + path);
                return;
            }
            if (!ame.write(imp)) {
                Utils.log("Error in writing Amira file!");
                return;
            }
        } else {
            new FileSaver(imp).saveAsTiff(path);
        }
    } else
        imp.show();
}
Also used : ByteProcessor(ij.process.ByteProcessor) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Rectangle(java.awt.Rectangle) BufferedImage(java.awt.image.BufferedImage) ImageProcessor(ij.process.ImageProcessor) USHORTPaint(ini.trakem2.display.paint.USHORTPaint) FileSaver(ij.io.FileSaver) TreeSet(java.util.TreeSet) ImageStack(ij.ImageStack) FloatProcessor(ij.process.FloatProcessor) Color(java.awt.Color) Calibration(ij.measure.Calibration) ImagePlus(ij.ImagePlus) Point(java.awt.Point) USHORTPaint(ini.trakem2.display.paint.USHORTPaint) Graphics2D(java.awt.Graphics2D) ShortProcessor(ij.process.ShortProcessor) Area(java.awt.geom.Area) ExecutorService(java.util.concurrent.ExecutorService) AmiraMeshEncoder(amira.AmiraMeshEncoder) Future(java.util.concurrent.Future) AffineTransform(java.awt.geom.AffineTransform) File(java.io.File) Map(java.util.Map) HashMap(java.util.HashMap) TreeMap(java.util.TreeMap)

Example 12 with AreaList

use of ini.trakem2.display.AreaList in project TrakEM2 by trakem2.

the class Graph method extractAndShowGraph.

/**
 * Shows a dialog to pick which classes is one interested in.
 */
public static final void extractAndShowGraph(final LayerSet ls) {
    GenericDialog gd = new GenericDialog("Graph elements");
    Class<Displayable>[] c = new Class[] { AreaList.class, AreaTree.class, Ball.class, Connector.class, Patch.class, Pipe.class, Polyline.class, Profile.class, DLabel.class, Treeline.class };
    String[] types = new String[] { "AreaList", "AreaTree", "Ball", "Connector", "Image", "Pipe", "Polyline", "Profile", "Text", "Treeline" };
    boolean[] states = new boolean[] { true, true, false, false, false, false, true, true, false, true };
    assert (c.length == types.length && types.length == states.length);
    for (int i = 0; i < c.length; i++) {
        if (ZDisplayable.class.isAssignableFrom(c[i])) {
            if (!ls.contains(c[i]))
                states[i] = false;
        } else if (!ls.containsDisplayable(c[i]))
            states[i] = false;
    }
    gd.addCheckboxGroup(types.length, 1, types, states, new String[] { "Include only:" });
    gd.showDialog();
    if (gd.wasCanceled())
        return;
    HashSet<Class<Displayable>> only = new HashSet<Class<Displayable>>();
    for (int i = 0; i < types.length; i++) {
        if (gd.getNextBoolean())
            only.add(c[i]);
    }
    Graph.extractAndShowGraph(ls, only);
}
Also used : AreaTree(ini.trakem2.display.AreaTree) Ball(ini.trakem2.display.Ball) Connector(ini.trakem2.display.Connector) Displayable(ini.trakem2.display.Displayable) ZDisplayable(ini.trakem2.display.ZDisplayable) Pipe(ini.trakem2.display.Pipe) AreaList(ini.trakem2.display.AreaList) Profile(ini.trakem2.display.Profile) Point(java.awt.Point) DLabel(ini.trakem2.display.DLabel) Treeline(ini.trakem2.display.Treeline) GenericDialog(ij.gui.GenericDialog) Polyline(ini.trakem2.display.Polyline) Patch(ini.trakem2.display.Patch) HashSet(java.util.HashSet)

Example 13 with AreaList

use of ini.trakem2.display.AreaList 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 14 with AreaList

use of ini.trakem2.display.AreaList in project TrakEM2 by trakem2.

the class ProjectTree method insertSegmentations.

/* // makes no sense, because there may be multiple projects open and thus the viewport and position may interfere with each other across multiple projects. Saving the collapsed node state suffices.
	public void exportXML(final StringBuffer sb_body, String indent, JScrollPane jsp) {
		Point p = jsp.getViewport().getViewPosition();
		Dimension d = jsp.getSize(null);
		sb_body.append(indent).append("<t2_tree")
		       .append(" width=\"").append(d.width).append('\"')
		       .append(" height=\"").append(d.height).append('\"')
		       .append(" viewport_x=\"").append(p.e).append('\"')
		       .append(" viewport_y=\"").append(p.y).append('\"')
		;
		sb_body.append("\n").append(indent).append("</t2_tree>\n");
	}
	*/
/**
 * Creates a new node of basic type for each AreaList, Ball, Pipe or Polyline present in the ArrayList. Other elements are ignored.
 */
public void insertSegmentations(final Collection<? extends Displayable> al) {
    final TemplateThing tt_root = (TemplateThing) project.getTemplateTree().getRoot().getUserObject();
    // create a new abstract node called "imported_segmentations", if not there
    final String imported_labels = "imported_labels";
    if (!project.typeExists(imported_labels)) {
        // create it
        // yes I know I should check for the project of each Displayable in the ArrayList
        TemplateThing tet = new TemplateThing(imported_labels, project);
        project.addUniqueType(tet);
        DefaultMutableTreeNode root = project.getTemplateTree().getRoot();
        tt_root.addChild(tet);
        DefaultMutableTreeNode child_node = addChild(tet, root);
        DNDTree.expandNode(project.getTemplateTree(), child_node);
    // JTree is serious pain
    }
    // it's the same as 'tet' above, unless it existed
    TemplateThing tt_is = project.getTemplateThing(imported_labels);
    // create a project node from "imported_segmentations" template under a new top node
    final DefaultMutableTreeNode project_node = project.getProjectTree().getRoot();
    ProjectThing project_pt = (ProjectThing) project_node.getUserObject();
    final ProjectThing ct = project_pt.createChild(tt_root.getType());
    ProjectThing pt_is = ct.createChild(imported_labels);
    // addChild(pt_is, ctn);
    final DefaultMutableTreeNode node_pt_is = new DefaultMutableTreeNode(pt_is);
    final HashMap<Class<?>, String> types = new HashMap<Class<?>, String>();
    types.put(AreaList.class, "area_list");
    types.put(Pipe.class, "pipe");
    types.put(Polyline.class, "polyline");
    types.put(Ball.class, "ball");
    types.put(Treeline.class, "treeline");
    types.put(AreaTree.class, "areatree");
    types.put(Connector.class, "connector");
    // now, insert a new ProjectThing if of type AreaList, Ball and/or Pipe under node_child
    for (final Displayable d : al) {
        final String type = types.get(d.getClass());
        if (null == type) {
            Utils.log("insertSegmentations: ignoring " + d);
            continue;
        }
        try {
            final TemplateThing tt = getOrCreateChildTemplateThing(tt_is, type);
            ProjectThing one = new ProjectThing(tt, project, d);
            pt_is.addChild(one);
            // addChild(one, node_pt_is);
            // at the end
            node_pt_is.add(new DefaultMutableTreeNode(one));
        // Utils.log2("one parent : " + one.getParent());
        } catch (Exception e) {
            IJError.print(e);
        }
    }
    javax.swing.SwingUtilities.invokeLater(new Runnable() {

        public void run() {
            DefaultMutableTreeNode ctn = addChild(ct, project_node);
            ctn.add(node_pt_is);
            try {
                ProjectTree.this.scrollPathToVisible(new TreePath(node_pt_is.getPath()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    DNDTree.expandNode(this, node_pt_is);
}
Also used : Displayable(ini.trakem2.display.Displayable) ZDisplayable(ini.trakem2.display.ZDisplayable) DefaultMutableTreeNode(javax.swing.tree.DefaultMutableTreeNode) TreePath(javax.swing.tree.TreePath) HashMap(java.util.HashMap)

Example 15 with AreaList

use of ini.trakem2.display.AreaList in project TrakEM2 by trakem2.

the class AreaUtils method generateTriangles.

/**
 * Expects areas in local coordinates to the Displayable @param d.
 *  @param d
 *  @param scale The scaling of the entire universe, to limit the overall box
 *  @param resample_ The optimization parameter for marching cubes (i.e. a value of 2 will scale down to half, then apply marching cubes, then scale up by 2 the vertices coordinates).
 *  @param areas
 *  @return The List of triangles involved, specified as three consecutive vertices. A list of Point3f vertices.
 */
public static List<Point3f> generateTriangles(final Displayable d, final double scale, final int resample_, final Map<Layer, Area> areas) {
    // in the LayerSet, layers are ordered by Z already.
    try {
        int n = areas.size();
        if (0 == n)
            return null;
        final int resample;
        if (resample_ <= 0) {
            resample = 1;
            Utils.log2("Fixing zero or negative resampling value to 1.");
        } else
            resample = resample_;
        final LayerSet layer_set = d.getLayerSet();
        final AffineTransform aff = d.getAffineTransformCopy();
        final Rectangle r = d.getBoundingBox(null);
        // remove translation from a copy of the Displayable's AffineTransform
        final AffineTransform at_translate = new AffineTransform();
        at_translate.translate(-r.x, -r.y);
        aff.preConcatenate(at_translate);
        // incorporate resampling scaling into the transform
        final AffineTransform atK = new AffineTransform();
        // Utils.log("resample: " + resample + "  scale: " + scale);
        // 'scale' is there to limit gigantic universes
        final double K = (1.0 / resample) * scale;
        atK.scale(K, K);
        aff.preConcatenate(atK);
        final Calibration cal = layer_set.getCalibrationCopy();
        // Find first layer, compute depth, and fill in the depth vs area map
        Layer first_layer = null, last_layer = null;
        final int w = (int) Math.ceil(r.width * K);
        final int h = (int) Math.ceil(r.height * K);
        int depth = 0;
        final Map<Integer, Area> ma = new HashMap<Integer, Area>();
        for (final Layer la : layer_set.getLayers()) {
            // layers sorted by Z ASC
            final Area area = areas.get(la);
            if (null != area) {
                ma.put(depth, area);
                if (null == first_layer) {
                    first_layer = la;
                }
                // Utils.log("area at depth " + depth + " for layer " + la);
                depth++;
                n--;
            } else if (0 != depth) {
                // Utils.log("Empty area at depth " + depth);
                // an empty layer
                depth++;
            }
            if (0 == n) {
                last_layer = la;
                // no more areas to paint
                break;
            }
        }
        if (0 == depth) {
            Utils.log("ERROR could not find any areas for " + d);
            return null;
        }
        if (0 != n) {
            Utils.log("WARNING could not find all areas for " + d);
        }
        // No zero-padding: Marching Cubes now can handle edges
        final ShapeList<ByteType> shapeList = new ShapeListCached<ByteType>(new int[] { w, h, depth }, new ByteType(), 32);
        final Image<ByteType> shapeListImage = new Image<ByteType>(shapeList, shapeList.getBackground(), "ShapeListContainer");
        // 255 or -1 don't work !? So, giving the highest value (127) that is both a byte and an int.
        final ByteType intensity = new ByteType((byte) 127);
        for (final Map.Entry<Integer, Area> e : ma.entrySet()) {
            Area a = e.getValue();
            if (!aff.isIdentity()) {
                a = M.areaInIntsByRounding(a.createTransformedArea(aff));
            }
            shapeList.addShape(a, intensity, new int[] { e.getKey() });
        }
        // debug:
        // ImagePlus imp = ImageJFunctions.displayAsVirtualStack(shapeListImage);
        // imp.getProcessor().setMinAndMax( 0, 255 );
        // imp.show();
        // Utils.log2("Using imglib Shape List Image Container");
        // Now marching cubes
        // origins at 0,0,0: uncalibrated
        final List<Point3f> list = new MCTriangulator().getTriangles(shapeListImage, 1, new float[3]);
        // The list of triangles has coordinates:
        // - in x,y: in pixels, scaled by K = (1 / resample) * scale,
        // translated by r.x, r.y (the top-left coordinate of this AreaList bounding box)
        // - in z: in stack slice indices
        // So all x,y,z must be corrected in x,y and z of the proper layer
        // final double offset = first_layer.getZ();
        final int i_first_layer = layer_set.indexOf(first_layer);
        // The x,y translation to correct each point by:
        final float dx = (float) (r.x * scale * cal.pixelWidth);
        final float dy = (float) (r.y * scale * cal.pixelHeight);
        // Correct x,y by resampling and calibration, but not scale
        // scale is already in the pixel coordinates
        final float rsw = (float) (resample * cal.pixelWidth);
        final float rsh = (float) (resample * cal.pixelHeight);
        // no resampling in Z. and Uses pixelWidth, not pixelDepth.
        final double sz = scale * cal.pixelWidth;
        // debug:
        /*
			// which p.z types exist?
			final TreeSet<Float> ts = new TreeSet<Float>();
			for (final Iterator it = list.iterator(); it.hasNext(); ) {
				ts.add(((Point3f)it.next()).z);
			}
			for (final Float pz : ts) Utils.log2("A z: " + pz);
			*/
        // debug: How many different Z?
        /*
			HashSet<Float> zs = new HashSet<Float>();
			for (Point3f p : list) {
				zs.add(p.z);
			}
			ArrayList<Float> a = new ArrayList<Float>(zs);
			java.util.Collections.sort(a);
			for (Float f : a) {
				Utils.log("f: " + f);
			}
			*/
        // Utils.log2("Number of slices: " + imp.getNSlices());
        // Fix all points:
        // Read from list, modify and put into verts
        // and don't modify it if the verts already has it (it's just coincident)
        final Point3f[] verts = new Point3f[list.size()];
        // Utils.log("number of verts: " + verts.length + " mod 3: " + (verts.length % 3));
        final TreeMap<Integer, Point3f> output = new TreeMap<Integer, Point3f>();
        // The first section generates vertices at -1 and 0
        // The last section generates them at last_section_index and last_section_index +1
        // Capture from -1 to 0
        fix3DPoints(list, output, verts, first_layer.getZ(), 0, -1, dx, dy, rsw, rsh, sz, 1);
        int slice_index = 0;
        for (final Layer la : layer_set.getLayers().subList(i_first_layer, i_first_layer + depth)) {
            // If layer is empty, continue
            /* // YEAH don't! At least the immediate next layer would have points, like the extra Z level after last layer, to account for the thickness of the layer!
				if (empty_layers.contains(la)) {
					slice_index++;
					continue;
				}
				*/
            fix3DPoints(list, output, verts, la.getZ(), la.getThickness(), slice_index, dx, dy, rsw, rsh, sz, 1);
            slice_index++;
        }
        // Do the last layer again. The last layer has two Z planes in which it has pixels:
        try {
            // Capture from last_section_index to last_section_index+1, inclusive
            fix3DPoints(list, output, verts, last_layer.getZ() + last_layer.getThickness(), 0, slice_index, dx, dy, rsw, rsh, sz, 2);
        } catch (final Exception ee) {
            IJError.print(ee);
        }
        // Handle potential errors:
        if (0 != list.size() - output.size()) {
            Utils.log2("Unprocessed/unused points: " + (list.size() - output.size()));
            for (int i = 0; i < verts.length; i++) {
                if (null == verts[i]) {
                    final Point3f p = (Point3f) list.get(i);
                    Utils.log2("verts[" + i + "] = " + p.x + ", " + p.y + ", " + p.z + "  p.z as int: " + ((int) (p.z + 0.05f)));
                }
            }
            return new ArrayList<Point3f>(output.values());
        } else {
            return java.util.Arrays.asList(verts);
        }
    } catch (final Exception e) {
        e.printStackTrace();
    }
    return null;
}
Also used : HashMap(java.util.HashMap) Rectangle(java.awt.Rectangle) ArrayList(java.util.ArrayList) ShapeListCached(mpicbg.imglib.container.shapelist.ShapeListCached) ByteType(mpicbg.imglib.type.numeric.integer.ByteType) Image(mpicbg.imglib.image.Image) Point3f(org.scijava.vecmath.Point3f) LayerSet(ini.trakem2.display.LayerSet) Calibration(ij.measure.Calibration) TreeMap(java.util.TreeMap) Layer(ini.trakem2.display.Layer) ExecutionException(java.util.concurrent.ExecutionException) Area(java.awt.geom.Area) AffineTransform(java.awt.geom.AffineTransform) HashMap(java.util.HashMap) Map(java.util.Map) TreeMap(java.util.TreeMap)

Aggregations

AreaList (ini.trakem2.display.AreaList)7 Area (java.awt.geom.Area)7 ImagePlus (ij.ImagePlus)6 Color (java.awt.Color)6 Point (java.awt.Point)6 ArrayList (java.util.ArrayList)6 GenericDialog (ij.gui.GenericDialog)5 Worker (ini.trakem2.utils.Worker)5 Rectangle (java.awt.Rectangle)5 ImageStack (ij.ImageStack)4 ShapeRoi (ij.gui.ShapeRoi)4 AffineTransform (java.awt.geom.AffineTransform)4 NoninvertibleTransformException (java.awt.geom.NoninvertibleTransformException)4 HashMap (java.util.HashMap)4 PolygonRoi (ij.gui.PolygonRoi)3 Roi (ij.gui.Roi)3 Layer (ini.trakem2.display.Layer)3 USHORTPaint (ini.trakem2.display.paint.USHORTPaint)3 File (java.io.File)3 HashSet (java.util.HashSet)3