Jython Scripting

Revision as of 15:37, 13 June 2008 by Albertcardona (talk | contribs) (New page: <h1>Jython tutorial for ImageJ</h1> <h3>Language basics</h3> <p>Any text after a # is commented out.</p> <p>There are no line terminators (such as ';' in other languages), neither curly b...)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Jython tutorial for ImageJ

Language basics

Any text after a # is commented out.

There are no line terminators (such as ';' in other languages), neither curly braces to define code blocks.

Indentation defines code blocks.

Functions are defined with def, and classes with class. <p>Functions are objects, and thus storable in variables.

Jython (and python in general) accepts a mixture of procedural and object-oriented code.

Defining variables: obtaining the current image

imp = IJ.getImage()

Which is the same as:

imp = WindowManager.getCurrentImage()

Since calling the above is long and tedious, one can declare a variable that points to the above static methods:

c = WindowManager.getCurrentImage

Above note the lack of parentheses.

To execute the function, just use parentheses on it:

imp = c()

The above gets the value of c, which is the method named getCurrentImage in class WindowManager, and executes it, storing its returned object in imp.

Manipulating pixels

Creating a grayscale ramp image

First create an image and obtain its pixels:

imp = ImagePlus("my new image", FloatProcessor(512, 512))
pix = imp.getProcessor().getPixels()

The length of an array:

n_pixels = len(pix)

Then loop to modify them:

# catch width
w = imp.getWidth()

# create a ramp gradient from left to right
for i in range(len(pix)):
  pix[i] = i % w

# adjust min and max, since we know them
imp.getProcessor().setMinAndMax(0, w-1)

... and show the new image:


Creating a random 8-bit image

The Jython interpreter plugin

Launch it from plugins - Scripting - Jython Interpreter.

Creating jython scripts