mitk.Image#
- class mitk.Image#
Bases:
pybind11_objectN-dimensional medical image with attached geometry and properties.
mitk.Imagewraps the C++mitk::Imageclass. 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; callinitialize()before reading or writing pixel data.mitk.Image(path)loads from disk (acceptsstrorpathlib.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()andload()are also available.- __init__(*args, **kwargs)#
Overloaded function.
__init__(self: mitk.Image) -> None
Construct an empty image.
The pixel buffer is not allocated until
initialize()is called.__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")
__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
arrayis not array-like.ValueError – If
array.ndimis less than 2 or greater than 4, or ifcopy=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
BaseGeometryfor 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
Noneif 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
Read-only NumPy view of the image buffer at time step 0.
Direction cosine matrix at time step 0 as a 3x3 NumPy array.
Direction cosines at time step 0 as a flat 9-element tuple.
NumPy dtype matching the MITK pixel type.
Number of dimensions of the image (2, 3, or 4).
Origin at time step 0 as a 3-tuple
(ox, oy, oz).Live, mutable view of the image's properties.
List of all property keys currently set on this object.
Image shape in NumPy order.
Voxel spacing at time step 0 as a 3-tuple
(sx, sy, sz).The full
TimeGeometryof this object.Number of time steps.
- __array__(self: mitk.Image, dtype: object = None, copy: object = None) numpy.ndarray#
NumPy array protocol hook.
Allows
numpy.asarray(img)andnumpy.array(img)to work directly on an image. Returns a read-only direct view by default; passesdtypeandcopythrough 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, usearray, or wrap withnumpy.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=Truefor a view backed byImageReadAccessor/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, useuse_accessor=False. Defaults to 0.
- Returns:
NumPy array sharing memory with the image buffer.
- Raises:
mitk.Exception – If the image data cannot be accessed.
ValueError – If
use_accessor=Trueandtime_step != 0.
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 ofImagefor argument details.- Returns:
A new
Imagewrapping the array contents.
- get_dimension(*args, **kwargs)#
Overloaded function.
get_dimension(self: mitk.Image) -> int
Return the number of dimensions of the image.
Equivalent to
ndim.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
BaseGeometryfor 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
Noneif not set.By default returns a coerced Python-native value:
bool,int,float,str, or an(r, g, b)tuple forColorProperty. For types without a known Python equivalent the rawmitk.BasePropertyobject is returned.- Parameters:
key – Property name.
raw – If True, always return the underlying
mitk.BasePropertyobject (useful to access metadata or to pass to a C++ function that expects one). Defaults to False.
- Returns:
The property value, or
Noneif 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.
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 aPixelTypeinstance).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)
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
PixelTypeinstance 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, aMutableMappingbacked by the image’s underlyingIPropertyOwnerinterface. Reading delegates toget_property(); writing and deletion delegate toset_property()/remove_property()and may raisePropertyNotOwnedErrorfor 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
BasePropertysubtype based on its Python type:bool->BoolProperty,int->IntProperty,float->DoubleProperty,str->StringProperty, 3-tuple ->ColorProperty, or an existingmitk.BasePropertyinstance is used as-is.- Parameters:
key – Property name.
value – Property value (auto-wrapped to a
BasePropertysubtype).
- 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
TimeGeometryof this object.
- property time_steps#
Number of time steps.