# CT and MR Volume Annotation for DICOM and NIfTI

Source: https://www.potatoannotator.com/docs/annotation-types/volume-annotation

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.

[DICOM](https://en.wikipedia.org/wiki/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](https://en.wikipedia.org/wiki/Neuroimaging_Informatics_Technology_Initiative) 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](https://radiopaedia.org/articles/windowing-ct) 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](#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](/docs/measurement/mask-consensus-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` option | Default | Meaning |
|---|---|---|
| `name` | required | Scheme name |
| `description` | required | The question shown above the viewer |
| `labels` | required | Names, or `{name, color, key_value, dicom}`. 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 |
| `source_field` | `volume` | The item field holding the volume path |
| `tools` | all five | Any of `navigate`, `brush`, `eraser`, `box`, and `polygon`. `navigate` is always added |
| `views` | all three | Any of `axial`, `coronal`, and `sagittal` |
| `window_presets` | none | Extra windows as `{name, center, width}`, listed first in the window menu. The width must be positive |
| `default_window` | first listed window | The 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_size` | `2` | Starting 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_field` | none | The item field naming an RTSTRUCT whose ROIs become the starting masks |
| `display_tags` | none | DICOM header keywords shown under the views |
| `allow_identifying_tags` | none | Identifying 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:

| Key | Action |
|---|---|
| <kbd>n</kbd> | Navigate. A click moves the other two views to the clicked point |
| <kbd>b</kbd> / <kbd>e</kbd> | Brush and eraser for the selected label |
| <kbd>p</kbd> | Polygon |
| <kbd>x</kbd> | Box |
| <kbd>i</kbd> | Interpolate the selected label |
| <kbd>Ctrl</kbd>+<kbd>Z</kbd> or <kbd>Cmd</kbd>+<kbd>Z</kbd> | Undo, up to the last 30 edits |
| <kbd>&uarr;</kbd> / <kbd>&darr;</kbd>, Page Up / Page Down | Next or previous slice in the focused view |
| A label's `key_value` | Select 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 <kbd>Enter</kbd>, and <kbd>Esc</kbd> 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](https://en.wikipedia.org/wiki/Signed_distance_function) 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.

## 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` holds the boxes as voxel coordinates, and `prefilled_from` appears when the masks started from an RTSTRUCT or from a model's pre-labels.

## Export

Three export formats read `volume_annotation` masks:

```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
```

| Format | Files written | Sources |
|---|---|---|
| `volume_nifti` | Per 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 earlier | DICOM and NIfTI |
| `dicom_seg` | Per annotator, `<item>__<scheme>.dcm`, a binary DICOM Segmentation with one segment per label that has voxels, referencing the source series | DICOM only |
| `dicom_sr` | The 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 observer | DICOM only |

`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](/docs/features/export-formats#images-video-3d-and-medical-volumes) lists the formats beside the other image and 3D exports.

## Agreement

The agreement report at `/admin/iaa` scores `volume_annotation` by 3D [Dice](https://en.wikipedia.org/wiki/S%C3%B8rensen%E2%80%93Dice_coefficient) 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](/docs/measurement/mask-consensus-staple) and averages each annotator's sensitivity and specificity per label over the items. On 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 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

- [Segment CT Volumes With Several Readers and STAPLE](/blog/segment-ct-volumes-several-readers) - Three annotators, NIfTI exports, and a consensus mask
- [Medical Image Annotation with Potato](/blog/medical-imaging-annotation) - Radiographs, CT and MR volumes, and whole-slide images
- [Medical Image and Clinical Text Annotation Tools Compared](/docs/guides/medical-annotation-tools-compared) - Potato beside 3D Slicer, ITK-SNAP, OHIF, V7, and Encord
- [Train Models on Volumes, Point Clouds, and Video](/docs/model-training/volumes-point-clouds-video) - The `volume-unet` trainer and mask pre-labels
- [Mask Consensus with STAPLE](/docs/measurement/mask-consensus-staple) - Sensitivity and specificity per annotator
- [Self-Hosted Clinical Text and Medical Image Annotation](/use-cases/healthcare) - Potato for clinical text and medical images

For implementation details, see the [source documentation](https://github.com/davidjurgens/potato/blob/master/docs/annotation-types/multimedia/volume_annotation.md).
