mitk.Image#

class mitk.Image#

Bases: pybind11_object

N-dimensional medical image with attached geometry and properties.

mitk.Image wraps the C++ mitk::Image class. It stores pixel data of arbitrary numeric type, supports up to four dimensions (three spatial plus time), and carries a full geometry (spacing, origin, direction cosines) plus a typed property dictionary.

Construction is overloaded by argument type:

  • mitk.Image() constructs an empty image; call initialize() before reading or writing pixel data.

  • mitk.Image(path) loads from disk (accepts str or pathlib.Path).

  • mitk.Image(array, spacing=..., origin=..., direction=...) constructs an image from a copy of a NumPy array (the image owns its buffer).

Equivalent factory methods from_numpy() and load() are also available.

__init__(*args, **kwargs)#

Overloaded function.

  1. __init__(self: mitk.Image) -> None

Construct an empty image.

The pixel buffer is not allocated until initialize() is called.

  1. __init__(self: mitk.Image, path: os.PathLike | str | bytes) -> None

Load an image from a file path.

Parameters:

path – Path to an image file. Accepts str, pathlib.Path, or any object with a __fspath__ method.

Raises:

ValueError – If the file cannot be loaded (unknown format, no reader available, or the path does not exist).

Examples

>>> import mitk
>>> img = mitk.Image("input.nrrd")
  1. __init__(self: mitk.Image, array: numpy.ndarray, spacing: typing.Annotated[collections.abc.Sequence[typing.SupportsFloat], “FixedSize(3)”] | None = None, origin: typing.Annotated[collections.abc.Sequence[typing.SupportsFloat], “FixedSize(3)”] | None = None, direction: typing.Annotated[numpy.typing.ArrayLike, numpy.float64] | None = None, copy: bool = True) -> None

Construct an image from a NumPy array.

The array is copied; the resulting image owns its buffer. The NumPy array is interpreted in C order (slowest-varying axis first). For 4D arrays, the slowest axis becomes the time dimension.

Parameters:
  • array – NumPy array with 2, 3, or 4 dimensions. Must be of a supported dtype (uint8, int8, uint16, int16, uint32, int32, float32, float64).

  • spacing – Optional (sx, sy, sz) voxel spacing. Defaults to (1, 1, 1).

  • origin – Optional (ox, oy, oz) origin in world coordinates. Defaults to (0, 0, 0).

  • direction – Optional 3x3 direction cosine matrix. Defaults to identity.

  • copy – Reserved for future zero-copy support. Must currently be True.

Raises:
  • TypeError – If array is not array-like.

  • ValueError – If array.ndim is less than 2 or greater than 4, or if copy=False (not yet supported).

Examples

>>> import numpy as np
>>> img = mitk.Image(np.zeros((64, 64, 64), dtype=np.float32),
...                  spacing=(1.0, 1.0, 2.5))

Methods

__init__(*args, **kwargs)

Overloaded function.

as_numpy(self[, use_accessor, writeable, ...])

Return a NumPy view of the image buffer.

from_numpy(array[, spacing, origin, ...])

Construct an image from a NumPy array (explicit factory).

get_dimension(*args, **kwargs)

Overloaded function.

get_direction(self[, time_step])

Return the direction cosine matrix at the given time step.

get_direction_cosines(self[, time_step])

Return the direction cosines as a flat 9-element tuple.

get_geometry(self[, time_step])

Return the full BaseGeometry for the given time step.

get_origin(self[, time_step])

Return the origin at the given time step.

get_property(self, key[, raw])

Return the property value for key, or None if not set.

get_spacing(self[, time_step])

Return the voxel spacing at the given time step.

initialize(*args, **kwargs)

Overloaded function.

load(path)

Load an image from a file path (explicit factory).

property_is_owned(self, key)

Return True if the property key is owned (writable) by this object.

remove_property(self, key)

Remove the property key if it exists.

save(self, path)

Save the image to a file.

set_direction(self, direction[, time_step])

Set the direction cosine matrix at the given time step.

set_origin(self, origin[, time_step])

Set the origin at the given time step.

set_property(self, key, value)

Set the property key to value.

set_spacing(self, spacing[, time_step])

Set the voxel spacing at the given time step.

Attributes

array

Read-only NumPy view of the image buffer at time step 0.

direction

Direction cosine matrix at time step 0 as a 3x3 NumPy array.

direction_cosines

Direction cosines at time step 0 as a flat 9-element tuple.

dtype

NumPy dtype matching the MITK pixel type.

ndim

Number of dimensions of the image (2, 3, or 4).

origin

Origin at time step 0 as a 3-tuple (ox, oy, oz).

properties

Live, mutable view of the image's properties.

property_keys

List of all property keys currently set on this object.

shape

Image shape in NumPy order.

spacing

Voxel spacing at time step 0 as a 3-tuple (sx, sy, sz).

time_geometry

The full TimeGeometry of this object.

time_steps

Number of time steps.

__array__(self: mitk.Image, dtype: object = None, copy: object = None) numpy.ndarray#

NumPy array protocol hook.

Allows numpy.asarray(img) and numpy.array(img) to work directly on an image. Returns a read-only direct view by default; passes dtype and copy through with the standard NumPy semantics.

property array#

Read-only NumPy view of the image buffer at time step 0.

Zero-copy. The view pins the image alive via a smart-pointer capsule. Equivalent to img.as_numpy(writeable=False, time_step=0).

as_numpy(self: mitk.Image, use_accessor: bool = False, writeable: bool = True, time_step: SupportsInt = 0) numpy.ndarray#

Return a NumPy view of the image buffer.

Writeable by default (matching NumPy convention). For a read-only view pass writeable=False, use array, or wrap with numpy.asarray(img).

By default the view is direct: zero-copy, no locking. The view pins the image alive via a smart-pointer capsule. Pass use_accessor=True for a view backed by ImageReadAccessor / ImageWriteAccessor, which acquires MITK’s read/write lock and releases it when the NumPy array is garbage-collected. Use the accessor-backed mode when other threads (typically C++) may access the image concurrently.

Parameters:
  • use_accessor – If True, return a view backed by ImageReadAccessor/ImageWriteAccessor (lock-acquiring). Defaults to False (direct, unlocked).

  • writeable – If True, return a writable view; otherwise read-only. Defaults to True.

  • time_step – Time-step index for 4D images. Must be 0 when use_accessor=True; for time-step-specific access, use use_accessor=False. Defaults to 0.

Returns:

NumPy array sharing memory with the image buffer.

Raises:

Examples

>>> arr = img.as_numpy()
>>> arr[0, 0, 0] = 1.0
>>> # Concurrency-safe write:
>>> locked = img.as_numpy(use_accessor=True, writeable=True)
>>> locked[5, 5, 5] = 7
>>> del locked  # release the write lock
property direction#

Direction cosine matrix at time step 0 as a 3x3 NumPy array.

property direction_cosines#

Direction cosines at time step 0 as a flat 9-element tuple.

property dtype#

NumPy dtype matching the MITK pixel type.

static from_numpy(array: numpy.ndarray, spacing: Annotated[collections.abc.Sequence[SupportsFloat], 'FixedSize(3)'] | None = None, origin: Annotated[collections.abc.Sequence[SupportsFloat], 'FixedSize(3)'] | None = None, direction: Annotated[numpy.typing.ArrayLike, numpy.float64] | None = None, copy: bool = True) mitk.Image#

Construct an image from a NumPy array (explicit factory).

Equivalent to mitk.Image(array, spacing=..., origin=..., direction=..., copy=...). See the array-constructor overload of Image for argument details.

Returns:

A new Image wrapping the array contents.

get_dimension(*args, **kwargs)#

Overloaded function.

  1. get_dimension(self: mitk.Image) -> int

Return the number of dimensions of the image.

Equivalent to ndim.

  1. get_dimension(self: mitk.Image, i: typing.SupportsInt) -> int

Return the size of the i-th dimension.

Parameters:

i – Dimension index in MITK order (0 = x, 1 = y, 2 = z, 3 = t).

Returns:

The size of the requested dimension, in voxels.

get_direction(self: mitk.Image, time_step: SupportsInt = 0) numpy.typing.NDArray[numpy.float64]#

Return the direction cosine matrix at the given time step.

Parameters:

time_step – Time-step index (default 0).

Returns:

A 3x3 NumPy array of doubles.

get_direction_cosines(self: mitk.Image, time_step: SupportsInt = 0) Annotated[list[float], 'FixedSize(9)']#

Return the direction cosines as a flat 9-element tuple.

Parameters:

time_step – Time-step index (default 0).

Returns:

A 9-element sequence in row-major order.

get_geometry(self: mitk.Image, time_step: SupportsInt = 0) mitk.BaseGeometry#

Return the full BaseGeometry for the given time step.

Parameters:

time_step – Time-step index (default 0).

Returns:

The spatial geometry at the requested time step.

get_origin(self: mitk.Image, time_step: SupportsInt = 0) tuple[float, float, float]#

Return the origin at the given time step.

Parameters:

time_step – Time-step index (default 0).

Returns:

A 3-tuple (ox, oy, oz) in world coordinates.

get_property(self: mitk.Image, key: str, raw: bool = False) object#

Return the property value for key, or None if not set.

By default returns a coerced Python-native value: bool, int, float, str, or an (r, g, b) tuple for ColorProperty. For types without a known Python equivalent the raw mitk.BaseProperty object is returned.

Parameters:
  • key – Property name.

  • raw – If True, always return the underlying mitk.BaseProperty object (useful to access metadata or to pass to a C++ function that expects one). Defaults to False.

Returns:

The property value, or None if the property is not set.

get_spacing(self: mitk.Image, time_step: SupportsInt = 0) tuple[float, float, float]#

Return the voxel spacing at the given time step.

Parameters:

time_step – Time-step index (default 0).

Returns:

A 3-tuple (sx, sy, sz) in world units.

initialize(*args, **kwargs)#

Overloaded function.

  1. initialize(self: mitk.Image, dtype: object, dimensions: collections.abc.Sequence[typing.SupportsInt], channels: typing.SupportsInt = 1) -> None

Initialize the image with the given pixel type and dimensions.

Parameters:
  • dtype – NumPy dtype or any value accepted by make_pixel_type() (for example "float32", numpy.float32, or a PixelType instance).

  • dimensions – List of dimension sizes in MITK order (x, y, z[, t]).

  • channels – Number of components per pixel. Default 1; use 3 for RGB, 4 for RGBA.

Examples

>>> img = mitk.Image()
>>> img.initialize("float32", [64, 64, 64])
>>> img.initialize("uint8", [256, 256, 32], channels=3)
  1. initialize(self: mitk.Image, type: mitk.PixelType, dimensions: collections.abc.Sequence[typing.SupportsInt], channels: typing.SupportsInt = 1) -> None

Initialize the image with a pre-built PixelType.

Parameters:
  • type – A PixelType instance describing the per-pixel layout.

  • dimensions – List of dimension sizes in MITK order (x, y, z[, t]).

  • channels – Number of components per pixel (default 1).

static load(path: os.PathLike | str | bytes) mitk.Image#

Load an image from a file path (explicit factory).

Equivalent to mitk.Image(path).

Parameters:

path – Path to an image file. Accepts str, pathlib.Path, or any object with a __fspath__ method.

Returns:

The loaded image.

Raises:

ValueError – If the file cannot be loaded.

property ndim#

Number of dimensions of the image (2, 3, or 4).

property origin#

Origin at time step 0 as a 3-tuple (ox, oy, oz).

property properties#

Live, mutable view of the image’s properties.

Returns a mitk.property_view.PropertyView, a MutableMapping backed by the image’s underlying IPropertyOwner interface. Reading delegates to get_property(); writing and deletion delegate to set_property() / remove_property() and may raise PropertyNotOwnedError for provided (read-only) properties.

Examples

>>> img.properties["DICOM.PatientName"] = "Doe^John"
>>> for key in img.properties:
...     print(key, img.properties[key])
>>> del img.properties["my.custom.key"]
property_is_owned(self: mitk.Image, key: str) bool#

Return True if the property key is owned (writable) by this object.

Returns False if the property does not exist or is provided read-only (for example, routed from an internal component like a Label inside a MultiLabelSegmentation).

Parameters:

key – Property name.

property property_keys#

List of all property keys currently set on this object.

remove_property(self: mitk.Image, key: str) None#

Remove the property key if it exists.

Parameters:

key – Property name.

Raises:

PropertyNotOwnedError – If the property is provided read-only and cannot be removed.

save(self: mitk.Image, path: os.PathLike | str | bytes) None#

Save the image to a file.

The output format is inferred from the file extension. Common formats: .nrrd, .nii, .nii.gz, .mha, .mhd, .dcm.

Parameters:

path – Output file path. Accepts str, pathlib.Path, or any object with a __fspath__ method.

Raises:

ValueError – If the image is null or the format is not writable.

set_direction(self: mitk.Image, direction: Annotated[numpy.typing.ArrayLike, numpy.float64], time_step: SupportsInt = 0) None#

Set the direction cosine matrix at the given time step.

Parameters:
  • direction – 3x3 array-like (NumPy array, nested list, etc.).

  • time_step – Time-step index (default 0).

set_origin(self: mitk.Image, origin: Annotated[collections.abc.Sequence[SupportsFloat], 'FixedSize(3)'], time_step: SupportsInt = 0) None#

Set the origin at the given time step.

Parameters:
  • origin – 3-element sequence (ox, oy, oz) in world coordinates.

  • time_step – Time-step index (default 0).

set_property(self: mitk.Image, key: str, value: object) None#

Set the property key to value.

The value is auto-wrapped into the appropriate BaseProperty subtype based on its Python type: bool -> BoolProperty, int -> IntProperty, float -> DoubleProperty, str -> StringProperty, 3-tuple -> ColorProperty, or an existing mitk.BaseProperty instance is used as-is.

Parameters:
  • key – Property name.

  • value – Property value (auto-wrapped to a BaseProperty subtype).

Raises:

PropertyNotOwnedError – If the property is provided read-only (not owned) by this object.

set_spacing(self: mitk.Image, spacing: Annotated[collections.abc.Sequence[SupportsFloat], 'FixedSize(3)'], time_step: SupportsInt = 0) None#

Set the voxel spacing at the given time step.

Parameters:
  • spacing – 3-element sequence (sx, sy, sz) in world units.

  • time_step – Time-step index (default 0).

property shape#

Image shape in NumPy order.

For a 3D scalar image of MITK dimensions (x, y, z) this returns (z, y, x). For a multi-channel image an extra trailing axis is appended for the per-pixel component count.

property spacing#

Voxel spacing at time step 0 as a 3-tuple (sx, sy, sz).

property time_geometry#

The full TimeGeometry of this object.

property time_steps#

Number of time steps.