MultiLabel Segmentation
MultiLabelSegmentation – 4D label volume with group semantics.
This module provides:
MultiLabelSegmentation: Container of label groups backed by a 4D numpy array. Label values are globally unique across all groups; value 0 is reserved. Supports group-level image access, label properties editing, and value remapping.LabelGroup: A named collection of labels within aMultiLabelSegmentation, exposed as a live view (itslabelsandimagereflect the segmentation’s current state at access time).Label: A single label with value, name, color, opacity, visibility, and lock state.
- class mitk_workbench_remote.multilabel.Label(value=None, name='', *, color=(1.0, 1.0, 1.0), opacity=1.0, visible=True, locked=False, tracking_id=None, tracking_uid=None, description=None)
Bases:
objectA single label within a MultiLabelSegmentation.
Label value 0 is reserved as UNLABELED_VALUE and is rejected. When created with
value=None, the value is assigned byMultiLabelSegmentation.add_label()via_assign_value().- Parameters:
value (
int|None(default:None)) – Integer label value (>= 1), orNonefor deferred assignment.name (
str(default:'')) – Human-readable label name.color (
tuple[float,float,float] (default:(1.0, 1.0, 1.0))) – RGB color tuple with components in [0.0, 1.0].opacity (
float(default:1.0)) – Opacity in [0.0, 1.0].visible (
bool(default:True)) – Whether the label is visible.locked (
bool(default:False)) – Whether the label is locked for editing.tracking_id (
str|None(default:None)) – Optional external tracking identifier.tracking_uid (
str|None(default:None)) – Optional external tracking UID.description (
str|None(default:None)) – Optional free-text description.
- Raises:
ValueError – If
value == 0(reserved) orcolorcomponents out of range.
- class mitk_workbench_remote.multilabel.LabelGroup(name=None)
Bases:
objectOne group of a MultiLabelSegmentation.
Returned by
MultiLabelSegmentation.groupsandMultiLabelSegmentation.get_group(). A LabelGroup is a live view over its owning segmentation, not a point-in-time copy:labelsandimagereflect the segmentation’s current state at access time.It also remains the internal membership record: the ordered label values (
label_ids) are read directly by the segmentation and the NRRD I/O layer. Label objects themselves live in the parent’sMultiLabelSegmentation_labelsregistry.- property name: str | None
Group name, or
Noneif unnamed.Read-only, matching native
mitk.LabelGroup(a read-only snapshot). Rename viaMultiLabelSegmentation.set_group_name().
- property index: int
0-based position of this group within the owning segmentation.
- Raises:
RuntimeError – If this group is not attached to a segmentation (e.g. a bare
LabelGroup(...)obtained other than viaseg.groupsorseg.get_group(i)).
- property labels: list[Label]
Label objects in this group, current at access time.
- Raises:
RuntimeError – If this group is not attached to a segmentation.
- property image: Any
The group’s live pixel
Image.Delegates to
MultiLabelSegmentation.get_group_image(), so accessing it lazily zero-allocates the image exactly as that method does, and edits via.image.arraypersist on the segmentation.- Raises:
RuntimeError – If this group is not attached to a segmentation.
- class mitk_workbench_remote.multilabel.MultiLabelSegmentation(*, groups, labels, group_images=None, spacing=None, origin=None, direction=None, properties=None, _shape=None)
Bases:
objectContainer of label groups backed by per-group spatial images.
Label values are globally unique across all groups. Value 0 is reserved as
UNLABELED_VALUE. Group pixel data is stored as individualImageobjects (Noneuntil set or lazily allocated byget_group_image()).Use
create()to build a new segmentation from scratch. The constructor is the primary path for I/O deserialization.- Parameters:
groups (
list[LabelGroup]) – Ordered list of label groups (each pre-populated with label IDs).labels (
dict[int,Label]) – Global label registry mapping value -> Label.group_images (
Sequence[Any|None] |None(default:None)) – Per-group pixel data. Filled withNoneif not given.spacing (
Sequence[float] |ndarray|None(default:None)) – Voxel spacing (3D).origin (
Sequence[float] |ndarray|None(default:None)) – World-space origin (3D).direction (
Sequence[Any] |ndarray|None(default:None)) – Direction cosine matrix (3x3).properties (
dict[str,Any] |None(default:None)) – Data-scope properties dict.
- Raises:
ValueError – On shape/geometry inconsistency or duplicate/missing label IDs.
- classmethod create(*, groups=None, reference=None, shape=None, spacing=None, origin=None, direction=None)
Create a new empty segmentation.
Either
referenceorshapemust be supplied.- Parameters:
groups (
list[LabelGroup] |None(default:None)) – Initial groups. Defaults to an empty list.reference (
Any|None(default:None)) – AnImagefrom which geometry is inherited (overrideable via spacing/origin/direction).shape (
tuple[int,...] |None(default:None)) – Spatial shape(x, y, z)used whenreferenceis not given.spacing (
Sequence[float] |None(default:None)) – Override spacing (defaults to reference geometry or (1, 1, 1)).origin (
Sequence[float] |None(default:None)) – Override origin (defaults to reference geometry or (0, 0, 0)).direction (
ndarray|None(default:None)) – Override direction (defaults to reference geometry or identity).
- Return type:
- Returns:
A new
MultiLabelSegmentationwith no pixel data.- Raises:
ValueError – If neither
referencenorshapeis given.
- property groups: list[LabelGroup]
Ordered list of label groups (copy).
- property labels: list[Label]
All Label objects across all groups, sorted by value.
- Raises:
ValueError – If any label still has
value is None. By construction,add_labelassigns a value before storing, so aNonehere indicates internal-state corruption — aliasing it onto the reservedUNLABELED_VALUE(0) would hide a real bug.
- get_property(key)
Get a property by key.
- set_property(key, value)
Set a property by key.
- remove_property(key)
Remove a property by key.
- to_mitk()
Convert to a
mitk.MultiLabelSegmentation(native MITK Python binding).Requires the
mitkpackage, which is typically only available inside a MITK-provided Python environment. Geometry, pixel data, and all label metadata (groups, labels, colors, lock state, etc.) are transferred via NRRD round-trip.Note: data-scope properties stored in
propertiesare not transferred, because the remote library’s NRRD writer does not embed arbitrary properties. For a full round-trip including data-scope properties, useDataNode.get_data()/DataNode.set_data()withas_type=DataRepresentation.MITK.- Return type:
- Returns:
A
mitk.MultiLabelSegmentationinstance.- Raises:
ImportError – If
mitkis not installed.
- classmethod from_mitk(mitk_seg)
Create from a
mitk.MultiLabelSegmentation(native MITK Python binding).Geometry, pixel data, and all label metadata are transferred via NRRD round-trip.
- Parameters:
mitk_seg (
Any) – A native MITK MultiLabelSegmentation object.- Return type:
- Returns:
A new
MultiLabelSegmentationinstance.- Raises:
ImportError – If
mitkis not installed.
- get_label(value)
Look up a label by value.
Labels are keyed by value, so a miss raises
KeyError(dict-like), matching nativemitk.MultiLabelSegmentation.get_label. Usehas_label()for an existence check that never raises.
- has_label(value)
Return whether a label with the given value exists.
- Parameters:
value (
int) – Integer label value.- Return type:
- Returns:
Trueif a label withvalueexists, elseFalse. Never raises (including for the reservedUNLABELED_VALUE).
- get_group_of_label(value)
Return the index of the group that owns a label.
- get_group(index)
Return the group at the given index.
- Parameters:
index (
int) – Group index.- Return type:
- Returns:
The
LabelGroup.- Raises:
IndexError – If
indexis out of range.
- get_group_by_name(name)
Find a group by name using a linear search.
- Parameters:
name (
str) – Group name to search for.- Return type:
- Returns:
The first matching
LabelGroup, orNone.
- set_group_name(index, name)
Set a group’s display name.
The group’s
LabelGroup.nameis read-only; this is the supported way to rename it, mirroring nativeset_group_name. PassingNoneto clear the name is a remote-only allowance – nativemitkrequires a string and rejectsNone.- Parameters:
- Raises:
IndexError – If
indexis out of range.- Return type:
- get_group_labels(index)
Return all Label objects belonging to a group.
- Parameters:
index (
int) – Group index.- Return type:
- Returns:
Ordered list of
Labelobjects.- Raises:
IndexError – If
indexis out of range.
- get_labels(values)
Return the labels for the given values, in input order.
Missing values are skipped silently (matching native
get_labelsand preserving cross-mode parity). For a strict single lookup that raises, useget_label().
- get_label_values_by_name(name, group=None)
Return the values of all labels whose name equals
name.- Parameters:
- Return type:
- Returns:
Matching label values, sorted ascending (consistent with
label_values); an empty list if none match.- Raises:
IndexError – If
groupis out of range.
- get_group_label_values(index)
Return the label values belonging to a group, in group order.
- Parameters:
index (
int) – Group index.- Return type:
- Returns:
The group’s label values, in group order.
- Raises:
IndexError – If
indexis out of range.
- add_label(label_or_name, /, color=<object object>, group=0)
- Overloads:
self, label (Label), group (int) → Label
self, name (str), color (tuple[float, float, float]), group (int) → Label
Add a label to a group and return it (with its value assigned).
Two spellings, dispatched on the first argument’s type:
add_label(label, group=0)– add an existingLabel.add_label(name, color, group=0)– build and add a label from a name and RGB color.
If
label.valueisNonethe next free integer >= 1 is assigned.Unlike native mitk – which clones the label and reassigns its value on a collision – this stores the given object and raises on collision.
- Parameters:
- Returns:
The added label.
- Raises:
TypeError – If the first argument is neither a Label nor a str, or the str spelling is used without a color.
ValueError – If the value is 0 (reserved) or already exists.
IndexError – If
groupis out of range.
- remove_labels(values)
Remove several labels (and their pixels).
Atomic: every value is validated to exist first (
KeyErrornaming the first missing value) before any label is removed.
- erase_label(value)
Zero every pixel equal to
valuein its group image; keep the label.Unlike
remove_label(), the label metadata is retained. If the group’s image has not been allocated yet this is a no-op on pixels (it does not force allocation). After erasing,validate()reports the label as declared-but-unpainted, which is the intended state.
- erase_labels(values)
erase_label()for several values, with the same atomic validation.
- rename_label(value, name, color)
Set a label’s name and color in one call.
Both
nameandcolorare required, matching nativerename_label.
- merge_labels(target, sources)
Reassign each source label’s pixels to
target, then remove the sources.Simplified vs native
mitk.MultiLabelSegmentation.merge_labels: it does not implement lock handling, merge/overwrite styles, or native’sTransferLabelContentsemantics, and – unlike native, which retains the source labels – it removes them. On use it emitsMitkApiDivergenceWarning. It exists so callers do not break underget_data(as_type=AUTO); for full fidelity use the mitk bindings.In the target group, overlaps are best-effort (the target value wins), which can overwrite another target-group label’s last pixels and leave it declared but unpainted – part of the documented divergence.
- remove_label(value)
Remove a label and zero its pixels in its group image.
Matches native
mitk.MultiLabelSegmentation.remove_label: MITK does not model a “remove the label but keep its orphan pixels” state. To clear a label’s pixels while keeping the label, useerase_label(); to reassign pixels to another label, remap them first, then remove.
- add_group(name=None, image=None, labels=None)
Append a new group and return its index.
Optionally seed the group with pixel
imageand/or a list oflabels.imageandlabelsare positional-or-keyword to mirror nativeadd_group(name, image, labels), so the same call works in both modes.- Parameters:
image (
Any|None(default:None)) – Optional pixel data (ndarray / Image / converter type, same acceptance asset_group_image()).labels (
list[Label] |None(default:None)) – Optional labels to add to the new group (each viaadd_label(); value assignment and collision handling are identical).
- Return type:
- Returns:
Index of the newly added group.
- Raises:
TypeError – If
imagecannot be resolved to an ndarray (not an ndarray,Image, or a type with a registered converter).ValueError – On shape/geometry mismatch of
imageor a duplicate label value.
On any failure the half-seeded group is rolled back, so a raised
add_groupnever leaves a dangling group behind.
- get_group_image(index)
Return the pixel data for a group as an Image.
If no data has been set for this group, a zero-filled Image is created and cached. Edits to the returned Image’s array are reflected in subsequent calls.
- Parameters:
index (
int) – Group index.- Return type:
- Returns:
An
Imagewith this group’s pixels.- Raises:
IndexError – If
indexis out of range.ValueError – If shape is unknown and no pixel data has been set yet.
- set_group_image(index, data)
Set pixel data for a group.
- Parameters:
- Raises:
IndexError – If
indexis out of range.ValueError – If the array shape does not match the segmentation’s shape, ndim < 3, or dtype is not integer-compatible.
- Return type:
- import_group_image(index, data, *, value_map)
Import and remap pixel data into a group.
Source pixel values are remapped according to
value_map. Unmapped values pass through unchanged. Value 0 always maps to 0.- Parameters:
- Raises:
IndexError – If
indexis out of range.ValueError – If a target label name does not exist in the group, or a target integer value does not belong to the group.
- Return type: