or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

data-conversion.mddisplay-visualization.mdenvironment-diagnostics.mdgateway-initialization.mdimage-processing.mdindex.mdscript-execution.md

script-execution.mddocs/

0

# Script Execution

1

2

Execute ImageJ macros, plugins, and scripts in various languages with argument passing and result retrieval capabilities. This enables access to the vast ecosystem of ImageJ plugins and custom processing workflows.

3

4

## Capabilities

5

6

### ImageJ Macro Execution

7

8

Execute ImageJ macro language scripts with parameter passing and output retrieval.

9

10

```python { .api }

11

def run_macro(macro: str, args=None):

12

"""

13

Execute an ImageJ macro script.

14

15

Args:

16

macro: Macro code as string with optional parameter declarations

17

args: Dictionary of macro arguments in key-value pairs

18

19

Returns:

20

ScriptModule with macro execution results and outputs

21

22

Raises:

23

ImportError: If legacy ImageJ support is not available

24

"""

25

```

26

27

**Usage Examples:**

28

29

```python

30

# Simple macro without parameters

31

simple_macro = """

32

newImage("Test", "8-bit black", 256, 256, 1);

33

run("Add Noise");

34

"""

35

result = ij.py.run_macro(simple_macro)

36

37

# Parameterized macro with inputs and outputs

38

parameterized_macro = """

39

#@ String name

40

#@ int age

41

#@ OUTPUT String greeting

42

greeting = "Hello " + name + ", you are " + age + " years old!";

43

"""

44

45

args = {

46

"name": "Alice",

47

"age": 30

48

}

49

result = ij.py.run_macro(parameterized_macro, args)

50

greeting = result.getOutput("greeting")

51

print(greeting) # "Hello Alice, you are 30 years old!"

52

53

# Macro working with active image

54

image_macro = """

55

if (nImages == 0) {

56

newImage("Demo", "8-bit black", 512, 512, 1);

57

}

58

run("Gaussian Blur...", "sigma=2");

59

getStatistics(area, mean, min, max);

60

print("Image stats - Mean: " + mean + ", Min: " + min + ", Max: " + max);

61

"""

62

ij.py.run_macro(image_macro)

63

```

64

65

### ImageJ Plugin Execution

66

67

Execute ImageJ 1.x plugins with argument string formatting and image context.

68

69

```python { .api }

70

def run_plugin(

71

plugin: str,

72

args=None,

73

ij1_style: bool = True,

74

imp=None

75

):

76

"""

77

Execute an ImageJ 1.x plugin.

78

79

Args:

80

plugin: Plugin command name as string

81

args: Dictionary of plugin arguments

82

ij1_style: Use ImageJ 1.x boolean style (True) or ImageJ2 style (False)

83

imp: Optional ImagePlus to pass to plugin execution

84

85

Returns:

86

Plugin execution results

87

"""

88

```

89

90

**Usage Examples:**

91

92

```python

93

# Run plugin without arguments

94

ij.py.run_plugin("Duplicate...")

95

96

# Run plugin with arguments

97

blur_args = {

98

"radius": 5.0,

99

"stack": True

100

}

101

ij.py.run_plugin("Gaussian Blur...", blur_args)

102

103

# Run plugin with explicit boolean style

104

threshold_args = {

105

"method": "Otsu",

106

"background": "Dark",

107

"calculate": True

108

}

109

ij.py.run_plugin("Auto Threshold", threshold_args, ij1_style=False)

110

111

# Run plugin on specific image

112

imp = ij.py.active_imageplus()

113

roi_args = {

114

"x": 100,

115

"y": 100,

116

"width": 200,

117

"height": 200

118

}

119

ij.py.run_plugin("Specify...", roi_args, imp=imp)

120

```

121

122

### Multi-Language Script Execution

123

124

Execute scripts in ImageJ2's supported scripting languages including JavaScript, Python, Groovy, and others.

125

126

```python { .api }

127

def run_script(language: str, script: str, args=None):

128

"""

129

Execute script in specified language through ImageJ2's script engine.

130

131

Args:

132

language: Language name or file extension (e.g., "javascript", "js", "python", "groovy")

133

script: Script source code as string

134

args: Dictionary of script arguments in key-value pairs

135

136

Returns:

137

ScriptModule containing script outputs and results

138

"""

139

```

140

141

**Usage Examples:**

142

143

```python

144

# JavaScript script

145

js_script = """

146

#@ ImageJ ij

147

#@ OUTPUT String result

148

importClass(Packages.ij.IJ);

149

IJ.newImage("JS Test", "8-bit black", 100, 100, 1);

150

result = "Created image from JavaScript";

151

"""

152

result = ij.py.run_script("javascript", js_script)

153

print(result.getOutput("result"))

154

155

# Groovy script with parameters

156

groovy_script = """

157

#@ int width

158

#@ int height

159

#@ String title

160

#@ OUTPUT String info

161

#@ ImageJ ij

162

163

import ij.IJ

164

IJ.newImage(title, "32-bit black", width, height, 1)

165

info = "Created ${width}x${height} image titled '${title}'"

166

"""

167

168

script_args = {

169

"width": 300,

170

"height": 200,

171

"title": "Groovy Generated"

172

}

173

result = ij.py.run_script("groovy", groovy_script, script_args)

174

print(result.getOutput("info"))

175

176

# Python script (Jython) within ImageJ2

177

python_script = """

178

#@ Dataset dataset

179

#@ OUTPUT String analysis

180

from net.imagej.ops import OpService

181

from scijava import SciJava

182

183

# Analyze the input dataset

184

dims = dataset.numDimensions()

185

pixels = dataset.size()

186

analysis = "Dataset has %d dimensions and %d pixels" % (dims, pixels)

187

"""

188

189

# Assuming we have a dataset

190

dataset = ij.py.to_dataset(np.random.rand(100, 100))

191

result = ij.py.run_script("python", python_script, {"dataset": dataset})

192

```

193

194

### Argument Handling

195

196

Utilities for formatting arguments for ImageJ plugins and scripts.

197

198

```python { .api }

199

def argstring(args, ij1_style=True):

200

"""

201

Convert argument dictionary to ImageJ argument string format.

202

203

Args:

204

args: Dictionary of arguments or pre-formatted string

205

ij1_style: Use ImageJ 1.x implicit boolean style (True) or explicit style (False)

206

207

Returns:

208

Formatted argument string for ImageJ commands

209

"""

210

211

def jargs(*args):

212

"""

213

Convert Python arguments to Java Object array for ImageJ2 operations.

214

215

Args:

216

*args: Variable number of Python arguments

217

218

Returns:

219

Java Object[] array suitable for ImageJ2 method calls

220

"""

221

```

222

223

**Usage Examples:**

224

225

```python

226

# Format arguments for ImageJ 1.x style

227

args_dict = {

228

"radius": 3.5,

229

"create": True,

230

"stack": False,

231

"title": "Processed Image"

232

}

233

234

# ImageJ 1.x style (implicit booleans)

235

ij1_string = ij.py.argstring(args_dict, ij1_style=True)

236

print(ij1_string) # "radius=3.5 create title=[Processed Image]"

237

238

# ImageJ2 style (explicit booleans)

239

ij2_string = ij.py.argstring(args_dict, ij1_style=False)

240

print(ij2_string) # "radius=3.5 create=true stack=false title=[Processed Image]"

241

242

# Convert Python args to Java Object array

243

java_args = ij.py.jargs("param1", 42, True, np.array([1, 2, 3]))

244

# Use with ImageJ2 operations that expect Object[] arguments

245

result = ij.command().run("some.command.Class", java_args).get()

246

```

247

248

### Advanced Script Integration

249

250

Work with ImageJ2's script execution framework for complex workflows.

251

252

**Script Parameter Types:**

253

254

ImageJ2 scripts support various parameter annotations:

255

- `#@ String parameter_name` - String input

256

- `#@ int parameter_name` - Integer input

257

- `#@ float parameter_name` - Float input

258

- `#@ boolean parameter_name` - Boolean input

259

- `#@ Dataset parameter_name` - Image dataset input

260

- `#@ ImagePlus parameter_name` - ImageJ ImagePlus input

261

- `#@ OUTPUT String result_name` - String output

262

- `#@ ImageJ ij` - Inject ImageJ2 gateway

263

264

**Complex Workflow Example:**

265

266

```python

267

# Multi-step processing workflow

268

workflow_script = """

269

#@ Dataset input_image

270

#@ float gaussian_sigma (min=0.1, max=10.0)

271

#@ int threshold_method (choices={"Otsu", "Li", "Moments"})

272

#@ OUTPUT Dataset processed_image

273

#@ OUTPUT String processing_log

274

#@ ImageJ ij

275

276

// Apply Gaussian blur

277

blurred = ij.op().filter().gauss(input_image, gaussian_sigma)

278

279

// Apply threshold

280

if (threshold_method == 0) {

281

processed_image = ij.op().threshold().otsu(blurred)

282

method_name = "Otsu"

283

} else if (threshold_method == 1) {

284

processed_image = ij.op().threshold().li(blurred)

285

method_name = "Li"

286

} else {

287

processed_image = ij.op().threshold().moments(blurred)

288

method_name = "Moments"

289

}

290

291

processing_log = "Applied Gaussian blur (sigma=" + gaussian_sigma + ") and " + method_name + " threshold"

292

"""

293

294

# Execute workflow

295

input_data = ij.py.to_dataset(np.random.rand(256, 256))

296

workflow_args = {

297

"input_image": input_data,

298

"gaussian_sigma": 2.0,

299

"threshold_method": 0 # Otsu

300

}

301

302

result = ij.py.run_script("javascript", workflow_script, workflow_args)

303

processed = result.getOutput("processed_image")

304

log_message = result.getOutput("processing_log")

305

306

print(log_message)

307

processed_array = ij.py.from_java(processed)

308

```

309

310

## Error Handling

311

312

Common script execution issues:

313

314

- **Language Availability**: Verify scripting language is installed with ImageJ2

315

- **Legacy Dependency**: Macros and some plugins require `add_legacy=True`

316

- **Parameter Mismatch**: Script parameters must match provided arguments

317

- **Import Errors**: Java imports in scripts must use full class names

318

- **Context Requirements**: Some scripts need active images or specific ImageJ2 services