BAR

Revision as of 07:36, 27 October 2014 by Eglinger (talk | contribs) (Adjusted instructions how to install from update sites; correct typos)

BAR (ImageJ/Fiji)
Maintainer Tiago Ferreira
Source on GitHub
Initial release June 2014
Category Analysis, Annotation, Filtering, Segmentation, Scripting


BAR: A collection of Broadly Applicable Routines.

The collection contains Macros, Scripts and Plugins focused on Data Analysis, Image Annotation, Image Segmentation and Bitmap Morphometry. It is curated using GitHub and distributed as an optional update site.

Installation

The easiest way is to install and maintain the collection is to subscribe to the BAR update site. By doing so you will not need to manually download and install anything: the Fiji Updater will take care of it for you:
Run Help▷ Update... and choose Manage update sites. Activate the BAR checkbox in the alphabetically-sorted list of update sites. Press OK, then Apply changes. Restart ImageJ. That's it. Enjoy BAR!

Alternatively, if you prefer to manually install and update the collection, you can do so through GitHub: either by downloading individual files, or by downloading the entire repository as a ZIP archive.

Description

BAR files are accessible through a dedicated top-level menu subdivided in task-oriented categories. Some of the routines have a dedicated documentation page, others feature built-in help while a handful were deemed too simple to require dedicated instructions. Nevertheless, all files are described in the Details panel of the Fiji Updater and contain useful commentary at the top of the source code file.

Tip: You can open any BAR script by holding Shift while selecting its name from the BAR▷ menu. For pre-compiled java plugins, the source code is available through the About BAR... command.


Overview of BAR (v1.0.0)

List of BARs

Annotation
ROI Color Coder
Data Analysis
Distribution Plotter
Find Peaks
Fit Polynomial
Plot Results
Morphometry
Strahler Analysis
Segmentation
Shen-Castan Edge Detector
Apply Threshold To ROI
Clear Thresholded Pixels
Remove Isolated Pixels
Threshold From Background
Wipe Background
Snippets
This submenu lists generic and reusable scripts to be recycled at will in personalized workflows. Any script or macro file stored in the Snippets folder with an underscore "_" in the filename will be listed here.
Tools and Toolsets
Calibration Menu
ROI Manager Tools
Segment Profile
Shortcuts Menu
Toolset Creator

Accessing BARs

BAR commands can be accessed in multiple ways: 1) through the BAR▷ menu, 2) the Context Menu, 3) Keyboard Shortcuts, 3) the Shortcuts Menu Tool (BAR▷ Tool Installers▷ Install Shortcuts Menu), that registers frequently used commands in the ImageJ toolbar or, as most ImageJ commands, 4) from other scripts, macros and plugins.

Context Menu

BAR features a neat mechanism that allows BAR▷ commands to shuttle between the main menu bar and the image's context menu.

BAR▷ submenus can be appended to the image's context menu (the menu that pops up when right-clicking on the image canvas) by running BAR▷ Submenu▷Move Menu (Context<>Main). The transfer is bidirectional: once in the context menu, running the same command will place the submenu back in the main menu bar.

The shuttling mechanism is not permanent, i.e., it will not be remembered across restarts. However, it is macro recordable which means it can be imposed at startup, using the ImageJ macro language. So, e.g., to install BAR▷ Segmentation▷ in the context menu, one would:

  1. Start the Macro Recorder ( Plugins▷ Macros▷ Record...)
  2. Run BAR▷ Segmentation▷ Move Menu (Context<>Main)
  3. Open the Edit▷ Options▷ Startup... window and paste the string generated by the Macro Recorder into its text area so that ImageJ can run the command at every startup.


It may be wise to allow ImageJ enough time to register all scripts before triggering transfers to the context menu (remember: The structure of the BAR▷ menu reflects plugins stored in Plugins/BAR_-1.x.x.jar and scripts saved in the Plugins/Scripts/BAR/ directory). This can be achieved through the built-in macro function wait(). For a slow setup requiring at least 1 second (1000 milliseconds), the pasted code would look something like this:

StartupBAR.png


Notes

  • The several Move Menu (Context<>Main) commands across BAR▷ submenus do not use the same label and are distinguishable by extra trailing spaces. This is intentional because all ImageJ commands must have unique names.
  • Any toolset loaded via the ">>" More Tools drop down menu can define its own contextual menu (as detailed in the ImageJ User Guide, the contextual menu is controlled by a macro called Popup Menu that gets loaded at startup). To have BARs immediately available when such toolsets are loaded, just append the same run("Move Menu (Context<>Main)"); call described above for StartupMacros.

Keyboard Shortcuts

You can use Plugins▷ Shortcuts▷ Create Shortcut... to assign hotkeys (e.g., keyboard key that you do not use frequently such as 0 or F7) to any script registered in the BAR▷ menu. These shortcuts will be listed in Plugins▷ Shortcuts▷ and are remembered across restarts.

Alternatively, keyboard shortcuts can be defined in macros that call BAR commands by placing the shortcut key within square brackets at the end of the macro name. Such macros can pass specific options to BAR commands, allowing scripts to run without prompt. Example:

macro "Remove Round Structures [0]" {
    run("Wipe Background", "size=100 circ.=0.75-1.00"); // Runs Wipe_Background.ijm with the specified parameters 
}

As mentioned, such macros can then be pasted into the text area of Edit▷ Options▷ Startup... so that they can be executed when ImageJ starts up.

Scripting BARs

Template:ScriptingAlthough BARs can be used as standalone commands (launched e.g., by pressing L, the Command Launcher shortcut), the scripts and plugins in BAR become more useful when incorporated into other routines. Indeed, they are designed to function as snippets.

Snippets

BAR contains a growing depository of reusable scripts to be used as scripting templates. Below is an example, taken from Process_Folder.ijm, a more customizable and modular alternative to the Process▷ Batch▷ Macro... built-in command. This snippet, an ImageJ macro that applies a common operation to a directory, is composed of four functions:

  1. expectedImage(): Determines wich image types should be processed
  2. getOutputDirectory(): Sets a destination folder to save processed images
  3. myRoutines(): Container to hold the image processing routines
  4. processImage(): Applies myRoutines() to each individual image


Because all the tasks required to iterate through the files are handled by separated functions, only the myRoutines() function needs to be edited e.g., with code generated by the Macro Recorder. It can also call macros and scripts saved elsewhere. Example:

function myRoutines() {
    runMacro("/Path/to/Coolest/Macro.ijm");
    eval("python", "/Path/to/Coolest/Script.py");
}

Here is how the assembled snippet looks like:

// Define which images should be processed. Only file extensions listed in this
// array will be accepted as valid by expectedImage(). Note that certain files
// may not be handled by IJ directly but by other plugins, such as Bio-Formats
var extensions = newArray(".tif", ".stk", ".oib");

// Define input directory
inputDir = getDirectory("Select a source directory");

// Define output directory
outputDir = getOutputDirectory(inputDir);

// Iterate through inputDir, ignore files with non-specified extensions and save
// a copy of processed images in outputDir
processImage(inputDir, outputDir);

showMessage("All done!");


/* This function defines all the image manipulation routines. */
function myRoutines() {
	// <Your code here>
}

/*
 * This function retrieves the full path to a "Processed" folder placed at the
 * same location of <input_dir>. For safety, the macro is aborted if <input_dir>
 * is not accessible or if the directory cannot be created, e.g., due to lack of
 * appropriate credentials. It does nothing if such a directory already exists.
 */
function getOutputDirectory(input_dir) {
	if (!File.isDirectory(input_dir)) {
		exit("Macro aborted: The directory\n'"+ input_dir +"'\nwas not found.");
	}
	if (endsWith(input_dir, File.separator)) {
		separatorPosition = lengthOf(input_dir);
		input_dir = substring(input_dir, 0, separatorPosition-1);
	}
	new_dir = input_dir + "_Processed" + File.separator;
	if (!File.isDirectory(new_dir)) {
		File.makeDirectory(new_dir);
		if (!File.isDirectory(new_dir))
			exit("Macro aborted:\n" + new_dir + "\ncould not be created.");
	}
	return new_dir;
}

/*
 * This function applies <myRoutines()> to individual files filtered by
 * <expectedImage()>. It takes 2 arguments: <open_dir>, the full path of input
 * directory and <save_dir>, the directory where a copy of the processed images
 * will be saved. It does nothing if <open_dir> does not exist.
 */
function processImage(open_dir, save_dir) {

	// Do not display images during macro execution
	setBatchMode(true);

	// Get the array containing the names of input files and loop through it.
	// We will not perform safety checks to verify if open_dir and save_dir
	// exist since that task was already performed by getOutputDirectory()
	files = getFileList(open_dir);
	for (i=0; i<files.length; i++) {
		file_path = files[i];
		if (expectedImage(file_path)) {
			print(i+1, "Analyzing "+ file_path +"...");
			open(file_path);

			// Apply processing steps
			myRoutines();

			output_path = save_dir + "Treated_" + getTitle();
			saveAs("tiff", output_path);
			close();
		} else {
			print(i+1, "Skipping "+ file_path +"... not the right file type");
		}
	}

}

/*
 * This function returns true if the file extension of the argument <filename>
 * is present in the global variable <extensions> array. Returns false otherwise.
 */
function expectedImage(filename) {
	expected = false;
	for (i=0; i<extensions.length; i++) {
		if (endsWith(toLowerCase(filename), extensions[i])) {
			expected = true;
			break;
		}
	}
	return expected;
}

FAQ

What is the rationale behind BAR?
The motivation behind bar is quite simple: To collect snippets of code that can be incorporated into any workflow. So rather than performing fully fledged procedures, BARs tend to produce single tasks. The advantages are two-fold: 1) Scripts are easier to understand and maintain and 2) they can be used to complement any other ImageJ add-on, let it be the simplest macro or the most sophisticated plugin.
Will I find BAR useful?
Probably. But it is likely that you will need to delve a bit into the BAR philosophy.
Can I contribute to BAR?
Yes, please do! If you have some suggestions on how to improve it, do let us know.
Nothing happens when I run a BAR. What's going on?
In a case of premature termination BARs tend to exit rather silently. The best way to have insights on an unexpected error is to run it directly from the Script Editor: Open the script by holding Shift while selecting it from the BAR▷ menu, press Run and have a look at the editors' s console, where all sort of useful messages will be printed to. Do let us know if you have found a bug.
How do I uninstall BAR?
If you are using Fiji: run the Updater. Choose Advance Mode then Manage update sites. Deactivate the BAR checkbox in the alphabetically-sorted list of update sites. Press OK, then Apply changes. All BAR files will be deleted. Note that you can install and uninstall BAR as you see fit. See How to follow a 3rd party update site for more details.
If you have a installed BAR manually and cannot remember where files were placed have a look at this installation list.

License

These scripts are free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.