CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pyimagej

Python wrapper for ImageJ2 that provides seamless integration between ImageJ and Python scientific computing ecosystems

Pending
Overview
Eval results
Files

script-execution.mddocs/

Script Execution

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.

Capabilities

ImageJ Macro Execution

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

def run_macro(macro: str, args=None):
    """
    Execute an ImageJ macro script.
    
    Args:
        macro: Macro code as string with optional parameter declarations
        args: Dictionary of macro arguments in key-value pairs
        
    Returns:
        ScriptModule with macro execution results and outputs
        
    Raises:
        ImportError: If legacy ImageJ support is not available
    """

Usage Examples:

# Simple macro without parameters
simple_macro = """
newImage("Test", "8-bit black", 256, 256, 1);
run("Add Noise");
"""
result = ij.py.run_macro(simple_macro)

# Parameterized macro with inputs and outputs
parameterized_macro = """
#@ String name
#@ int age
#@ OUTPUT String greeting
greeting = "Hello " + name + ", you are " + age + " years old!";
"""

args = {
    "name": "Alice", 
    "age": 30
}
result = ij.py.run_macro(parameterized_macro, args)
greeting = result.getOutput("greeting")
print(greeting)  # "Hello Alice, you are 30 years old!"

# Macro working with active image
image_macro = """
if (nImages == 0) {
    newImage("Demo", "8-bit black", 512, 512, 1);
}
run("Gaussian Blur...", "sigma=2");
getStatistics(area, mean, min, max);
print("Image stats - Mean: " + mean + ", Min: " + min + ", Max: " + max);
"""
ij.py.run_macro(image_macro)

ImageJ Plugin Execution

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

def run_plugin(
    plugin: str, 
    args=None, 
    ij1_style: bool = True, 
    imp=None
):
    """
    Execute an ImageJ 1.x plugin.
    
    Args:
        plugin: Plugin command name as string
        args: Dictionary of plugin arguments  
        ij1_style: Use ImageJ 1.x boolean style (True) or ImageJ2 style (False)
        imp: Optional ImagePlus to pass to plugin execution
        
    Returns:
        Plugin execution results
    """

Usage Examples:

# Run plugin without arguments
ij.py.run_plugin("Duplicate...")

# Run plugin with arguments
blur_args = {
    "radius": 5.0,
    "stack": True
}
ij.py.run_plugin("Gaussian Blur...", blur_args)

# Run plugin with explicit boolean style
threshold_args = {
    "method": "Otsu",
    "background": "Dark",
    "calculate": True
}
ij.py.run_plugin("Auto Threshold", threshold_args, ij1_style=False)

# Run plugin on specific image
imp = ij.py.active_imageplus()
roi_args = {
    "x": 100,
    "y": 100, 
    "width": 200,
    "height": 200
}
ij.py.run_plugin("Specify...", roi_args, imp=imp)

Multi-Language Script Execution

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

def run_script(language: str, script: str, args=None):
    """
    Execute script in specified language through ImageJ2's script engine.
    
    Args:
        language: Language name or file extension (e.g., "javascript", "js", "python", "groovy")
        script: Script source code as string
        args: Dictionary of script arguments in key-value pairs
        
    Returns:
        ScriptModule containing script outputs and results
    """

Usage Examples:

# JavaScript script
js_script = """
#@ ImageJ ij
#@ OUTPUT String result
importClass(Packages.ij.IJ);
IJ.newImage("JS Test", "8-bit black", 100, 100, 1);
result = "Created image from JavaScript";
"""
result = ij.py.run_script("javascript", js_script)
print(result.getOutput("result"))

# Groovy script with parameters
groovy_script = """
#@ int width
#@ int height  
#@ String title
#@ OUTPUT String info
#@ ImageJ ij

import ij.IJ
IJ.newImage(title, "32-bit black", width, height, 1)
info = "Created ${width}x${height} image titled '${title}'"
"""

script_args = {
    "width": 300,
    "height": 200,
    "title": "Groovy Generated"
}
result = ij.py.run_script("groovy", groovy_script, script_args)
print(result.getOutput("info"))

# Python script (Jython) within ImageJ2
python_script = """
#@ Dataset dataset
#@ OUTPUT String analysis
from net.imagej.ops import OpService
from scijava import SciJava

# Analyze the input dataset
dims = dataset.numDimensions()
pixels = dataset.size()
analysis = "Dataset has %d dimensions and %d pixels" % (dims, pixels)
"""

# Assuming we have a dataset
dataset = ij.py.to_dataset(np.random.rand(100, 100))
result = ij.py.run_script("python", python_script, {"dataset": dataset})

Argument Handling

Utilities for formatting arguments for ImageJ plugins and scripts.

def argstring(args, ij1_style=True):
    """
    Convert argument dictionary to ImageJ argument string format.
    
    Args:
        args: Dictionary of arguments or pre-formatted string
        ij1_style: Use ImageJ 1.x implicit boolean style (True) or explicit style (False)
        
    Returns:
        Formatted argument string for ImageJ commands
    """

def jargs(*args):
    """
    Convert Python arguments to Java Object array for ImageJ2 operations.
    
    Args:
        *args: Variable number of Python arguments
        
    Returns:
        Java Object[] array suitable for ImageJ2 method calls
    """

Usage Examples:

# Format arguments for ImageJ 1.x style
args_dict = {
    "radius": 3.5,
    "create": True,
    "stack": False,
    "title": "Processed Image"
}

# ImageJ 1.x style (implicit booleans)
ij1_string = ij.py.argstring(args_dict, ij1_style=True)
print(ij1_string)  # "radius=3.5 create title=[Processed Image]"

# ImageJ2 style (explicit booleans)  
ij2_string = ij.py.argstring(args_dict, ij1_style=False)
print(ij2_string)  # "radius=3.5 create=true stack=false title=[Processed Image]"

# Convert Python args to Java Object array
java_args = ij.py.jargs("param1", 42, True, np.array([1, 2, 3]))
# Use with ImageJ2 operations that expect Object[] arguments
result = ij.command().run("some.command.Class", java_args).get()

Advanced Script Integration

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

Script Parameter Types:

ImageJ2 scripts support various parameter annotations:

  • #@ String parameter_name - String input
  • #@ int parameter_name - Integer input
  • #@ float parameter_name - Float input
  • #@ boolean parameter_name - Boolean input
  • #@ Dataset parameter_name - Image dataset input
  • #@ ImagePlus parameter_name - ImageJ ImagePlus input
  • #@ OUTPUT String result_name - String output
  • #@ ImageJ ij - Inject ImageJ2 gateway

Complex Workflow Example:

# Multi-step processing workflow
workflow_script = """
#@ Dataset input_image
#@ float gaussian_sigma (min=0.1, max=10.0)
#@ int threshold_method (choices={"Otsu", "Li", "Moments"})
#@ OUTPUT Dataset processed_image
#@ OUTPUT String processing_log
#@ ImageJ ij

// Apply Gaussian blur
blurred = ij.op().filter().gauss(input_image, gaussian_sigma)

// Apply threshold
if (threshold_method == 0) {
    processed_image = ij.op().threshold().otsu(blurred)
    method_name = "Otsu"
} else if (threshold_method == 1) {
    processed_image = ij.op().threshold().li(blurred)  
    method_name = "Li"
} else {
    processed_image = ij.op().threshold().moments(blurred)
    method_name = "Moments"
}

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

# Execute workflow
input_data = ij.py.to_dataset(np.random.rand(256, 256))
workflow_args = {
    "input_image": input_data,
    "gaussian_sigma": 2.0,
    "threshold_method": 0  # Otsu
}

result = ij.py.run_script("javascript", workflow_script, workflow_args)
processed = result.getOutput("processed_image")
log_message = result.getOutput("processing_log")

print(log_message)
processed_array = ij.py.from_java(processed)

Error Handling

Common script execution issues:

  • Language Availability: Verify scripting language is installed with ImageJ2
  • Legacy Dependency: Macros and some plugins require add_legacy=True
  • Parameter Mismatch: Script parameters must match provided arguments
  • Import Errors: Java imports in scripts must use full class names
  • Context Requirements: Some scripts need active images or specific ImageJ2 services

Install with Tessl CLI

npx tessl i tessl/pypi-pyimagej

docs

data-conversion.md

display-visualization.md

environment-diagnostics.md

gateway-initialization.md

image-processing.md

index.md

script-execution.md

tile.json