Selecting and renaming ROIs automatically from plugin

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

Selecting and renaming ROIs automatically from plugin

Anna Svagzdys
This post was updated on .
Hello, I'm new to ImageJ so apologies if this is an obvious question!

I am writing a plugin that tracks particles through an .avi. When the plugin runs, I would like it to automatically add each particle to the ROI manager and give it a sequential number so I can tell if this particle is the same particle as it was on the previous slide, if that makes any sense. Here's my attempt:

public void showBlobs(ArrayList<ArrayList<Blob>> blobs, int s) {
        Frame frame = WindowManager.getFrame("ROI Manager");
        if (frame == null) {
            IJ.run("ROI Manager...");
        }
        frame = WindowManager.getFrame("ROI Manager");
        RoiManager roiManager = (RoiManager) frame;

        for (int i = 0; i < blobs.size(); i++) {

            //System.out.println("Showing Blobs on slice " + s + ": i = " + i + " size = "
            //+ blobs.get(i).size());

            if (blobs.get(i).size() > s) {
                if (blobs.get(i).get(s - 1) != null) {
                    Polygon p = blobs.get(i).get(s - 1).getOuterContour();
                    int n = p.npoints;
                    float[] x = new float[p.npoints];
                    float[] y = new float[p.npoints];
                    for (int j = 0; j < n; j++) {
                        x[j] = p.xpoints[j] + 0.5f;
                        y[j] = p.ypoints[j] + 0.5f;
                    }
                    Roi roi = new PolygonRoi(x, y, n, Roi.TRACED_ROI);
                    Roi.setColor(Color.green);
                    roiManager.add(image, roi, i);

                    //name ROI
                    int ind = roiManager.getRoiIndex(roi);
                    System.out.println("Plotting ROIs: index = " + ind); //-1 = roi not found
                    roiManager.select(ind);
                    String name = "" + prevSlice + "-" + i;
                    roiManager.runCommand("rename",name);
                    roiManager.deselect();
                }
            }
        }
    }

The index returned is always -1 and I get an error message saying no ROI is selected. If comment out the naming part, the code successfully adds all the ROIs to the manager and I am able to rename them manually--but that defeats much of the purpose of the plugin.

Thanks in advance for any advice!


-----UPDATE------------

I solved part of my problem after some debugging elsewhere in the code. Now the "i" in the "roiManager.add(image, roi, i);" command appears as the second part in the three-part name of each ROI in the roi manager, e.g "SliceNumber-i-YCoordinate". However, it would still be nice to be able to sort the ROIs by this ID number, rather than by slice--does anyone know if this is possible?