Aller au contenu
Cette page n'est pas encore disponible dans votre langue. La version anglaise est affichée.

CT and MR Volume Annotation for DICOM and NIfTI

Paint label masks on CT and MR scans in three linked views, fill the slices between painted ones, and export NIfTI label volumes or DICOM SEG objects.

The volume_annotation scheme shows a CT or MR scan in three linked views (axial, coronal, and sagittal), and annotators paint a mask for each label with a brush or by closing a polygon. Interpolation fills the slices between two painted axial slices, and an RTSTRUCT on the item can provide the starting masks. Masks export as NIfTI label volumes for training pipelines, and masks on DICOM sources also export as DICOM SEG objects for picture archives and clinical viewers. The scheme fits studies in which several annotators segment the same scans, and Potato's agreement report scores the annotators' masks by 3D Dice per label. Potato added the scheme in version 2.12.0. From version 2.15.0, a Skeleton tool also traces neurons and other branching structures as nodes and edges, and the swc export writes each traced skeleton as an SWC file.

DICOM is the standard format in which scanners and hospital picture archives (PACS) store medical images, and a CT or MR series is usually a folder of DICOM files with one file per slice. NIfTI stores a whole volume in one .nii or .nii.gz file and is common in research datasets. A DICOM SEG object stores a segmentation as labeled voxels that reference the source images, and an RTSTRUCT stores contours in the format of radiotherapy planning systems. Gray-level windows map a range of intensity values onto the screen's gray levels, and each window is set by a center and a width. CT windows are given in Hounsfield units.

Potato is research software with no clinical or regulatory clearance. The viewer withholds identifying DICOM header fields from annotators but does not de-identify files, and Patient information in DICOM headers lists the data that still reaches the browser. Volume support needs an optional install. The volumes extra installs pydicom, nibabel, and highdicom:

bash
pip install 'potato-annotation[volumes]'

Configuration

The config below gives each scan to three annotators and asks for a lesion mask and a bone-ring mask on the synthetic CT phantom from Potato's examples/image/ct-volume/ folder:

yaml
annotation_task_name: "CT lesion segmentation"
task_dir: .
output_annotation_dir: annotation_output/
media_directory: media
data_files:
  - data/volumes.json
item_properties:
  id_key: id
  text_key: text
num_annotators_per_item: 3
user_config:
  allow_all_users: true
 
annotation_schemes:
  - annotation_type: volume_annotation
    name: ct_segmentation
    description: "Paint the lesion and the bone ring on every slice where each one appears."
    source_field: volume
    labels:
      - name: Lesion
        color: "#e6553a"
        key_value: "1"
        dicom:
          category: {code: "49755003", scheme: SCT, meaning: Morphologically Altered Structure}
          type: {code: "52988006", scheme: SCT, meaning: Lesion}
      - {name: Bone, color: "#3a8ee6", key_value: "2"}
    tools: [brush, eraser, polygon]
    prefill_rtstruct_field: rtstruct
    window_presets:
      - {name: Abdomen, center: 40, width: 400}
      - {name: Wide bone, center: 400, width: 1800}
    default_window: Abdomen
    display_tags: [Modality, BodyPartExamined, SliceThickness]

The tool list leaves out the box tool, because a box is saved as a separate shape and never becomes mask voxels. Potato adds the Navigate tool to every tool list. A NIfTI file has no modality header, and a NIfTI scan therefore gets only the presets in window_presets and an automatic window. Both copies of the phantom offer the two presets. The DICOM copy also offers From file, Soft tissue, Lung, Bone, Brain, and Auto, and the NIfTI copy adds only Auto. Neither preset name repeats a built-in CT preset, and the window menu lists each name once. With three annotators on each scan, the agreement report adds STAPLE estimates of each annotator's sensitivity and specificity to the Dice scores.

The dicom: block gives the Lesion segment SNOMED CT codes in a DICOM SEG or SR export. Bone has no dicom: block and gets SNOMED CT 85756007 "Tissue" as both the category and the type. The three display_tags keywords appear under the views, and none of the three identifies a patient. Potato checks the labels, tools, views, brush size, tag lists, window presets, and default_window when the server starts, and stops with a message naming any bad value.

Data format

Each item names a volume relative to media_directory. The value is a directory holding one DICOM series, or a .nii or .nii.gz file:

json
[
  {"id": "phantom_dicom", "volume": "phantom_dicom", "rtstruct": "phantom_rtstruct.dcm",
   "text": "Synthetic CT phantom (DICOM series), with the lesion outlined in an RTSTRUCT"},
  {"id": "phantom_nifti", "volume": "phantom.nii.gz",
   "text": "The same phantom as NIfTI"}
]

Potato reads the rtstruct field only because prefill_rtstruct_field names the field, and an item without an RTSTRUCT opens with empty masks. File and directory names reach the browser in the item data and in error messages. PACS exports often name directories after the patient's name or record number, so give case directories pseudonymous names such as case_001/.

Options

volume_annotation optionDefaultMeaning
namerequiredScheme name
descriptionrequiredThe question shown above the viewer
labelsrequiredNames, or {name, color, key_value, dicom, swc_type}. Names must be unique, with at most 254 labels. A label without a color takes the palette color at the label's position in the label list, and an uncolored second label gets the second of Potato's eight colors. key_value is the key that selects the label. swc_type sets the SWC structure type of the label's skeleton nodes, as a whole number from 0 to 255
source_fieldvolumeThe item field holding the volume path
toolsnavigate, brush, eraser, box, and polygonAny of the five defaults and skeleton. navigate is always added, and skeleton appears only when the list names the tool
viewsall threeAny of axial, coronal, and sagittal
window_presetsnoneExtra windows as {name, center, width}, listed first in the window menu. The width must be positive
default_windowfirst listed windowThe window the viewer opens in. The name must match a window_presets entry or a built-in CT preset (Soft tissue, Lung, Bone, or Brain)
brush_size2Starting brush radius in voxels of the finer of the view's two axes, as a positive number. The toolbar slider runs from 1 to 15
prefill_rtstruct_fieldnoneThe item field naming an RTSTRUCT whose ROIs become the starting masks
display_tagsnoneDICOM header keywords shown under the views
allow_identifying_tagsnoneIdentifying keywords from display_tags that may be shown

A label's dicom: block takes an optional category, type, and anatomic_region. Each entry is {code, scheme, meaning}, with a code of at most 64 characters, a scheme designator such as SCT or DCM of at most 16, and a meaning of at most 64. A missing category or type falls back to SNOMED CT "Tissue" by itself, and a label without the block gets "Tissue" for both.

Window presets

The window menu lists the scheme's window_presets first. A DICOM series whose header stores a window adds the stored window next, and a series whose header says CT adds four built-in presets (soft tissue 40/400, lung -600/1500, bone 400/1800, and brain 40/80). Every volume also gets an automatic window from the 1st to the 99th percentile of the volume's values. A NIfTI scan gets only the scheme's presets and the automatic window. Annotators can also adjust the window by dragging with the right mouse button on any view. A horizontal drag changes the width, and a vertical drag changes the center.

Patient information in DICOM headers

DICOM headers usually contain the patient's name, ID, birth date, and institution. The viewer shows annotators only the header keywords listed in display_tags. A keyword on the list of the DICOM basic confidentiality profile (PS3.15) appears only when allow_identifying_tags also names the keyword. Potato's list has 59 keywords, including PatientName, PatientID, PatientBirthDate, InstitutionName, AccessionNumber, the study and series dates, the study, series, and instance UIDs, StudyDescription, and SeriesDescription. The server applies the filter to every request, and a browser cannot ask for other keywords.

Potato's /media/ route refuses DICOM and NIfTI files, whether or not the request comes from a signed-in user. The route recognizes a DICOM file by the file's content, with or without a .dcm suffix. The check looks for the "DICM" marker of the DICOM Part 10 preamble at byte 128, and a DICOM file written without the preamble is served like any other file. Convert such files to Part 10 or keep the files out of the served media directory. Setting serve_raw_medical_files: true at the top level of the config allows raw downloads. Like every other file under /media/, the raw files are then served without sign-in to anyone who has the URL, so turn the setting on only for de-identified data. The slice images, the volume description, interpolation, and RTSTRUCT loading all need a signed-in user.

The header filter leaves three channels open. First, file and directory names reach the browser. Second, Potato checks pixels only through the BurnedInAnnotation flag. Ultrasound images and secondary captures often have patient details written into the image, and Potato refuses to load a series marked BurnedInAnnotation YES. Pixels in a series without the flag are not inspected. Third, the files on disk stay as uploaded, so de-identify the files before upload whenever the people running the server must not see identifying data. Because the DICOM standard requires a SEG to copy the patient and study modules from the source images, a DICOM SEG export is identifiable. A NIfTI export contains the label volume and the source's geometry, and none of the source's header fields.

Painting masks in the three views

The toolbar holds the tool buttons, the brush-size slider, the window menu, Interpolate, and Undo, and the label buttons sit under the toolbar. Each tool and action has a key:

KeyAction
nNavigate. A click moves the other two views to the clicked point
b / eBrush and eraser for the selected label
pPolygon
xBox
kSkeleton, when the tool list names the tool
iInterpolate the selected label
Ctrl+Z or Cmd+ZUndo, up to the last 30 edits
↑ / ↓, Page Up / Page DownNext or previous slice in the focused view
A label's key_valueSelect the label

Annotators change slice by scrolling over a view, with the slider under the view, or with the arrow keys. A crosshair on each view marks where the other two views cut the volume. Each view is drawn at the volume's physical aspect ratio, and the brush radius is measured in voxels of the finer of the view's two axes. A brush stroke on a coronal or sagittal view therefore stays round in millimeters on a scan with thick slices. Potato writes a stroke on the coronal or sagittal view into every axial slice the stroke crosses, because Potato stores each mask as a set of axial slices.

A polygon takes one click per vertex and closes on a double-click or Enter, and Esc cancels a polygon in progress. Closing a polygon of three or more points paints the polygon's region into the selected label's mask on the polygon's slice, as the brush would. The painted region reaches the exports and the Dice score, and Undo takes the region back. A box is a drag, and boxes are listed under the views. Clicking a box in the list jumps to the box's slice, and the box's Remove button deletes the box. Boxes are not mask voxels and are not scored.

The views follow radiological convention, with the patient's right on the viewer's left. Potato reorients every volume to one canonical orientation (RAS) when the volume is read, so the views show anatomical planes whatever order the scanner wrote the slices in. For an oblique acquisition, the three views are the planes of the nearest orthogonal grid rather than true axial, coronal, and sagittal planes.

Interpolation

Interpolate fills the axial slices between painted axial slices of the selected label, and the label needs paint on at least two axial slices. The server blends each pair of consecutive painted slices through the outlines' signed distance maps. Painted slices never change, and the slices before the first painted slice and after the last one stay empty. Paint the first and last slice of the structure, plus one or more slices in between wherever the shape changes. The filled slices are ordinary mask that annotators can paint over, and Undo removes the filled slices together.

Two outlines that do not overlap blend to nothing in the middle. The middle slices of a non-overlapping pair stay empty, and the status line names the empty slices and the painted pair and suggests painting a slice between the pair. Potato also leaves a blended slice empty when the slice's area is under 10% of the smaller painted outline's area. The 10% floor keeps a few stray pixels out of the narrow end of a blend. Interpolation accepts volumes of up to 2,048 voxels along each axis, slices included.

Tracing neurons and other branching structures

New in v2.15.0

A neuron reconstruction records a branching structure as nodes joined by edges, with a position and a radius for each node, rather than as painted voxels. The Skeleton tool traces such structures in the three views, and the swc export writes the result in the SWC format of Cannon et al. (1998). An SWC file is plain text with one line per node, and each line gives the node's number, structure type, position, radius, and parent. Potato keeps the Skeleton tool off by default. The config below lists only Navigate and Skeleton, and annotators on the scheme trace without painting masks:

yaml
annotation_task_name: "Neuron tracing"
task_dir: .
output_annotation_dir: annotation_output/
media_directory: media
data_files:
  - data/stacks.json
item_properties:
  id_key: id
  text_key: text
user_config:
  allow_all_users: true
 
annotation_schemes:
  - annotation_type: volume_annotation
    name: trace
    description: "Trace the neuron from the soma along each dendrite and the axon."
    source_field: volume
    tools: [navigate, skeleton]
    labels:
      - name: soma
      - name: dendrite
      - name: axon
      - name: spine
        swc_type: 7

Each item names a NIfTI file or a DICOM series under media_directory, as for masks. The tool works by clicks on the slices:

  • Adding nodes. A click adds a node of the selected label at the clicked voxel, joins the node to the selected node, and selects the new node. Clicks along a process therefore trace a path. Change slices between clicks to follow the process through the volume.
  • Branching. A click on an existing node on the slice shown selects the existing node, and the next node joins the selected node as the start of a branch.
  • Starting a new tree. Esc clears the selection, and the next node then starts a new tree.
  • Deleting a node. Delete or Backspace removes the selected node. The node's children join the node's parent, or become roots when the deleted node had no parent. Undo brings the node back.
  • Node radius. The toolbar slider, labeled Size when the Skeleton tool is on, sets the radius of the next node in voxels.

Each view draws the nodes within three slices of the slice shown, fainter with distance, and a white ring marks the selected node. The list under the views counts the nodes and the trees.

The label name sets each node's SWC structure type, matched without regard to case. A label named soma writes type 1, axon type 2, dendrite or basal dendrite type 3, and apical dendrite type 4, and any other name writes type 0. Setting swc_type on a label overrides the name, and the spine label above therefore writes type 7.

Starting masks from an RTSTRUCT

When prefill_rtstruct_field names a field and an item's field names an RTSTRUCT under media_directory, the item opens with the RTSTRUCT's closed planar contours as masks. Potato matches ROIs to labels by case-insensitive name, and the status line lists the ROIs that match no label. A contour on a plane that does not fall on an axial slice is skipped with a warning in the server log. The starting masks appear whenever an item's stored answer has no masks or boxes. An item saved with every mask erased therefore opens with the RTSTRUCT's contours again.

Opening an item saves nothing, but the starting masks go out with the annotator's next save. Pressing Next is a save, so an annotator who moves on without editing accepts the starting contours, and Potato stores and exports the contours as the annotator's masks. To measure how much annotators changed the contours, compare each annotator's export with the RTSTRUCT.

Stored answer

Each scheme stores one JSON value per item:

json
{"volume": "phantom_dicom", "shape": [96, 80, 48], "labels": ["Lesion", "Bone"],
 "masks": {"Lesion": {"21": [4065, 4, 90, 8, 87, 10, 85, 12, 84, 12, 83, 14, 82, 14, 82, 14,
                             82, 14, 83, 12, 84, 12, 85, 10, 87, 8, 90, 4, 2363]}},
 "shapes": [],
 "prefilled_from": "rtstruct"}

The value above is the phantom's RTSTRUCT starting mask, shortened to the first of the lesion's seven slices. Coordinates are voxel indices (i, j, k) in the canonical RAS orientation, where i grows toward the patient's right, j toward anterior, and k toward superior. Each entry under masks is one axial slice k, flattened row by row (row j, column i) and run-length encoded as alternating counts of 0s and 1s. The first count is always a count of 0s. shapes lists the boxes as voxel coordinates, and prefilled_from appears when the masks started from an RTSTRUCT or from a model's pre-labels. A traced skeleton adds a skeleton entry beside masks and shapes:

json
{"skeleton": {"nodes": [{"id": "vol_k3x9qa_1", "label": "soma", "position": [40, 31, 22], "radius": 2, "parent": null},
                        {"id": "vol_k3x9qa_2", "label": "dendrite", "position": [44, 33, 22], "radius": 1, "parent": "vol_k3x9qa_1"}],
              "spacing": [0.8, 0.8, 2.5]}}

Each node's position is a voxel index (i, j, k), radius is in voxels, and parent is another node's id, or null for a root. spacing is the voxel size along each axis.

Export

Three export formats read volume_annotation masks, and the swc format reads traced skeletons:

bash
python -m potato.export -c config.yaml -f volume_nifti -o out/nifti
python -m potato.export -c config.yaml -f dicom_seg -o out/seg
python -m potato.export -c config.yaml -f dicom_sr -o out/sr
python -m potato.export -c config.yaml -f swc -o out/swc
FormatFiles writtenSources
volume_niftiPer annotator, <item>__<scheme>.nii.gz, a uint8 label volume in the source file's voxel order and affine, with 0 for background and 1 for the first label. labels__<scheme>.json at the top of the export maps values to label names, and <item>__<scheme>__shapes.json holds any boxes, plus polygons saved by Potato 2.13.0 or earlierDICOM and NIfTI
dicom_segPer annotator, <item>__<scheme>.dcm, a binary DICOM Segmentation with one segment per label that has voxels, referencing the source seriesDICOM only
dicom_srThe same SEG, plus <item>__<scheme>__sr.dcm, a Comprehensive 3D SR holding a TID 1500 measurement report with each segment's volume in mm³ and the annotator as observerDICOM only
swcPer annotator, <item>__<scheme>.swc for each item with a traced skeleton, one n T x y z R P line per nodeDICOM and NIfTI

dicom_seg and dicom_sr skip NIfTI items with a warning that names the items and points to volume_nifti. Every format skips an item whose stored shape no longer matches the file on disk and names the item in a warning. The dicom_sr format writes the SEG and the SR in one run, because the SR references the SEG by the SEG's instance UID. Each label is a separate segment in a DICOM SEG. A NIfTI label volume has one label per voxel, and where two labels overlap, the later label in the scheme's list wins. Export Formats lists the formats beside the other image and 3D exports.

In an SWC file, every parent comes before the parent's children, and a root's parent is -1. The x y z position is the voxel position multiplied by the voxel spacing along each axis, and the radius R is the voxel radius multiplied by the mean voxel spacing. Positions and radii are in the volume's own units, usually millimeters for NIfTI and DICOM. T is the structure type from the label's swc_type or name. Comment lines at the top of each file name the item, the scheme, the annotator, the source volume, and each label's type.

A node whose parent is missing becomes a root. The export leaves out a node without three numeric coordinates, a node whose id another node already has, and a node more than a million voxels from the origin. A radius that is not a number of 0 or more is written as 1, and the export's warnings list each node the export changed. The swc format needs no extra packages.

Agreement

The agreement report at /admin/iaa scores volume_annotation by 3D Dice per label between each pair of annotators of an item, 2|A∩B| / (|A| + |B|). A pair where neither annotator painted a label is left out for that label rather than counted as agreeing. The report gives the mean Dice per label, the number of pairs behind each mean, and the mean over labels. On items with three or more annotators, the report also runs STAPLE and averages each annotator's sensitivity and specificity per label over the items. For a volume of more than 2,000,000 voxels, STAPLE runs on the bounding box of every annotator's voxels of the label, and specificity is then measured over that box rather than the whole scan. Boxes and skeletons are not scored, and an item whose annotators drew on different versions of the file is left out.

Limits

  • Memory. The server reads each volume whole, as 32-bit floats, and keeps the three most recently used volumes in memory. A 512 × 512 × 300 CT takes about 315 MB.
  • Slice rendering. The server renders each slice as an 8-bit PNG on request, and very large volumes load slowly the first time.
  • DICOM series. A directory with two series, more than one multi-frame file, missing or duplicated slices, slices of different orientations, a gantry tilt over 0.5 degrees, or slices without position or pixel spacing is refused with the reason. dcm2niix resamples a tilted series to orthogonal slices. A multi-frame (enhanced) file alone in a directory is read through the file's per-frame functional groups.
  • NIfTI files. Only 3D files are read. A 4D file with one volume is read as 3D, and a file with more volumes is refused.
  • Not supported. 4D (time series) volumes, fused PET/CT, and oblique reformats.
  • Labels. Each label's mask is binary, and a scheme takes at most 254 labels.

Example

The release's CT phantom example runs from the root of a Potato checkout:

bash
python potato/flask_server.py start examples/image/ct-volume/config.yaml -p 8000

The phantom is a 96 × 80 voxel CT series of 48 slices, with 0.8 mm pixels and 2.5 mm between slices, stored once as a DICOM series and once as NIfTI, plus an RTSTRUCT outlining the lesion. Potato's generator writes made-up patient details into the DICOM header, and the example's display_tags lists PatientName without allowing the keyword, so the viewer withholds the name. generate_volume.py in the same folder writes the media files again. Point data_files at your own scans once the phantom works, and keep display_tags to non-identifying keywords.

Further reading

For implementation details, see the source documentation.