Skip to content

Dear Internet Explorer user: Your browser is no longer supported

Please switch to a modern browser such as Microsoft Edge, Mozilla Firefox or Google Chrome to view this website's content.

Check file names with RegEx in ImageJ

Use regular expressions to apply different steps in an ImageJ macro script by querying the file name.

A colleague of mine approached me and asked whether I could use ImageJ to measure the growth of her fungal cultures that were grown in petri dishes on six different types of media (named “A”, “B”, “C”, “D”, “E” and “F”). Unfortunately I could not use the same thresholding values in my ImageJ macro to analyse all of the images in the batch because the media were different colours.

Then it occurred to me: Can I just write a rule which queries the filename and then applies a different analysis depending on the result? The answer is ‘yes’ and I can do it with regular expressions too!

As it turns out, media “A” and “B” are the same colour, as are “C” and “D” and then “E” is similar to “F”. Sensibly, I encoded the media type in the file name so a regular expression could be used to test this. (The regular expression is .*[AB]\.[jJ][pP]e*[gG]$ – I won’t go into the details of how the regex was constructed as it is beyond the scope of this article).

Using my Image J batch processing macro where file is the variable containing the file name, I was able to query the file name and have ImageJ do something different for each image depending on its name:

if (matches(file, ".*[AB]\\.[jJ][pP]e*[gG]$")) {print("A or B");} else
if (matches(file, ".*[CD]\\.[jJ][pP]e*[gG]$")) {print("C or D");} else
if (matches(file, ".*[EF]\\.[jJ][pP]e*[gG]$")) {print("E or F");}

In this example, I simply asked ImageJ to print “A or B”, “C or D” or “E or F” (as is appropriate) but of course this can be substituted for any function. You can also test the image title via getTitle(). My real-world example is as follows:

title=getTitle();
if (matches(title, ".*[AB]\\.[jJ][pP]e*[gG]$")) {setThreshold(146.0000, 255.0000);} else
if (matches(title, ".*[CD]\\.[jJ][pP]e*[gG]$")) {setThreshold(22.0000, 189.01);} else
if (matches(title, ".*[EF]\\.[jJ][pP]e*[gG]$")) {
	setAutoThreshold("Shanbhag");
	setThreshold(82.5660, 255.0000);
	} 

This functionality is especially useful where an image analysis pipeline is uniform except for a couple of steps.

Note: Back-slashes need to be escaped (ie \\, hence the discrepancy between the regex in the ImageJ macro code and the original regex.

   

Comments

No comments have yet been submitted. Be the first!

Have Your Say

The following HTML is permitted:
<a href="" title=""> <b> <blockquote cite=""> <code> <em> <i> <q cite=""> <strike> <strong>

Comments will be published subject to the Editorial Policy.