Saturday, May 12, 2007

Automating simple file management tasks with BeanShell, Part 1

It's been a couple months now I've been working on our company's artificial vision system. Programming it has been quite an adventure, worth of a series of posts (which I might start sometime soon); today, however, I'd like to talk about a relatively simpler file management problem I faced, and how BeanShell helped me out of it.

For those of you who don't know BeanShell, it is basically interpreted Java with loosened type checks. It is closely integrated to the Java platform, meaning you can import and use Java classes just as you'd do in a regular Java program; it also comes with a set of scripts that, among other things, reproduce basic UNIX shell commands. Despite being in a rather stale state for some time now, it remains a very useful tool in my programmer's toolbox, and being the default scripting tool for jEdit – my default text editor, and another project that could use an upgrade – means it is always close at hand.

But back to my problem: the other day the project manager handled me a set of calibration pictures for our system. The set was comprised of eighteen picture pairs; each pair showed the same object, simultaneously captured by a pair of cameras mounted on a fixed support. In order to be loaded by the calibration software, pictures must be named left[i] or right[i] (depending on whether they were captured by the left or right camera), where [i] is the pair's index.

So far so good, save for two details: all "right" pictures were misprefixed "rigth", and all pair prefixes were inversed – that is, all pictures prefixed "left" actually came from the right camera, and vice-versa. Were I in a UNIX environment, I could easily write a shell script to remedy that situation, but what do you do whe you're stuck with Windows?

It turns out it is quite easy to write file management routines in BeanShell. So I opened jEdit and simply coded:


String basepath = "C:/images/";
for (int i = 1; i <= 18; i++)
{
mv(basepath + "left" + i + ".bmp",
basepath + "temp" + i + ".bmp");

mv(basepath + "rigth" + i + ".bmp",
basepath + "left" + i + ".bmp");

mv(basepath + "temp" + i + ".bmp",
basepath + "right" + i + ".bmp");
}


One "Evaluate Selection" later and it was done. It doesn't get much easier than that.