Jython tutorial for ImageJ
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.
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.