API

PyImageJ provides a set of wrapper functions for integration between ImageJ+ImageJ2 and Python. A major advantage of this approach is the ability to combine ImageJ+ImageJ2 with other tools available from the Python software ecosystem, e.g. NumPy, SciPy, scikit-image, CellProfiler, OpenCV, and ITK.

The first step when using PyImageJ is to create an ImageJ2 gateway. This gateway can point to any official release of ImageJ2 or to a local installation. Using the gateway, you have full access to the ImageJ2 API, plus utility functions for translating between Python (NumPy, xarray, pandas, etc.) and Java (ImageJ, ImageJ2, ImgLib2, etc.) structures.

Here is an example of opening an image using ImageJ2 and displaying it:

# Create an ImageJ2 gateway with the newest available version of ImageJ2.
import imagej
ij = imagej.init()

# Load an image.
image_url = 'https://imagej.net/images/clown.png'
jimage = ij.io().open(image_url)

# Convert the image from ImageJ2 to xarray, a package that adds
# labeled datasets to numpy (http://xarray.pydata.org/en/stable/).
image = ij.py.from_java(jimage)

# Display the image (backed by matplotlib).
ij.py.show(image, cmap='gray')

Initialization

imagej.init(ij_dir_or_version_or_endpoint=None, mode: Mode | str = Mode.HEADLESS, add_legacy=True, headless=None)[source]

Initialize an ImageJ2 environment.

The environment can wrap a local ImageJ2 installation, or consist of a specific version of ImageJ2 downloaded on demand, or even an explicit list of Maven artifacts. The environment can be initialized in headless mode or GUI mode, and with or without support for the original ImageJ. Note: some original ImageJ operations do not function in headless mode.

Parameters:
  • ij_dir_or_version_or_endpoint –

    Path to a local ImageJ2 installation (e.g. /Applications/Fiji.app),
    OR version of net.imagej:imagej artifact to launch (e.g. 2.3.0),
    OR endpoint of another artifact built on ImageJ2 (e.g. sc.fiji:fiji),
    OR list of Maven artifacts to include (e.g.
    [
    β€œnet.imagej:imagej:2.3.0”,
    ”net.imagej:imagej-legacy”,
    ”net.preibisch:BigStitcher”,
    ]
    ).
    The default is the latest version of net.imagej:imagej.

  • mode –

    How the environment will behave. Options include:

    • Mode.HEADLESS -

      Start the JVM in headless mode, i.e. with no GUI. This is the default mode. Useful if you want to use ImageJ as a library, or run it on a remote server. NB: In this mode with add_legacy=True, not all functions of the original ImageJ are available; in particular, some plugins do not work properly because they assume ImageJ has a GUI.

    • Mode.GUI -

      Start ImageJ2 as a GUI application, displaying the GUI automatically and then blocking. NB: In this mode with add_legacy=True, the JVM and Python will both terminate when ImageJ closes!

    • Mode.INTERACTIVE -

      Start ImageJ2 with GUI support, but not displaying the GUI automatically, Does not block. To display the GUI in this mode, call ij.ui().showUI(). NB: This mode is not available on macOS, due to its application threading model. NB: In this mode with add_legacy=True, the JVM and Python will both terminate when ImageJ closes!

  • add_legacy – Whether or not to include support for original ImageJ functionality. If True, original ImageJ functions (ij.* packages) will be available. If False, the environment will be β€œpure ImageJ2”, without ij.* support. NB: With legacy support enabled in GUI or interactive mode, the JVM and Python will both terminate when ImageJ closes! For further details, see: https://imagej.net/libs/imagej-legacy

  • headless – Deprecated. Please use the mode parameter instead.

Returns:

An instance of the net.imagej.ImageJ gateway

Example:

ij = imagej.init("sc.fiji:fiji", mode=imagej.Mode.GUI)
class imagej.Mode(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

An environment mode for the ImageJ2 gateway. See the imagej.init function for more details.

GUI = 'gui'
HEADLESS = 'headless'
INTERACTIVE = 'interactive'

Convenience methods

class imagej.ImageJPython(ij)[source]

ImageJ/Python convenience methods.

This class should not be initialized manually. Upon initialization the ImageJPython class is attached to the newly initialized ImageJ2 instance in the GatewayAddons class via JPype class customization mechanism:

https://jpype.readthedocs.io/en/latest/userguide.html#class-customizers

active_dataset() jc.Dataset[source]

Get the active Dataset image.

Get the active image as a Dataset from the Dataset service.

Returns:

The Dataset corresponding to the active image.

active_image_plus(sync=True) jc.ImagePlus[source]

ij.py.active_image_plus() is deprecated. Use ij.py.active_imageplus() instead.

active_imageplus(sync: bool = True) jc.ImagePlus[source]

Get the active ImagePlus image.

Get the active image as an ImagePlus, optionally synchronizing from ImageJ to ImageJ2.

Parameters:

sync – Synchronize the current ImagePlus slice if True.

Returns:

The ImagePlus corresponding to the active image.

active_xarray(sync=True) DataArray[source]

Get the active image as an xarray.

Get the active image as an xarray.DataArray, synchronizing from ImageJ to ImageJ2.

Parameters:

sync – Synchronize the current ImagePlus slice if True.

Returns:

xarray.DataArray array containing the image data.

argstring(args, ij1_style=True)[source]

Assemble an ImageJ (1.x) argument string from arguments in a dict.

Parameters:
  • args – A dict of arguments in key/value pairs

  • ij1_style – True to use implicit booleans in original ImageJ style, or False for explicit booleans in ImageJ2 style

Returns:

A string version of the arguments

dims(image)[source]

ij.py.dims(image) is deprecated. Use image.shape instead.

dtype(image_or_type)[source]

Get the dtype of the input image as a numpy.dtype object.

Note: for Java-based images, this is different than the image’s dtype property, because ImgLib2-based images report their dtype as a subclass of net.imglib2.type.Type, and ImagePlus images do not yet implement the dtype function (see https://github.com/imagej/pyimagej/issues/194).

Parameters:

image_or_type –

A NumPy array.
OR A NumPy array dtype.
OR An ImgLib2 image (net.imglib2.Interval).
OR An ImageJ2 Dataset (net.imagej.Dataset).
OR An ImageJ ImagePlus (ij.ImagePlus).

Returns:

Input image dtype.

from_java(data)[source]

Convert supported Java data into Python equivalents.

Converts Java objects (e.g. net.imagej.Dataset) into the Python equivalents.

Parameters:

data – Java object to be converted into its respective Python counterpart.

Returns:

A Python object converted from Java.

initialize_numpy_image(image) ndarray[source]

Initialize a NumPy array with zeros and shape of the input image.

Initialize a new NumPy array with the same dtype and shape as the input image with zeros.

Parameters:

image – A RandomAccessibleInterval or NumPy image

Returns:

A NumPy array with the same dtype and shape as the input image, filled with zeros.

jargs(*args)[source]

Convert Python arguments into a Java Object[]

Converts Python arguments into a Java Object[] (i.e.: array of Java objects). This is particularly useful in combination with ImageJ2’s various run functions, including ij.command().run(…), ij.module().run(…), ij.script().run(…), and ij.op().run(…).

Parameters:

args – The Python arguments to wrap into an Object[].

Returns:

A Java Object[]

new_numpy_image(image)[source]

ij.py.new_numpy_image() is deprecated. Use ij.py.initialize_numpy_image() instead.

rai_to_numpy(rai: jc.RandomAccessibleInterval, numpy_array: ndarray) ndarray[source]

Copy a RandomAccessibleInterval into a numpy array.

The input RandomAccessibleInterval is copied into the pre-initialized numpy array with either β€œfast copy” via net.imagej.util.Images.copy if available or the slower β€œcopy.rai” method. Note that the input RandomAccessibleInterval and numpy array must have reversed dimensions relative to each other (e.g. [β€œt”, β€œz”, β€œy”, β€œx”, β€œc”] and [β€œc”, β€œx”, β€œy”, β€œz”, β€œt”]).

Parameters:
  • rai – A net.imglib2.RandomAccessibleInterval.

  • numpy_array – A NumPy array with the same shape as the input RandomAccessibleInterval.

Returns:

NumPy array with the input RandomAccessibleInterval data.

run_macro(macro: str, args=None)[source]

Run an ImageJ macro.

Run an ImageJ macro by providing the macro code/script in a string and the arguments in a dictionary.

Parameters:
  • macro – The macro code/script as a string.

  • args – A dictionary of macro arguments in key: valye pairs.

Returns:

Runs the specified macro with the given arguments.

Example:

macro = """
#@ String name
#@ int age
output = name + " is " + age " years old."
"""
args = {
    "name": "Sean",
    "age": 26
}
macro_result = ij.py.run_macro(macro, args)
print(macro_result.getOutput("output"))
run_plugin(plugin: str, args=None, ij1_style: bool = True, imp: jc.ImagePlus = None)[source]

Run an ImageJ 1.x plugin.

Run an ImageJ 1.x plugin by specifying the plugin name as a string, and the plugin arguments as a dictionary. For the few plugins that use the ImageJ2 style macros (i.e. explicit booleans in the recorder), set the option variable ij1_style=False.

Parameters:
  • plugin – The string name for the plugin command.

  • args – A dictionary of plugin arguments in key: value pairs.

  • ij1_style – Boolean to set which implicit boolean style to use (ImageJ or ImageJ2).

  • imp – Optionally: the image to pass to the plugin execution.

Example:

plugin = "Mean"
args = {
    "block_radius_x": 10,
    "block_radius_y": 10
}
ij.py.run_plugin(plugin, args)
run_script(language: str, script: str, args=None)[source]

Run an ImageJ2 script.

Run a script in one of ImageJ2’s supported scripting languages. Specify the language of the script, provide the code as a string and the arguments as a dictionary.

Parameters:
  • language – The file extension for the scripting language.

  • script – A string of the script code.

  • args – A dictionary of macro arguments in key: value pairs.

Returns:

A Java map of output names and values, key: value pais.

Example:

language = "ijm"
script = """
#@ String name
#@ int age
output = name + " is " + age " years old."
"""
args = {
    "name": "Sean",
    "age": 26
}
script_result = ij.py.run_script(language, script, args)
print(script_result.getOutput("output"))
show(image, cmap=None)[source]

Display a Java or Python 2D image.

Display a Java or Python 2D image.

Parameters:
  • image – A Java or Python image that can be converted to a NumPy array.

  • cmap – The colormap for the matplotlib.pyplot image display.

Returns:

Displayed image.

sync_image(imp: jc.ImagePlus = None)[source]

Synchronize data between ImageJ and ImageJ2.

Synchronize between a Dataset or ImageDisplay linked to an ImagePlus by accepting the ImagePlus data as true.

Parameters:

imp – The ImagePlus that needs to be synchronized, or None to synchronize ImageJ’s active image.

synchronize_ij1_to_ij2(imp: jc.ImagePlus)[source]

This function is deprecated. Use sync_image instead.

to_dataset(data, dim_order=None)[source]

Convert the data into an ImageJ2 Dataset.

Converts a Python image (e.g. xarray or numpy array) or Java image (e.g. RandomAccessibleInterval or Img) into a net.imagej.Dataset Java object.

Parameters:

data – Image object to be converted to Dataset.

Returns:

A net.imagej.Dataset.

to_imageplus(data)[source]

Convert the data into an ImageJ ImagePlus.

Converts a Python image (e.g. xarray or numpy array) or Java image (e.g. RandomAccessibleInterval or Dataset) into an ij.ImagePlus Java object.

Parameters:

data – Image object to be converted to ImagePlus.

Returns:

An ij.ImagePlus.

to_img(data, dim_order=None)[source]

Convert the data into an ImgLib2 Img.

Converts a Python image (e.g. xarray or numpy array) or Java image (e.g. RandomAccessibleInterval) into a net.imglib2.img.Img Java object.

Parameters:

data – Image object to be converted to Img.

Returns:

A net.imglib2.img.Img.

to_java(data, **hints)[source]

Convert supported Python data into Java equivalents.

Converts Python objects (e.g. xarray.DataArray) into the Java equivalents. For numpy arrays, the Java image points to the Python array.

Parameters:
  • data – Python object to be converted into its respective Java counterpart.

  • hints – Optional conversion hints.

Returns:

A Java object converted from Python.

to_xarray(data, dim_order=None)[source]

Convert the data into an ImgLib2 Img.

Converts a Python image (e.g. xarray or numpy array) or Java image (e.g. RandomAccessibleInterval) into an xarray.DataArray Python object.

Parameters:

data – Image object to be converted to xarray.DataArray.

Returns:

An xarray.DataArray.

window_manager()[source]

ij.py.window_manager() is deprecated. Use ij.WindowManager instead.

RandomAccessibleInterval (RAI) operators

class imagej.RAIOperators[source]

RandomAccessibleInterval operators.

This class should not be initialized manually. Upon initialization the RAIOperators class automatically extends the Java RandomAccessibleInterval via JPype’s class customization mechanism:

https://jpype.readthedocs.io/en/latest/userguide.html#class-customizers

property T

Transpose RandomAccessibleInterval.

Returns:

Transposed RandomAccessibleInterval.

property dtype

Get the dtype of a RandomAccessibleInterval, a subclass of net.imglib2.type.Type.

Returns:

dtype of the RandomAccessibleInterval.

squeeze(axis=None)[source]

Remove axes of length one from array.

Returns:

Squeezed RandomAccessibleInterval.

property transpose

Transpose RandomAccessibleInterval.

Returns:

Transposed RandomAccessibleInterval.

ImageJ2 gateway addons

class imagej.GatewayAddons[source]

ImageJ2 gateway addons.

This class should not be initialized manually. Upon initialization the GatewayAddons class is attached to the newly initialized ImageJ2 instance via JPype’s class customization mechanism:

https://jpype.readthedocs.io/en/latest/userguide.html#class-customizers

property IJ

Get the original ImageJ IJ utility class.

Returns:

The ij.IJ class.

property ResultsTable

Get the original ImageJ ResultsTable class.

Returns:

The ij.measure.ResultsTable class.

property RoiManager

Get the original ImageJ RoiManager class.

Returns:

The ij.plugin.frame.RoiManager class.

property WindowManager

Get the original ImageJ WindowManager class.

Returns:

The ij.WindowManager class.

property legacy

Get the ImageJ2 LegacyService.

Gets the ImageJ2 gateway’s LegacyService, or None if original ImageJ support is not available in the current environment.

Returns:

The ImageJ2 LegacyService.

property py

Access the ImageJPython convenience methods.

Returns:

ImageJPython convenience methods.

ImagePlus addons

class imagej.ImagePlusAddons[source]

ImagePlus addons.

This class should not be initialized manually. Upon initialization the ImagePlusAddons class automatically extends the Java ij.ImagePlus via JPype’s class customization mechanism:

https://jpype.readthedocs.io/en/latest/userguide.html#class-customizers

property dims: Tuple[str]

Get the dimensional axis labels of the image.

ImagePlus objects are always ordered XYZCT, although this function squeezes out dimensions of length 1.

Returns:

Dimension labels of the image.

property shape

Get the shape of the image.

Returns:

Tuple of the image shape.

See:

ij.ImagePlus#getDimensions()

Interval addons

class imagej.IntervalAddons[source]
property shape

Get the shape of the interval.

Returns:

Tuple of the interval shape.

See:

net.imglib2.Interval#dimension(int)

Euclidean space addons

class imagej.EuclideanSpaceAddons[source]
property ndim

Get the number of dimensions.

Returns:

Number of dimensions.

See:

net.imglib2.EuclideanSpace#numDimensions()

Typed space addons

class imagej.TypedSpaceAddons[source]

TypedSpace addons.

This class should not be initialized manually. Upon initialization the TypedSpaceAddons class automatically extends the Java net.imagej.space.TypedSpace via JPype’s class customization mechanism:

https://jpype.readthedocs.io/en/latest/userguide.html#class-customizers

property dims: Tuple[str]

Get the axis labels of the dimensional space.

Returns:

Dimension labels of the space.

See:

net.imagej.space.TypedSpace#axis(int)

Annotated space addons

class imagej.AnnotatedSpaceAddons[source]

AnnotatedSpace addons.

This class should not be initialized manually. Upon initialization the AnnotatedSpaceAddons class automatically extends the Java net.imagej.space.AnnotatedSpace via JPype’s class customization mechanism:

https://jpype.readthedocs.io/en/latest/userguide.html#class-customizers

property dim_axes: Tuple[jc.Axis]

Get the axes of the dimensional space.

Returns:

tuple of net.imagej.axis.Axis objects describing the dimensional axes.

See:

net.imagej.space.AnnotatedSpace#axis(int)

PyImageJ submodules

imagej.dims

Utility functions for querying and manipulating dimensional axis metadata.

dims.get_axes(rai: jc.RandomAccessibleInterval) List[jc.CalibratedAxis][source]

imagej.dims.get_axes(image) is deprecated. Use image.dim_axes instead.

dims.get_axis_types(rai: jc.RandomAccessibleInterval) List[jc.AxisType][source]

imagej.dims.get_axis_types(image) is deprecated. Use this code instead:

axis_types = [axis.type() for axis in image.dim_axes]

dims.get_dims(image) List[str][source]

imagej.dims.get_dims(image) is deprecated. Use image.shape and image.dims instead.

dims.get_shape(image) List[int][source]

imagej.dims.get_shape(image) is deprecated. Use image.shape instead.

dims.prioritize_rai_axes_order(axis_types: List[jc.AxisType], ref_order: List[jc.AxisType]) List[int][source]

Prioritize the axes order to match a reference order.

The input List of β€˜AxisType’ from the image to be permuted will be prioritized to match (where dimensions exist) to a reference order (e.g. _python_rai_ref_order).

Parameters:
  • axis_types – List of β€˜net.imagej.axis.AxisType’ from image.

  • ref_order – List of β€˜net.imagej.axis.AxisType’ from reference order.

Returns:

List of int for permuting a image (e.g. [0, 4, 3, 1, 2])

dims.reorganize(rai: jc.RandomAccessibleInterval, permute_order: List[int]) jc.ImgPlus[source]

Reorganize the dimension order of a RandomAccessibleInterval.

Permute the dimension order of an input RandomAccessibleInterval using a List of ints (i.e. permute_order) to determine the shape of the output ImgPlus.

Parameters:
  • rai – A RandomAccessibleInterval,

  • permute_order – List of int in which to permute the RandomAccessibleInterval.

Returns:

A permuted ImgPlus.

imagej.stack

Utility functions for manipulating image stacks.

stack.rai_slice(rai, imin: Tuple, imax: Tuple, istep: Tuple)[source]

Slice ImgLib2 images.

Slice ImgLib2 images using Python’s slice notation to define the desired slice range. Returned interval includes both imin and imax

Parameters:
  • rai – An ImgLib2 RandomAccessibleInterval

  • imin – Tuple of minimum interval range values.

  • imax – Tuple of maximum interval range values.

Returns:

Sliced ImgLib2 RandomAccessibleInterval.

imagej.doctor

The PyImageJ doctor provides standalone tools for diagnosing your environment configuration, and offers advice for correcting problems.

To run the diagnostics:

import imagej.doctor imagej.doctor.checkup()

To enable debug-level logging:

import imagej.doctor imagej.doctor.debug_to_stderr() import imagej ij = imagej.init()

doctor.checkup(output=<built-in function print>)[source]

Check your environment for health problems that could prevent PyImageJ from functioning.

doctor.debug_to_stderr(logger=None, debug_maven=False)[source]

Enable debug logging to the standard error stream.

Parameters:
  • logger – The logger for which debug logging should go to stderr, or None to enable it for all known loggers across PyImageJ’s dependency stack (e.g.: jgo, imglyb, scyjava).

  • debug_maven – Enable Maven debug logging. It’s very verbose, so this flag is False by default, but if jgo is having problems resolving the environment, such as failure to download needed JAR files, try setting this flag to True for more details on where things go wrong.