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

data-conversion.mddocs/

Data Conversion

Comprehensive conversion system for translating data between Python (NumPy, xarray, pandas) and Java (ImageJ2, ImgLib2, ImagePlus) formats with full metadata preservation and type safety.

Capabilities

Core Conversion Methods

Primary conversion functions accessible via the ImageJ2 gateway's Python interface (ij.py.*).

def from_java(data):
    """
    Convert Java objects to Python equivalents.
    
    Args:
        data: Java object (Dataset, RandomAccessibleInterval, ImagePlus, etc.)
        
    Returns:
        Python equivalent (xarray.DataArray, numpy.ndarray, dict, etc.)
    """

def to_java(data, **hints):
    """
    Convert Python objects to Java equivalents.
    
    Args:
        data: Python object (numpy array, xarray, pandas DataFrame, etc.) 
        **hints: Optional conversion hints for fine-tuning conversion
        
    Returns:
        Java object suitable for ImageJ2 operations
    """

ImageJ2 Dataset Conversion

Convert data to ImageJ2's primary image format with dimension metadata support.

def to_dataset(data, dim_order=None) -> "Dataset":
    """
    Convert data to ImageJ2 Dataset with optional dimension reordering.
    
    Args:
        data: Python image data (numpy array, xarray) or Java image
        dim_order: Sequence of dimension names for reordering (e.g. ["x", "y", "z", "t"])
        
    Returns:
        net.imagej.Dataset with proper axis metadata
    """

Usage Examples:

import numpy as np
import xarray as xr

# Convert NumPy array to Dataset
array = np.random.rand(100, 100, 50)
dataset = ij.py.to_dataset(array, dim_order=["x", "y", "z"])

# Convert xarray to Dataset (preserves existing dimension names)
xarray_data = xr.DataArray(array, dims=["height", "width", "depth"])
dataset = ij.py.to_dataset(xarray_data)

# Convert Java image to Dataset
img = ij.op().create().img([256, 256])
dataset = ij.py.to_dataset(img)

ImgLib2 Image Conversion

Convert data to ImgLib2's core image format for high-performance processing.

def to_img(data, dim_order=None) -> "Img":
    """
    Convert data to ImgLib2 Img format.
    
    Args:
        data: Python image data or Java image
        dim_order: Optional dimension reordering for Python data
        
    Returns:
        net.imglib2.img.Img suitable for ImgLib2 operations
    """

ImageJ ImagePlus Conversion

Convert data to original ImageJ's ImagePlus format (requires legacy support).

def to_imageplus(data) -> "ImagePlus":
    """
    Convert data to ImageJ ImagePlus format.
    
    Args:
        data: Python image data or Java image
        
    Returns:
        ij.ImagePlus for use with original ImageJ plugins
        
    Raises:
        ImportError: If legacy ImageJ support is not available
    """

xarray DataArray Conversion

Convert data to xarray format with labeled dimensions and metadata.

def to_xarray(data, dim_order=None) -> xr.DataArray:
    """
    Convert data to xarray DataArray with dimension labels.
    
    Args:
        data: Python or Java image data
        dim_order: Sequence of dimension names for Python data
        
    Returns:
        xarray.DataArray with labeled dimensions and coordinates
    """

Usage Examples:

# Convert Java Dataset to xarray
dataset = ij.io().open("image.tif")
xarray_data = ij.py.to_xarray(dataset)
print(xarray_data.dims)  # ('z', 'y', 'x', 'c')

# Convert NumPy with custom dimensions
array = np.random.rand(10, 256, 256, 3)
xarray_data = ij.py.to_xarray(array, dim_order=["t", "y", "x", "c"])

# Access dimension information
print(xarray_data.coords)
print(xarray_data.attrs)

Type Information and Utilities

Query and manipulate data types across Python and Java formats.

def dtype(image_or_type):
    """
    Get NumPy dtype of image data.
    
    Args:
        image_or_type: NumPy array, Java image, or dtype object
        
    Returns:
        numpy.dtype representing the image data type
    """

def initialize_numpy_image(image) -> np.ndarray:
    """
    Create zero-filled NumPy array matching input image shape and dtype.
    
    Args:
        image: Template image (NumPy array or Java image)
        
    Returns:
        Zero-initialized NumPy array with same shape and dtype
    """

def is_arraylike(arr) -> bool:
    """
    Check if object has array-like properties.
    
    Args:
        arr: Object to check for arraylike properties
        
    Returns:
        True if object has .shape, .dtype, .__array__, and .ndim attributes
    """

def is_xarraylike(xarr) -> bool:
    """
    Check if object has xarray-like properties.
    
    Args:
        xarr: Object to check for xarraylike properties
        
    Returns:
        True if object has .values, .dims, .coords and arraylike .values
    """

def is_memoryarraylike(arr) -> bool:
    """
    Check if object is arraylike with memoryview data.
    
    Args:
        arr: Object to check for memoryarraylike properties
        
    Returns:
        True if arraylike object with .data type as memoryview
    """

def create_ndarray(image) -> np.ndarray:
    """
    Create NumPy ndarray with same dimensions as input image.
    
    Args:
        image: Template image (automatically handles dimension reversal for RAI)
        
    Returns:
        Zero-initialized ndarray matching image shape and dtype
    """

Low-Level Conversion Functions

Direct conversion functions from the convert module for advanced use cases.

# Java to Python conversions
def java_to_dataset(ij, jobj, dim_order=None) -> "Dataset": ...
def java_to_img(ij, jobj) -> "Img": ...
def java_to_xarray(ij, data) -> xr.DataArray: ...
def java_to_ndarray(ij, data) -> np.ndarray: ...

# Python to Java conversions  
def xarray_to_dataset(ij, xarray_data) -> "Dataset": ...
def xarray_to_img(ij, xarray_data) -> "Img": ...
def ndarray_to_xarray(array, dim_order=None) -> xr.DataArray: ...

# Specialized conversions
def imageplus_to_imgplus(ij, imp) -> "ImgPlus": ...
def ctype_to_realtype(ctype_obj): ...
def realtype_to_ctype(realtype_obj): ...

Specialized Conversion Functions

Advanced conversion functions for specialized data types and structures.

def labeling_to_imglabeling(ij, labeling: Labeling):
    """
    Convert a Python Labeling to an equivalent Java ImgLabeling.
    
    Args:
        ij: The ImageJ2 gateway
        labeling: Python Labeling object from the labeling package
        
    Returns:
        Java ImgLabeling for use with ImageJ2 segmentation operations
        
    Note:
        Uses temporary file I/O for data transfer between Python and Java
    """

def imglabeling_to_labeling(ij, imglabeling: "ImgLabeling"):
    """
    Convert a Java ImgLabeling to an equivalent Python Labeling.
    
    Args:
        ij: The ImageJ2 gateway
        imglabeling: Java ImgLabeling object
        
    Returns:
        Python Labeling object for analysis and visualization
    """

def image_metadata_to_dict(ij, image_meta: "ImageMetadata") -> dict:
    """
    Convert SCIFIO ImageMetadata to Python dictionary.
    
    Args:
        ij: The ImageJ2 gateway
        image_meta: io.scif.ImageMetadata object
        
    Returns:
        Dictionary containing all SCIFIO field information
    """

def metadata_wrapper_to_dict(ij, metadata_wrapper: "MetadataWrapper") -> dict:
    """
    Convert SCIFIO MetadataWrapper to Python dictionary.
    
    Args:
        ij: The ImageJ2 gateway
        metadata_wrapper: io.scif.filters.MetadataWrapper object
        
    Returns:
        Dictionary with implementation class and unwrapped metadata
    """

Conversion Support Checking

Functions to verify conversion compatibility before attempting operations.

def supports_java_to_xarray(ij, java_obj) -> bool: ...
def supports_java_to_ndarray(ij, java_obj) -> bool: ...
def supports_ctype_to_realtype(obj) -> bool: ...
def supports_realtype_to_ctype(obj) -> bool: ...
def supports_labeling_to_imglabeling(obj) -> bool: ...
def supports_imglabeling_to_labeling(obj) -> bool: ...

Memory Management

Direct memory operations for high-performance scenarios.

def rai_to_numpy(rai, numpy_array) -> np.ndarray:
    """
    Copy RandomAccessibleInterval data into pre-allocated NumPy array.
    
    Args:
        rai: Java RandomAccessibleInterval source
        numpy_array: Pre-allocated NumPy array (must match RAI dimensions)
        
    Returns:
        The numpy_array filled with RAI data
        
    Note:
        Dimensions must be in reverse order (e.g. RAI[t,z,y,x,c] → NumPy[c,x,y,z,t])
    """

def copy_rai_into_ndarray(ij, rai: "RandomAccessibleInterval", narr: np.ndarray) -> None:
    """
    Copy ImgLib2 RandomAccessibleInterval into NumPy ndarray with optimization.
    
    Args:
        ij: The ImageJ2 gateway
        rai: Source RandomAccessibleInterval
        narr: Pre-allocated NumPy ndarray with reversed dimensions
        
    Note:
        Uses fast copy via ImgUtil.copy for ImgLib2 5.9.0+ or falls back to
        slower pixel-by-pixel copy. Dimensions must be reversed between 
        RAI and NumPy array (e.g. RAI[t,z,y,x,c] → NumPy[c,x,y,z,t]).
        
    Raises:
        TypeError: If rai is not a RandomAccessibleInterval or narr not arraylike
    """

Data Type Mappings

PyImageJ automatically handles type conversions between Python and Java:

Python TypeJava TypeUsage
numpy.uint8UnsignedByteType8-bit images
numpy.uint16UnsignedShortType16-bit images
numpy.float32FloatType32-bit float processing
numpy.float64DoubleType64-bit precision
xarray.DataArrayDatasetImages with metadata
pandas.DataFrameTableTabular data

Dimension Handling

PyImageJ uses different dimension conventions:

  • Python (NumPy/xarray): [c, x, y, z, t] (channel-first)
  • ImageJ2: [x, y, z, c, t] (spatial-first)
  • Original ImageJ: [x, y, c, z, t] (XYCZT order)

Conversions automatically handle these differences, with optional dim_order parameter for explicit control.

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