0
# Data Conversion
1
2
Comprehensive conversion system for translating data between Python (NumPy, xarray, pandas) and Java (ImageJ2, ImgLib2, ImagePlus) formats with full metadata preservation and type safety.
3
4
## Capabilities
5
6
### Core Conversion Methods
7
8
Primary conversion functions accessible via the ImageJ2 gateway's Python interface (`ij.py.*`).
9
10
```python { .api }
11
def from_java(data):
12
"""
13
Convert Java objects to Python equivalents.
14
15
Args:
16
data: Java object (Dataset, RandomAccessibleInterval, ImagePlus, etc.)
17
18
Returns:
19
Python equivalent (xarray.DataArray, numpy.ndarray, dict, etc.)
20
"""
21
22
def to_java(data, **hints):
23
"""
24
Convert Python objects to Java equivalents.
25
26
Args:
27
data: Python object (numpy array, xarray, pandas DataFrame, etc.)
28
**hints: Optional conversion hints for fine-tuning conversion
29
30
Returns:
31
Java object suitable for ImageJ2 operations
32
"""
33
```
34
35
### ImageJ2 Dataset Conversion
36
37
Convert data to ImageJ2's primary image format with dimension metadata support.
38
39
```python { .api }
40
def to_dataset(data, dim_order=None) -> "Dataset":
41
"""
42
Convert data to ImageJ2 Dataset with optional dimension reordering.
43
44
Args:
45
data: Python image data (numpy array, xarray) or Java image
46
dim_order: Sequence of dimension names for reordering (e.g. ["x", "y", "z", "t"])
47
48
Returns:
49
net.imagej.Dataset with proper axis metadata
50
"""
51
```
52
53
**Usage Examples:**
54
55
```python
56
import numpy as np
57
import xarray as xr
58
59
# Convert NumPy array to Dataset
60
array = np.random.rand(100, 100, 50)
61
dataset = ij.py.to_dataset(array, dim_order=["x", "y", "z"])
62
63
# Convert xarray to Dataset (preserves existing dimension names)
64
xarray_data = xr.DataArray(array, dims=["height", "width", "depth"])
65
dataset = ij.py.to_dataset(xarray_data)
66
67
# Convert Java image to Dataset
68
img = ij.op().create().img([256, 256])
69
dataset = ij.py.to_dataset(img)
70
```
71
72
### ImgLib2 Image Conversion
73
74
Convert data to ImgLib2's core image format for high-performance processing.
75
76
```python { .api }
77
def to_img(data, dim_order=None) -> "Img":
78
"""
79
Convert data to ImgLib2 Img format.
80
81
Args:
82
data: Python image data or Java image
83
dim_order: Optional dimension reordering for Python data
84
85
Returns:
86
net.imglib2.img.Img suitable for ImgLib2 operations
87
"""
88
```
89
90
### ImageJ ImagePlus Conversion
91
92
Convert data to original ImageJ's ImagePlus format (requires legacy support).
93
94
```python { .api }
95
def to_imageplus(data) -> "ImagePlus":
96
"""
97
Convert data to ImageJ ImagePlus format.
98
99
Args:
100
data: Python image data or Java image
101
102
Returns:
103
ij.ImagePlus for use with original ImageJ plugins
104
105
Raises:
106
ImportError: If legacy ImageJ support is not available
107
"""
108
```
109
110
### xarray DataArray Conversion
111
112
Convert data to xarray format with labeled dimensions and metadata.
113
114
```python { .api }
115
def to_xarray(data, dim_order=None) -> xr.DataArray:
116
"""
117
Convert data to xarray DataArray with dimension labels.
118
119
Args:
120
data: Python or Java image data
121
dim_order: Sequence of dimension names for Python data
122
123
Returns:
124
xarray.DataArray with labeled dimensions and coordinates
125
"""
126
```
127
128
**Usage Examples:**
129
130
```python
131
# Convert Java Dataset to xarray
132
dataset = ij.io().open("image.tif")
133
xarray_data = ij.py.to_xarray(dataset)
134
print(xarray_data.dims) # ('z', 'y', 'x', 'c')
135
136
# Convert NumPy with custom dimensions
137
array = np.random.rand(10, 256, 256, 3)
138
xarray_data = ij.py.to_xarray(array, dim_order=["t", "y", "x", "c"])
139
140
# Access dimension information
141
print(xarray_data.coords)
142
print(xarray_data.attrs)
143
```
144
145
### Type Information and Utilities
146
147
Query and manipulate data types across Python and Java formats.
148
149
```python { .api }
150
def dtype(image_or_type):
151
"""
152
Get NumPy dtype of image data.
153
154
Args:
155
image_or_type: NumPy array, Java image, or dtype object
156
157
Returns:
158
numpy.dtype representing the image data type
159
"""
160
161
def initialize_numpy_image(image) -> np.ndarray:
162
"""
163
Create zero-filled NumPy array matching input image shape and dtype.
164
165
Args:
166
image: Template image (NumPy array or Java image)
167
168
Returns:
169
Zero-initialized NumPy array with same shape and dtype
170
"""
171
172
def is_arraylike(arr) -> bool:
173
"""
174
Check if object has array-like properties.
175
176
Args:
177
arr: Object to check for arraylike properties
178
179
Returns:
180
True if object has .shape, .dtype, .__array__, and .ndim attributes
181
"""
182
183
def is_xarraylike(xarr) -> bool:
184
"""
185
Check if object has xarray-like properties.
186
187
Args:
188
xarr: Object to check for xarraylike properties
189
190
Returns:
191
True if object has .values, .dims, .coords and arraylike .values
192
"""
193
194
def is_memoryarraylike(arr) -> bool:
195
"""
196
Check if object is arraylike with memoryview data.
197
198
Args:
199
arr: Object to check for memoryarraylike properties
200
201
Returns:
202
True if arraylike object with .data type as memoryview
203
"""
204
205
def create_ndarray(image) -> np.ndarray:
206
"""
207
Create NumPy ndarray with same dimensions as input image.
208
209
Args:
210
image: Template image (automatically handles dimension reversal for RAI)
211
212
Returns:
213
Zero-initialized ndarray matching image shape and dtype
214
"""
215
```
216
217
### Low-Level Conversion Functions
218
219
Direct conversion functions from the convert module for advanced use cases.
220
221
```python { .api }
222
# Java to Python conversions
223
def java_to_dataset(ij, jobj, dim_order=None) -> "Dataset": ...
224
def java_to_img(ij, jobj) -> "Img": ...
225
def java_to_xarray(ij, data) -> xr.DataArray: ...
226
def java_to_ndarray(ij, data) -> np.ndarray: ...
227
228
# Python to Java conversions
229
def xarray_to_dataset(ij, xarray_data) -> "Dataset": ...
230
def xarray_to_img(ij, xarray_data) -> "Img": ...
231
def ndarray_to_xarray(array, dim_order=None) -> xr.DataArray: ...
232
233
# Specialized conversions
234
def imageplus_to_imgplus(ij, imp) -> "ImgPlus": ...
235
def ctype_to_realtype(ctype_obj): ...
236
def realtype_to_ctype(realtype_obj): ...
237
```
238
239
### Specialized Conversion Functions
240
241
Advanced conversion functions for specialized data types and structures.
242
243
```python { .api }
244
def labeling_to_imglabeling(ij, labeling: Labeling):
245
"""
246
Convert a Python Labeling to an equivalent Java ImgLabeling.
247
248
Args:
249
ij: The ImageJ2 gateway
250
labeling: Python Labeling object from the labeling package
251
252
Returns:
253
Java ImgLabeling for use with ImageJ2 segmentation operations
254
255
Note:
256
Uses temporary file I/O for data transfer between Python and Java
257
"""
258
259
def imglabeling_to_labeling(ij, imglabeling: "ImgLabeling"):
260
"""
261
Convert a Java ImgLabeling to an equivalent Python Labeling.
262
263
Args:
264
ij: The ImageJ2 gateway
265
imglabeling: Java ImgLabeling object
266
267
Returns:
268
Python Labeling object for analysis and visualization
269
"""
270
271
def image_metadata_to_dict(ij, image_meta: "ImageMetadata") -> dict:
272
"""
273
Convert SCIFIO ImageMetadata to Python dictionary.
274
275
Args:
276
ij: The ImageJ2 gateway
277
image_meta: io.scif.ImageMetadata object
278
279
Returns:
280
Dictionary containing all SCIFIO field information
281
"""
282
283
def metadata_wrapper_to_dict(ij, metadata_wrapper: "MetadataWrapper") -> dict:
284
"""
285
Convert SCIFIO MetadataWrapper to Python dictionary.
286
287
Args:
288
ij: The ImageJ2 gateway
289
metadata_wrapper: io.scif.filters.MetadataWrapper object
290
291
Returns:
292
Dictionary with implementation class and unwrapped metadata
293
"""
294
```
295
296
### Conversion Support Checking
297
298
Functions to verify conversion compatibility before attempting operations.
299
300
```python { .api }
301
def supports_java_to_xarray(ij, java_obj) -> bool: ...
302
def supports_java_to_ndarray(ij, java_obj) -> bool: ...
303
def supports_ctype_to_realtype(obj) -> bool: ...
304
def supports_realtype_to_ctype(obj) -> bool: ...
305
def supports_labeling_to_imglabeling(obj) -> bool: ...
306
def supports_imglabeling_to_labeling(obj) -> bool: ...
307
```
308
309
### Memory Management
310
311
Direct memory operations for high-performance scenarios.
312
313
```python { .api }
314
def rai_to_numpy(rai, numpy_array) -> np.ndarray:
315
"""
316
Copy RandomAccessibleInterval data into pre-allocated NumPy array.
317
318
Args:
319
rai: Java RandomAccessibleInterval source
320
numpy_array: Pre-allocated NumPy array (must match RAI dimensions)
321
322
Returns:
323
The numpy_array filled with RAI data
324
325
Note:
326
Dimensions must be in reverse order (e.g. RAI[t,z,y,x,c] → NumPy[c,x,y,z,t])
327
"""
328
329
def copy_rai_into_ndarray(ij, rai: "RandomAccessibleInterval", narr: np.ndarray) -> None:
330
"""
331
Copy ImgLib2 RandomAccessibleInterval into NumPy ndarray with optimization.
332
333
Args:
334
ij: The ImageJ2 gateway
335
rai: Source RandomAccessibleInterval
336
narr: Pre-allocated NumPy ndarray with reversed dimensions
337
338
Note:
339
Uses fast copy via ImgUtil.copy for ImgLib2 5.9.0+ or falls back to
340
slower pixel-by-pixel copy. Dimensions must be reversed between
341
RAI and NumPy array (e.g. RAI[t,z,y,x,c] → NumPy[c,x,y,z,t]).
342
343
Raises:
344
TypeError: If rai is not a RandomAccessibleInterval or narr not arraylike
345
"""
346
```
347
348
## Data Type Mappings
349
350
PyImageJ automatically handles type conversions between Python and Java:
351
352
| Python Type | Java Type | Usage |
353
|-------------|-----------|--------|
354
| `numpy.uint8` | `UnsignedByteType` | 8-bit images |
355
| `numpy.uint16` | `UnsignedShortType` | 16-bit images |
356
| `numpy.float32` | `FloatType` | 32-bit float processing |
357
| `numpy.float64` | `DoubleType` | 64-bit precision |
358
| `xarray.DataArray` | `Dataset` | Images with metadata |
359
| `pandas.DataFrame` | `Table` | Tabular data |
360
361
## Dimension Handling
362
363
PyImageJ uses different dimension conventions:
364
365
- **Python (NumPy/xarray)**: `[c, x, y, z, t]` (channel-first)
366
- **ImageJ2**: `[x, y, z, c, t]` (spatial-first)
367
- **Original ImageJ**: `[x, y, c, z, t]` (XYCZT order)
368
369
Conversions automatically handle these differences, with optional `dim_order` parameter for explicit control.