Макроязык (Macro Language) программы ImageJ - BioinforMatix.ru - портал по биоинформатике, имейджингу и биософту
Макроязык (Macro Language) программы ImageJ |
Автор Команда bioinformatix.ru | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
22.04.2009 г. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Макроязык (Macro Language) - это специализированный функциональный программный механизм, который помогает автоматизировать ряд команд программы ImageJ. Cамый простой способ создать макрос – это записать серию
команд с помощью команды recorder (Plugins/Macros/Record...). Макрос сохраняется в виде текстового файла, и при
необходимости запускается с помощью команды run (Plugins/Macros/Run – и выбираете свой, ранее сохраненный макрос). Если ваш макрос открыть
Уже существует более чем 300
примеров макросов на официальном веб-сайте программы ImageJ (на английском
языке). На нашем сайте тоже постоянно обновляется раздел о макросах и плагинах,
где вы можете найти примеры других макросов, но только уже на русском языке. Чтобы
перейти Чтобы попробовать какой-нибудь из
них, необходимо:открыть его |
Команда |
Описание |
Crgb |
Установить цвет |
Bxy |
установить местонахождение
базы (по умолчанию (0,0)) |
Rxywh |
Нарисовать прямоугольник |
Fxywh |
Нарисовать и заполнить
прямоугольник |
Oxywh |
Нарисовать овал |
oxywh |
Нарисовать и заполнить овал |
Lxyxy |
Нарисовать линию |
Dxy |
Нарисовать точку |
Pxyxy...xy0 |
Нарисовать множественную
линию |
Txyssc |
Нарисовать символ |
Где X (X-координата), Y
(Y-координата), W (ширина), H (высота), R (красный), G (зеленый) и B (синий).
ПеременныеВ программа ImageJ макроязык является "typeless", т.е. бестиповым.
Переменные не должны быть описаны заранее и не имеют явных типов данных.
Они автоматически инициализируется при запуске макроса. Переменная может содержать числа, строки или массив.
По сути дела, одна и та же переменная может быть хоть строкой, хоть массивом,
хоть числомв разное время выполнения макроса. Числа хранятсяв 64-битном формате с плавающей точкой формате.
В этом примере рассмотрим числа, строки и массивы, которые относятся к одной и той же переменной.
v = 1.23;
print(v);
v = "a string";
print(v);
v = newArray(10, 20, 50);
for (i=0; iv.length; i++) print(v[i]);
Пример:
var x=1;
macro "Macro1..." {
x = getNumber("x:", x);
}
macro "Macro2" {
print("x="+x);
}
Следует
заметить, что макроязык чувствителен к регистру. Например, "Name" и
"name" – это две разные переменные.
Операторы
Макроязык программы ImageJ
поддерживает почти все стандартные операторы Java, но с меньшим числом
предшествующих уровней (Prec).
Оператор |
Prec. |
Описание
оператора |
++ |
1 |
До или
после увеличения |
-- |
1 |
До или
после уменьшения |
- |
1 |
Минус |
! |
1 |
Булевое
дополнение |
~ |
1 |
Побитовое
дополнение |
* |
2 |
Умножение |
/ |
2 |
Деление |
% |
2 |
Остаток |
& |
2 |
Побитовое
И |
| |
2 |
Побитовое
ИЛИ |
^ |
2 |
Побитовое
XOR (когда первый операнд не равен второму) |
,
|
2 |
Перемещение
влево, перемещение вправо |
+ |
3 |
Сложение,
если строки - совмещение |
- |
3 |
Вычитание |
, = |
4 |
Меньше,
меньше или равно |
, = |
4 |
Больше,
больше или равно |
==, != |
4 |
Равно,
не равно |
&&
|
5 |
Булевая
И |
|| |
5 |
Булевая
ИЛИ |
= |
6 |
Присваивание |
+=, -=,
*=, /= |
6 |
Присваивание
с операцией |
if/else Statements
The if statement conditionally executes other statements depending on the value of a boolean expression. It has the form:if (condition) {The condition is evaluated. If it is true, the code block is executed, otherwise it is skipped. If at least one image is open, this example prints the title of the active image, otherwise it does nothing.
statement(s)
}
if (nImages0) {An optional else statement can be included with the if statement:
title = getTitle();
print("title: " + title);
}
if (condition) {In this case, the code block after the else is executed if the condition is false. If no images are open, this example prints "No images are open", otherwise it prints the title of the active image.
statement(s)
} else {
statement(s)
}
if (nImages==0)Note that the "==" operator is used for comparisons and the "=" operator is used for assignments. The braces are omitted in this example since they are not required for code blocks containing a single statement.
print("No images are open");
else
print("The image title is " + getTitle);
The macro language does not have a switch statement but it can be simulated using if/else statements. Here is an example:
type = selectionType();
if (type==-1)
print("no selection");
else if ((type=0 && type=4) || type==9)
print("area selection");
else if (type==10)
print("point selection");
else
print("line selection");
Looping Statements (for, while and do...while)
Looping statements are used to repeatadly run a block of code. The ImageJ macro language has three looping statements:- for - runs a block of code a specified number of times
- while - repeatedly runs a block of code while a condition is true
- do...while - runs a block of code once then repeats while a condition is true
for (initialization; condition; increment) {The initialization is a statement that runs once at the beginning of the loop. The condition is evaluated at top of each iteration of the loop and the loop terminates when it evaluates to false. Finally, increment is a statement that runs after each iteration through the loop.
statement(s)
}
In this example, a for loop is used to print the values 0, 10, 20...90.
for (i=0; i10; i++) {The braces can be omitted if there is only one statement in the loop.
j = 10*i;
print(j);
}
for (i=0; i=90; i+=10)The while statement has the form:
print(i);
while (condition) {First, the condition is evaluated. If it is true, the code block is executed and the while statement continues testing the condition and executing the code block until the condition becomes false.
statement(s)
}
In this example, a while loop is used to print the values 0, 10, 20...90.
i = 0;The do...while statement has the form:
while (i=90) {
print(i);
i = i + 10;
}
do {Instead of evaluating the condition at the top of the loop, do-while evaluates it at the bottom. Thus the code block is always executed at least once.
statement(s)
} while (condition);
In this example, a do...while loop is used to print the values 0, 10, 20...90.
i = 0;
do {
print(i);
i = i + 10;
} while (i=90);
User-defined Functions
A function is a callable block of code that can be passed values and can return a value. The ImageJ macro language has two kinds of functions: built-in and user-defined. A user-defined function has the form:function myFunction(arg1, arg2. arg3) {Functions can use the return statement to return a value.
statement(s)
}
function sum(a, b) {The number of arguments given when calling a function must correspond to the number of arguments in the function definition. The sum() function has two arguments so it must called with two arguments.
return a + b;
}
print(sum(1, 2));A function definition with no arguments must include the parentheses
function hello() {and, unlike built-in functions, must be called with parentheses.
print("Hello");
}
hello();Basic data types (strings and numbers) are passed to a function by value; arrays are passed by reference.
Working with Strings
Use the indexOf() function to test to see if one string is contained in another. Use the startsWith() and endsWith() functions to see if a string starts with or ends with another string. Use the substring() function to extract a portion of string. Use the lengthOf() function to determine the length of a string.Use the "==", "!=", "" and "" operators to compare strings. Comparisons are case-insensitive. For example, the following code display true.
ans = "Yes";
if (ans=="yes")
print ("true");
else
print("false");
Extending the Macro Language
There are two ways to add functions implemented as Java code to the macro language. One is to use the call function to call static methods defined in a plugin. The other is to write a plugin that implements the MacroExtension interface. The ImpProps plugin demonstrates how to use the call function to get and set image properties and the Image5D_Extensions plugin demonstrates how to add MacroExtension (Ext) functions that work with the Image5D plugins.Running Macros from the Command Line
You can run a macro from the command line and pass a string argument using the -macro or -batch command line options. As an example, this macro opens an image in the 'images' directory in the users home directory:name = getArgument;Assume it is named 'OpenImage.txt' and it is located in the macros folder. Run the command
if (name=="") exit ("No argument!");
path = getDirectory("home")+"images"+File.separator+name;
setBatchMode(true);
open(path);
print(getTitle+": "+getWidth+"x"+getHeight);
java -jar ij.jar -macro OpenImage blobs.tifand ImageJ will launch and "blobs.tif: 256x254" is displayed in the Log window. Note that ImageJ assumed the '.txt' extension and the ImageJ/macros directory. Or run
java -jar ij.jar -batch OpenImage blobs.tifand ImageJ does not launch and "blobs.tif: 256x254" is displayed in the terminal window.
A description of all the ImageJ command line options is available at rsb.info.nih.gov/ij/docs/install/linux.html#options.
Debugging Macros
You can debug a macro using the commands in the Debug menu, which was added to the macro editor in ImageJ 1.42. You start a debugging session by pressing ctrl-d (Debug Macro). You can then single step through the macro code by repeatedly pressing ctrl-e (Step).There are seven commands in the Debug menu:
- Debug Macro - Starts running the macro in debug mode and opens the "Debug" window, which initially displays the memory usage, number of open images, and the active image's title. The macro stops running at the first executable line of code, which is highlighted. Use one of the following commands to continue execution.
- Step - Executes the highlighted statement and advances to the next. The variable names and values in the "Debug" window are updated.
- Trace - Runs the macro, displaying variable names and values in the "Debug" window as they are encountered.
- Fast Trace - Same as above, but faster.
- Run - Runs the macro to completion at normal speed.
- Run to Insertion Point - Runs the macro to a statement that was previously defined by clicking the mouse on an executable line of code.
- Abort - Exits the macro.
« Пред. |
---|