Difference between revisions of "Scripting toolbox"

(Consolidate "see also" links, and add BAR to the list)
(Add a note that tutorials should be added to the wiki (personal web space is prone to get garbage collected))
Line 6: Line 6:
 
* [[Scripting comparisons]] to compare and contrast the languages.
 
* [[Scripting comparisons]] to compare and contrast the languages.
 
* [[BAR|Broadly Applicable Routines]], a curated collection of snippets.
 
* [[BAR|Broadly Applicable Routines]], a curated collection of snippets.
* Albert Cardona's comprehensive [http://www.ini.uzh.ch/~acardona/fiji-tutorial/ Fiji Jython tutorial].
+
* Albert Cardona's comprehensive [http://www.ini.uzh.ch/~acardona/fiji-tutorial/ Fiji Jython tutorial] (please note that it is better idea to contribute tutorials to the ImageJ/Fiji wiki directly).
 
}}
 
}}
 
'''Note:''' To copy the snippets, just double-click somewhere into the code. If Javascript is enabled, this will automatically select the complete snippet.
 
'''Note:''' To copy the snippets, just double-click somewhere into the code. If Javascript is enabled, this will automatically select the complete snippet.

Revision as of 08:09, 16 September 2014

Template:ScriptingThis page is meant to provide small code snippets as a starting point for writing scripts.


Note: To copy the snippets, just double-click somewhere into the code. If Javascript is enabled, this will automatically select the complete snippet.

Opening an image using ImageJ

Macro

path = "/path/to/file";
open(path);

Javascript

importClass(Packages.ij.IJ);

var path = "/path/to/file";
var imp = IJ.openImage(path);
imp.show();

Python

from ij import IJ

path = "/path/to/file"
imp = IJ.openImage(path)
imp.show()

Ruby

include_class 'ij.IJ'

path = "/path/to/file"
imp = ij.IJ.openImage(path)
imp.show

Clojure

(import 'ij.IJ)

(let [path "/path/to/file"
      imp (IJ/openImage path)]
  (.show imp))

Beanshell

import ij.IJ;

path = "/path/to/file";
imp = IJ.openImage(path);
imp.show();

Opening an image using Bio-Formats

Macro

path = "/path/to/file";
run("Bio-Formats Importer", "open=" + path + "autoscale color_mode=Default view=Hyperstack stack_order=XYCZT");

Javascript

importClass(Packages.loci.plugins.BF);

var path = "/path/to/file";
var imps = BF.openImagePlus(path);

imps[0].show();

or, with more options:

importClass(Packages.loci.plugins.BF);
importClass(Packages['loci.plugins.in.ImporterOptions']); // 'in' is a reserved word, hence the different syntax
importClass(Packages.loci.common.Region);


var path = "/path/to/file";
var options = new ImporterOptions();
options.setId(path);
options.setAutoscale(true);
options.setCrop(true);
options.setCropRegion(0, new Region(x, y, w. h));
options.setColorMode(ImporterOptions.COLOR_MODE_COMPOSITE);
var imps = BF.openImagePlus(options);

imps[0].show();
  • Python
  • Ruby
  • Clojure
  • Beanshell

Opening, processing, and saving a sequence of files in a folder

Macro

dir1 = getDirectory("Choose Source Directory ");
dir2 = getDirectory("Choose Destination Directory ");
list = getFileList(dir1);

for (i=0; i<list.length; i++) {
  if (endsWith(list[i], ".tif")) {
    open(dir1 + list[i]);
    // process the image
    saveAs("TIFF", dir2+list[i]);
    close();
  }
}

See also the tutorial How to apply a common operation to a complete directory.

  • Javascript
  • Python
  • Ruby
  • Clojure
  • Beanshell

Wait a given amount of time, or until user presses OK

Macro

wait(100);

or

waitForUser();

Javascript

Thread.sleep(100);

or

new WaitForUserDialog("Action required", "Please press OK when done.").show();
  • Python
  • Ruby
  • Clojure
  • Beanshell

Select multiple ROIs from ROI manager and combine them

Macro

roiManager("select", newArray(0,2,4));
roiManager("AND");

Javascript

importClass(Packages.ij.plugin.frame.RoiManager);

rm = RoiManager.getInstance();
rm.setSelectedIndexes([0,2,4]);
rm.runCommand("AND");

Python

from ij.plugin.frame import RoiManager

rm = RoiManager.getInstance()
rm.setSelectedIndexes([0, 2, 4])
rm.runCommand("AND")

Beanshell

import ij.plugin.frame.RoiManager;

rm = RoiManager.getInstance();
rm.setSelectedIndexes(new int[] { 0, 2, 4});
rm.runCommand("AND");
  • Ruby
  • Clojure

Unlocking an image

Sometimes things go wrong and all you see is "blabla.jpg is locked" when you try to process the image in some way. Then all you can do is to force-unlock the image, like so:

Beanshell

IJ.getImage().unlock();

Scripting SIFT

The Scale-Invariant Feature Transform poses a relatively powerful way to reduce the complexity when trying to find matching parts of large images. Fiji has an implementation of this algorithm which you can use like so:

Beanshell

import java.util.ArrayList;

import mpicbg.ij.SIFT;
import mpicbg.imagefeatures.Feature;
import mpicbg.imagefeatures.FloatArray2DSIFT;

param = new FloatArray2DSIFT.Param();
sift = new SIFT(new FloatArray2DSIFT(param));
features = new ArrayList();
// ''ip'' refers to an ImageProcessor
sift.extractFeatures(ip, features);

// print coordinates
for (Feature feature : features)
    print("x: " + feature.location[0] + ", y: " + feature.location[1]);

For more information, please browse the Javadoc of the Feature class.

Plotting charts with JFreeChart

JFreeChart is a Java library for creating various charts. You can create charts as interactive JFrames, display them as an ImagePlus, or write them to SVG format.

Javascript

/* Javascript to test JFreeChart functionality */

importPackage(Packages.org.jfree.chart);
importPackage(Packages.org.jfree.chart.plot);
importPackage(Packages.org.jfree.chart.axis);
importPackage(Packages.org.jfree.chart.encoders);
importPackage(Packages.org.jfree.chart.renderer.category);

importPackage(Packages.java.awt);
importPackage(Packages.java.awt.geom);
importPackage(Packages.java.io);

importPackage(Packages.org.jfree.ui);
importPackage(Packages.org.jfree.data.category);
importPackage(Packages.org.jfree.data.statistics);

importPackage(Packages.org.apache.batik.dom);
importPackage(Packages.org.apache.batik.svggen);

var dataset = new DefaultStatisticalCategoryDataset();

// dataset.add(Mean, StdDev, "Series", "Condition")
dataset.add(15.0, 2.4, "Row 1", "Column 1");
dataset.add(15.0, 4.4, "Row 1", "Column 2");
dataset.add(13.0, 2.1, "Row 1", "Column 3");
dataset.add(7.0, 1.3, "Row 1", "Column 4");
dataset.add(2.0, 2.4, "Row 2", "Column 1");
dataset.add(18.0, 4.4, "Row 2", "Column 2");
dataset.add(28.0, 2.1, "Row 2", "Column 3");
dataset.add(17.0, 1.3, "Row 2", "Column 4");

var chart = ChartFactory.createLineChart(
	null,					// chart title
	"Treatment",				// domain axis label
	"Measurement",				// range axis label
	dataset,				// data
	PlotOrientation.VERTICAL,		// orientation
	false,					// include legend
	true,					// tooltips
	false					// urls
);

// set the background color for the chart...
chart.setBackgroundPaint(Color.white);

var plot = chart.getPlot();
plot.setBackgroundPaint(Color.white);
plot.setRangeGridlinesVisible(false);
plot.setAxisOffset(RectangleInsets.ZERO_INSETS);

// customise the range axis...
var rangeAxis = plot.getRangeAxis();
rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
rangeAxis.setAutoRangeIncludesZero(true);
rangeAxis.setRange(0, 40);

// customise the renderer...
var renderer = new StatisticalBarRenderer();
renderer.setErrorIndicatorPaint(Color.black);
renderer.setSeriesOutlinePaint(0,Color.black);
renderer.setSeriesOutlinePaint(1,Color.black);
renderer.setSeriesPaint(0,Color.black);
renderer.setSeriesPaint(1,Color.white);
renderer.setItemMargin(0.0);
plot.setRenderer(0,renderer);

renderer.setDrawBarOutline(true);

bi = chart.createBufferedImage(600, 400);

imp = new ImagePlus("Chart Test", bi);
imp.show();

// Create SVG image
// Get a DOMImplementation and create an XML document
var domImpl = GenericDOMImplementation.getDOMImplementation();
var document = domImpl.createDocument(null, "svg", null);

// Create an instance of the SVG Generator
var svgGenerator = new SVGGraphics2D(document);

// draw the chart in the SVG generator
var bounds = new Rectangle(600, 400);
chart.draw(svgGenerator, bounds);

var dir = IJ.getDirectory("Where should the svg file be saved?");
// Write svg file
var svgFile = new File(dir + "test.svg");
var outputStream = new FileOutputStream(svgFile);
var out = new OutputStreamWriter(outputStream, "UTF-8");
svgGenerator.stream(out, true /* use css */);
outputStream.flush();
outputStream.close();