Search in sources :

Example 91 with ImagePlus

use of ij.ImagePlus in project TrakEM2 by trakem2.

the class Patch method revert.

/**
 * Revert the ImagePlus to the one stored in original_path, if any; will revert all linked patches if this is part of a stack.
 */
public boolean revert() {
    synchronized (this) {
        // nothing to revert to
        if (null == original_path)
            return false;
        // 1 - check that original_path exists
        if (!new File(original_path).exists()) {
            Utils.log("CANNOT revert: Original file path does not exist: " + original_path + " for patch " + getTitle() + " #" + id);
            return false;
        }
        // 2 - check that the original can be loaded
        final ImagePlus imp = project.getLoader().fetchOriginal(this);
        if (null == imp || null == set(imp)) {
            Utils.log("CANNOT REVERT: original image at path " + original_path + " fails to load, for patch " + getType() + " #" + id);
            return false;
        }
        // 3 - update path in loader, and cache imp for each stack slice id
        if (isStack()) {
            for (final Patch p : getStackPatches()) {
                p.project.getLoader().addedPatchFrom(p.original_path, p);
                p.project.getLoader().cacheImagePlus(p.id, imp);
                p.project.getLoader().regenerateMipMaps(p);
            }
        } else {
            project.getLoader().addedPatchFrom(original_path, this);
            project.getLoader().cacheImagePlus(id, imp);
            project.getLoader().regenerateMipMaps(this);
        }
    // 4 - update screens
    }
    Display.repaint(layer, this, 0);
    Utils.showStatus("Reverted patch " + getTitle(), false);
    return true;
}
Also used : RandomAccessFile(java.io.RandomAccessFile) File(java.io.File) ImagePlus(ij.ImagePlus)

Example 92 with ImagePlus

use of ij.ImagePlus in project TrakEM2 by trakem2.

the class Patch method exportXML.

/**
 * Opens and closes the tag and exports data. The image is saved in the directory provided in @param any as a String.
 */
@Override
public void exportXML(final StringBuilder sb_body, final String indent, final XMLOptions options) {
    // TODO the Loader should handle the saving of images, not this class.
    final String in = indent + "\t";
    String path = null;
    String path2 = null;
    if (options.export_images) {
        path = options.patches_dir + title;
        // save image without overwriting, and add proper extension (.zip)
        path2 = project.getLoader().exportImage(this, path, false);
    // path2 will be null if the file exists already
    }
    sb_body.append(indent).append("<t2_patch\n");
    String rel_path = null;
    if (null != path && path.equals(path2)) {
        // this happens when a DB project is exported. It may be a different path when it's a FS loader
        // Utils.log2("p id=" + id + "  path==path2");
        rel_path = path2;
        // TrakEM2 uses paths that always have '/' and never '\', so using java.io.File.separatorChar would be an error.
        int i_slash = rel_path.lastIndexOf('/');
        if (i_slash > 0) {
            i_slash = rel_path.lastIndexOf('/', i_slash - 1);
            if (-1 != i_slash) {
                rel_path = rel_path.substring(i_slash + 1);
            }
        }
    } else {
        // Utils.log2("Setting rel_path to " + path2);
        rel_path = path2;
    }
    // For FSLoader projects, saving a second time will save images as null unless calling it
    if (null == rel_path) {
        // Utils.log2("path2 was null");
        final Object ob = project.getLoader().getPath(this);
        path2 = null == ob ? null : (String) ob;
        if (null == path2) {
            // Utils.log2("ERROR: No path for Patch id=" + id + " and title: " + title);
            // at least some clue for recovery
            rel_path = title;
        } else {
            rel_path = path2;
        }
    }
    // Utils.log("Patch path is: " + rel_path);
    super.exportXML(sb_body, in, options);
    final String[] RGB = Utils.getHexRGBColor(color);
    int type = this.type;
    if (-1 == this.type) {
        Utils.log2("Retrieving type for p = " + this);
        final ImagePlus imp = project.getLoader().fetchImagePlus(this);
        if (null != imp)
            type = imp.getType();
    }
    sb_body.append(in).append("type=\"").append(type).append("\"\n").append(in).append("file_path=\"").append(rel_path).append("\"\n").append(in).append("style=\"fill-opacity:").append(alpha).append(";stroke:#").append(RGB[0]).append(RGB[1]).append(RGB[2]).append(";\"\n").append(in).append("o_width=\"").append(o_width).append("\"\n").append(in).append("o_height=\"").append(o_height).append("\"\n");
    if (null != original_path) {
        sb_body.append(in).append("original_path=\"").append(original_path).append("\"\n");
    }
    sb_body.append(in).append("min=\"").append(min).append("\"\n");
    sb_body.append(in).append("max=\"").append(max).append("\"\n");
    final String pps = getPreprocessorScriptPath();
    if (null != pps)
        sb_body.append(in).append("pps=\"").append(project.getLoader().makeRelativePath(pps)).append("\"\n");
    sb_body.append(in).append("mres=\"").append(meshResolution).append("\"\n");
    if (hasCoordinateTransform()) {
        sb_body.append(in).append("ct_id=\"").append(ct_id).append("\"\n");
    }
    if (hasAlphaMask()) {
        sb_body.append(in).append("alpha_mask_id=\"").append(alpha_mask_id).append("\"\n");
    }
    sb_body.append(indent).append(">\n");
    if (hasCoordinateTransform()) {
        if (options.include_coordinate_transform) {
            // Write an XML entry for the CoordinateTransform
            char[] ct_chars = null;
            try {
                ct_chars = readCoordinateTransformFile();
            } catch (final Exception e) {
                IJError.print(e);
            }
            if (null != ct_chars) {
                sb_body.append(ct_chars).append('\n');
            } else {
                Utils.log("ERROR: could not write the CoordinateTransform to the XML file!");
            }
        }
    }
    if (null != filters && filters.length > 0) {
        // specify their own line termination
        for (final IFilter f : filters) sb_body.append(f.toXML(in));
    }
    super.restXML(sb_body, in, options);
    sb_body.append(indent).append("</t2_patch>\n");
}
Also used : IFilter(ini.trakem2.imaging.filters.IFilter) ImagePlus(ij.ImagePlus) NoninvertibleModelException(mpicbg.models.NoninvertibleModelException) NoninvertibleTransformException(java.awt.geom.NoninvertibleTransformException) IOException(java.io.IOException)

Example 93 with ImagePlus

use of ij.ImagePlus in project TrakEM2 by trakem2.

the class Patch method setPreprocessorScriptPath.

/**
 * After setting a preprocessor script, it is advisable that you call updateMipMaps() immediately.
 */
public void setPreprocessorScriptPath(final String path) {
    final String old_path = project.getLoader().getPreprocessorScriptPath(this);
    if (null == path && null == old_path)
        return;
    project.getLoader().setPreprocessorScriptPath(this, path);
    if (null != old_path || null != path) {
        // Update dimensions
        // transformed by the new preprocessor script, if any
        ImagePlus imp = getImagePlus();
        final int w = imp.getWidth();
        final int h = imp.getHeight();
        imp = null;
        if (w != this.o_width || h != this.o_height) {
            // replace source ImagePlus o_width,o_height
            final int old_o_width = this.o_width;
            final int old_o_height = this.o_height;
            this.o_width = w;
            this.o_height = h;
            // scale width,height
            final double old_width = this.width;
            final double old_height = this.height;
            this.width *= ((double) this.o_width) / old_o_width;
            this.height *= ((double) this.o_height) / old_o_height;
            // translate Patch to preserve the center
            final AffineTransform aff = new AffineTransform();
            aff.translate((old_width - this.width) / 2, (old_height - this.height) / 2);
            updateInDatabase("dimensions");
            preTransform(aff, false);
        }
    }
}
Also used : AffineTransform(java.awt.geom.AffineTransform) ImagePlus(ij.ImagePlus)

Example 94 with ImagePlus

use of ij.ImagePlus in project TrakEM2 by trakem2.

the class ImageJCommandListener method commandExecuting.

// I know, I could create a hashtable and then map methods of this class to each command key ... this is just easier, and performance-wise nobody cares
// Or even a hastable with String command keys and then a number as value, and use a gigantic switch block. So much pain to write. WHAT I REALLY WANT is a switch that takes a String and is fast because it has its own hash setup.
public String commandExecuting(final String command) {
    // Utils.log2("Command: " + command);
    // 1 - check source
    ImagePlus current = WindowManager.getCurrentImage();
    // not a trakem2 display: continue happily
    if (!(current instanceof FakeImagePlus))
        return command;
    // 2 - identify project
    final FakeImagePlus fimp = (FakeImagePlus) current;
    final Display display = fimp.getDisplay();
    final LayerSet layer_set = display.getLayer().getParent();
    final Project project = display.getProject();
    final ProjectTree ptree = project.getProjectTree();
    final Displayable active = display.getActive();
    final Selection selection = display.getSelection();
    // FILE menu
    if (command.equals("Save")) {
        project.save();
        return null;
    } else // EDIT menu
    if (command.equals("Undo")) {
        // TODO forward to the active image, if any
        niy(command);
        return null;
    } else if (command.equals("Cut")) {
        // TODO forward to the active image, if any
        niy(command);
        return null;
    } else if (command.equals("Copy")) {
        // TODO forward to the active image, if any
        niy(command);
        return null;
    } else if (command.equals("Copy to System")) {
        // TODO forward to the active image, if any
        niy(command);
        return null;
    } else if (command.equals("Paste")) {
        // TODO forward to the active image, if any
        niy(command);
        return null;
    } else if (command.equals("Clear")) {
        // TODO forward to the active image, if any
        niy(command);
        return null;
    } else if (command.equals("Clear Outside")) {
        // TODO forward to the active image, if any
        niy(command);
        return null;
    } else if (command.equals("Fill")) {
        // TODO forward to the active image, if any
        niy(command);
        return null;
    } else if (command.equals("Draw")) {
        // TODO forward to the active image, if any
        niy(command);
        return null;
    } else if (command.equals("Invert")) {
        // TODO forward to the active image, if any
        niy(command);
        return null;
    } else // EDIT - SELECTION menu
    if (command.equals("Select All")) {
        if (ProjectToolbar.SELECT == Toolbar.getToolId()) {
            selection.selectAll();
            return null;
        }
        return command;
    } else if (command.equals("Select None")) {
        if (ProjectToolbar.SELECT == Toolbar.getToolId()) {
            display.select(null);
            return null;
        }
        return command;
    } else if (command.equals("Restore Selection")) {
        if (ProjectToolbar.SELECT == Toolbar.getToolId()) {
            selection.restore();
            return null;
        }
        return command;
    } else // IMAGE - TYPE menu
    if (command.equals("8-bit")) {
        // TODO forward to the active image, if any
        niy(command);
        return null;
    } else if (command.equals("16-bit")) {
        // TODO forward to the active image, if any
        niy(command);
        return null;
    } else if (command.equals("32-bit")) {
        // TODO forward to the active image, if any
        niy(command);
        return null;
    } else if (command.equals("8-bit Color")) {
        // TODO forward to the active image, if any
        niy(command);
        return null;
    } else if (command.equals("RGB Color")) {
        // TODO forward to the active image, if any
        niy(command);
        return null;
    } else if (command.equals("RGB Stack") || command.equals("HSB Stack")) {
        Utils.showMessage("Can't convert to " + command);
        return null;
    } else // IMAGE - ADJUST menu
    if (command.equals("Brightness/Contrast...")) {
        // TODO forward to the active image, if any
        niy(command);
        return null;
    } else if (command.equals("Window/Level...")) {
        // TODO forward to the active image, if any
        niy(command);
        return null;
    } else if (command.equals("Color Balance...")) {
        // TODO forward to the active image, if any
        niy(command);
        return null;
    } else if (command.equals("Threshold...")) {
        // TODO forward to the active image, if any
        niy(command);
        return null;
    } else if (command.equals("Size...")) {
        if (null != active)
            selection.specify();
        return null;
    } else if (command.equals("Canvas Size...")) {
        display.resizeCanvas();
        return null;
    } else // IMAGE menu
    if (command.equals("Show Info...")) {
        // TODO perhaps it should show only for images ...
        if (null == active) {
            ptree.showInfo(project.getRootProjectThing());
        } else {
            ProjectThing pt = project.findProjectThing(active);
            if (null != pt)
                ptree.showInfo(pt);
        }
        return null;
    } else // IMAGE - COLOR menu
    if (in(command, new String[] { "RGB Split", "RGB Merge...", "Stack to RGB", "Make Composite" })) {
        notAvailable(command);
        return null;
    } else if (command.equals("Show LUT")) {
        return setTempCurrentImage(command, active);
    } else if (command.equals("Edit LUT...")) {
        // TODO forward to the active image, if any
        niy(command);
        return null;
    } else if (command.equals("Average Color")) {
        // TODO forward to the active image, if any
        niy(command);
        return null;
    } else if (command.equals("RGB to CIELAB")) {
        // TODO forward to the active image, if any
        niy(command);
        return null;
    } else if (command.equals("RGB to Luminance")) {
        // TODO forward to the active image, if any
        niy(command);
        return null;
    } else // IMAGE STACK menu
    if (in(command, new String[] { "Add Slice", "Delete Slice" })) {
        Utils.showMessage("Go to the Layer Tree and right-click to add/delete a layer.");
        return null;
    } else if (command.equals("Next Slice [>]")) {
        display.nextLayer(IJ.shiftKeyDown() ? Event.SHIFT_MASK : 0);
        return null;
    } else if (command.equals("Previous Slice [<]")) {
        display.previousLayer(IJ.shiftKeyDown() ? Event.SHIFT_MASK : 0);
        return null;
    } else if (in(command, new String[] { "Set Slice", "Images to Stack", "Stack to Images", "Make Montage..." })) {
        notAvailable(command);
        return null;
    } else if (command.equals("Reslice [/]...")) {
        // TODO
        niy(command);
        return null;
    } else if (command.equals("Z Project...")) {
        // TODO
        niy(command);
        return null;
    } else if (command.equals("3D Project...")) {
        // TODO
        niy(command);
        return null;
    } else if (command.equals("Plot Z-axis Profile")) {
        // TODO
        niy(command);
        return null;
    } else if (command.equals("Start Animation [\\]")) {
        // TODO
        niy(command);
        return null;
    } else if (command.equals("Stop Animation")) {
        // TODO
        niy(command);
        return null;
    } else // IMAGE menu again
    if (command.equals("Crop")) {
        notAvailable(command);
        return null;
    } else if (in(command, new String[] { "Translate...", "Scale..." })) {
        if (null != active)
            selection.specify();
        return null;
    } else if (command.equals("Duplicate...")) {
        if (null != active && active.getClass().equals(Patch.class)) {
            // TODO stacks?
            // 2.5 security factor: for awt in non-1.6.0 machines
            project.getLoader().releaseToFit((long) (project.getLoader().estimateImageFileSize((Patch) active, 0) * 2.5));
            new ImagePlus(active.getTitle(), ((Patch) active).getImageProcessor().duplicate()).show();
        }
        return null;
    } else if (command.equals("Rename...")) {
        if (null != active) {
            active.adjustProperties();
            Display.updateSelection();
        }
        return null;
    } else // IMAGE ROTATE menu
    if (command.equals("Flip Horizontally")) {
        selection.apply(2, new double[] { -1, 1 });
        return null;
    } else if (command.equals("Flip Vertically")) {
        selection.apply(2, new double[] { 1, -1 });
        return null;
    } else if (command.equals("Rotate 90 Degrees Right")) {
        selection.apply(1, new double[] { 90 });
        return null;
    } else if (command.equals("Rotate 90 Degrees Left")) {
        selection.apply(1, new double[] { -90 });
        return null;
    } else if (command.equals("Arbitrarily...")) {
        if (null != active)
            selection.specify();
        return null;
    } else // IMAGE ZOOM menu
    if (command.equals("To Selection")) {
        Roi roi = fimp.getRoi();
        if (null != roi) {
            Rectangle b = roi.getBounds();
            b.x -= b.width / 2;
            b.y -= b.height / 2;
            b.width *= 2;
            b.height *= 2;
            display.getCanvas().showCentered(b);
        }
        return null;
    } else if (command.equals("View 100%")) {
        // TODO
        niy(command);
        return null;
    } else // ANALYZE menu
    if (command.equals("Measure")) {
        // Minimal measurement: area of closed ROIs, length of unclosed ROIs, calibrated.
        Roi roi = fimp.getRoi();
        if (null != roi) {
            Calibration cal = fimp.getCalibration();
            AffineTransform caff = new AffineTransform();
            caff.scale(cal.pixelWidth, cal.pixelHeight);
            if (M.isAreaROI(roi)) {
                Area area = M.getArea(roi);
                area = area.createTransformedArea(caff);
                ResultsTable rt = Utils.createResultsTable("ROI area", new String[] { "area", "perimeter" });
                rt.incrementCounter();
                rt.addLabel("units", cal.getUnit());
                rt.addValue(0, Math.abs(AreaCalculations.area(area.getPathIterator(null))));
                rt.addValue(1, roi.getLength());
                rt.show("ROI area");
            } else {
                ResultsTable rt = Utils.createResultsTable("ROI length", new String[] { "length" });
                rt.incrementCounter();
                rt.addLabel("units", cal.getUnit());
                rt.addValue(0, roi.getLength());
                rt.show("ROI length");
            }
            return null;
        } else if (null != active) {
            // Measure the active displayable
            if (active.getClass() == Patch.class) {
                // measure like 'm' would in ImageJ for an image
                ImagePlus imp = ((Patch) active).getImagePlus();
                imp.setCalibration(active.getLayer().getParent().getCalibrationCopy());
                IJ.run(imp, "Measure", "");
            } else {
                // Call measure like ProjectThing does
                ProjectThing pt = active.getProject().findProjectThing(active);
                if (active instanceof Profile)
                    ((ProjectThing) pt.getParent()).measure();
                else
                    pt.measure();
            }
            return null;
        }
        Utils.log("Draw a ROI or select an object!");
        return null;
    } else if (in(command, new String[] { "Analyze Particles...", "Histogram", "Plot Profile", "Surface Plot...", "Color Inspector 3D", "3D Surface Plot", "Color Histogram" })) {
        return setTempCurrentImage(command, active);
    } else if (command.equals("Label")) {
        notAvailable(command);
        return null;
    } else // PLUGINS menu
    if (command.equals("Volume Viewer")) {
        return runOnVirtualLayerSet(command, layer_set, display);
    } else if (command.equals("3D Viewer")) {
        // it's virtual and non-caching, will appear as a regular ImageJ stack
        layer_set.createLayerStack(Displayable.class, ImagePlus.COLOR_RGB, display.getDisplayChannelAlphas()).getImagePlus().show();
        return command;
    } else // PROCESS menu and submenus
    if (in(command, new String[] { "FFT", "Fast FFT (2D/3D)" })) {
        return setTempCurrentImage(command, active);
    } else if (in(command, new String[] { "Bandpass Filter...", "Custom Filter...", "FD Math...", "Swap Quadrants", "Convolve...", "Gaussian Blur...", "Median...", "Mean...", "Minimum...", "Maximum...", "Unsharp Mask...", "Variance...", "Show Circular Masks...", "Subtract Background..." })) {
        return duplicate(command, active);
    } else if (in(command, new String[] { "Smooth", "Sharpen", "Find Edges", "Enhance Contrast", "Add Noise", "Add Specified Noise...", "Salt and Pepper", "Despeckle", "Remove Outliers...", "North", "Northeast", "East", "Southeast", "South", "Southwest", "West", "Northwest", "Make Binary", "Convert to Mask", "Find Maxima...", "Erode", "Dilate", "Open ", "Close-", "Outline", "Fill Holes", "Skeletonize", "Distance Map", "Ultimate Points", "Watershed", "Add...", "Subtract...", "Multiply...", "Divide...", "AND...", "OR...", "XOR...", "Min...", "Max...", "Gamma...", "Log", "Exp", "Square", "Square Root", "Reciprocal", "NaN Background", "Abs" })) {
        return duplicate(command, active);
    }
    /*else {
			// continue happily
			//Utils.log2("Skipping " + command);
		}*/
    // If it's part of "Save As", ignore it
    Menu menu = Menus.getSaveAsMenu();
    for (int i = menu.getItemCount() - 1; i > -1; i--) {
        if (command.equals(menu.getItem(i).getActionCommand())) {
            notAvailable(command);
            return null;
        }
    }
    // Give it back to ImageJ
    return command;
}
Also used : Rectangle(java.awt.Rectangle) Calibration(ij.measure.Calibration) ImagePlus(ij.ImagePlus) Roi(ij.gui.Roi) Project(ini.trakem2.Project) Area(java.awt.geom.Area) ProjectTree(ini.trakem2.tree.ProjectTree) AffineTransform(java.awt.geom.AffineTransform) ResultsTable(ij.measure.ResultsTable) Menu(java.awt.Menu) ProjectThing(ini.trakem2.tree.ProjectThing)

Example 95 with ImagePlus

use of ij.ImagePlus in project TrakEM2 by trakem2.

the class ImageJCommandListener method duplicate.

/**
 * Duplicate the active image (if any) and set it as active, so the command is run on it.
 */
private String duplicate(final String command, final Displayable active) {
    if (!isPatch(command, active))
        return null;
    Patch pa = (Patch) active;
    Project project = pa.getProject();
    project.getLoader().releaseToFit((long) (project.getLoader().estimateImageFileSize(pa, 0) * 5));
    // don't show it yet
    ImagePlus imp = new ImagePlus("Copy of " + pa.getTitle(), pa.getImageProcessor().duplicate());
    WindowManager.setTempCurrentImage(imp);
    imp.show();
    // now execute command
    return command;
}
Also used : Project(ini.trakem2.Project) ImagePlus(ij.ImagePlus)

Aggregations

ImagePlus (ij.ImagePlus)363 ImageStack (ij.ImageStack)85 ImageProcessor (ij.process.ImageProcessor)74 Rectangle (java.awt.Rectangle)60 ArrayList (java.util.ArrayList)46 IOException (java.io.IOException)40 File (java.io.File)36 Roi (ij.gui.Roi)32 Point (java.awt.Point)32 ByteProcessor (ij.process.ByteProcessor)29 FormatException (loci.formats.FormatException)29 GenericDialog (ij.gui.GenericDialog)27 Calibration (ij.measure.Calibration)26 FloatProcessor (ij.process.FloatProcessor)22 Future (java.util.concurrent.Future)22 ExtendedGenericDialog (uk.ac.sussex.gdsc.core.ij.gui.ExtendedGenericDialog)22 LinkedList (java.util.LinkedList)21 ExecutorService (java.util.concurrent.ExecutorService)19 MemoryPeakResults (uk.ac.sussex.gdsc.smlm.results.MemoryPeakResults)19 PointRoi (ij.gui.PointRoi)17