Login  Register

Re: Fiji - Jython Interpreter, how does it work?

Posted by Albert Cardona on Apr 10, 2009; 9:14am
URL: http://imagej.273.s1.nabble.com/Fiji-Jython-Interpreter-how-does-it-work-tp3692998p3693001.html

maringa wrote:
>  Thanks a lot Albert!
>  Now I have a lot of tutorials and pages to read through!
>  Do you think it's a good idea to use Jython when developing plugins? It
>  feels like the MacroJ is too week to create anything userfriendly, at
>  least that is my impression of it. I also found some information about
>  Beanshell, but that is perhaps very similar (when it comes to user
>  friendlyness and structure) to Jython?


By "MacroJ" I guess you mean the ImageJ Macro Language.
The Macro language is great to record a dozen of commands and then
execute that in batch mode using the Multiple Image Processor plugin,
for example.
Beyond a dozen lines, ImageJ Macros become very difficult to understand
a few weeks after being written. I would discourage you to write Macros
other than by using the recorder and editing its output a bit.

Jython is orders of magnitude cleaner to read, and furthermore, way more
powerful: you may use abstractions like classes, collections,
dictionaries, sets, tuples, and even do multithreading (see for example
the plugins/Examples/Delayed_Snapshot.py script for how to launch a
separate thread). Also functions are first-class citizens, so you may
pass functions as arguments to other functions, which is very useful. In
short, Jython is a complete, proper language for writing plugins.

An example of a dictionary containing two new images:

 >>> images = {}
 >>> images["first one"] = ImagePlus("one", ByteProcessor(100, 100))
 >>> images["other"] = ImagePlus("other", FloatProcessor(200, 200))


 >>> print len(images)
 2


Now loop your dictionary and print its data:

 >>> for name, image in images.iteritems():
       print "Name is", name, "and the image is", image

 Name is other and the image is imp[other 200x200x1]
 Name is first one and the image is imp[one 100x100x1


Now query one image by the name key:

 >>> imp = images["other"]
 >>> print imp
 imp[other 200x200x1]


Now define a generic function that applies a function to each
value in the dictionary:

 >>> def apply_to_all(table, fn):
       for value in table.values():
         fn(value)


Then use it to apply an anonymous function to each image:

 >>> apply_to_all(images, lambda x: x.show())

... which results in all images in the dictionary being shown.


Be careful that python specifies it's code blocks not by curly brackets
like java does, but by indentation of its lines., Emails are famous for
not respecting line indentation.


>  Thanks again for your extensive answer!

You are welcome.

Albert
--
Albert Cardona
http://albert.rierol.net