Sorting DICOM Slices: Image Position vs Instance Number
- Sorting DICOM slices by Instance Number fails due to reversed acquisition, interleaved MRI, and multi-phase scans.
- Correct ordering projects Image Position (Patient) onto the slice normal vector derived from Image Orientation.
- The slice normal vector comes from the cross product of the row and column direction cosines in the orientation tag.
- Sorting by the Z-axis alone fails for oblique scans like cardiac MRI views and tilted-gantry CT studies.
- After sorting, checking slice spacing against Slice Thickness can reveal duplicate or dropped instances.
To assemble DICOM slices into a correct 3D volume, never sort by file name or Instance Number (0020,0013). You must project each slice’s Image Position (Patient) (0020,0032) onto the slice normal vector calculated from Image Orientation (Patient) (0020,0037). This geometric projection guarantees anatomically correct ordering across every scanner vendor.
When a hospital scanner sends a Computed Tomography (CT) or Magnetic Resonance Imaging (MRI) series, the files arrive as separate files. Over a network connection, these files frequently arrive out of order. If your application sorts them with basic file counters, your 3D reconstructions and clinical viewers will produce scrambled or inverted images.
Why sorting DICOM slices by Instance Number fails in production
Instance Number is defined in Section C.7.6.1 of DICOM Part 3 as an integer that identifies an instance. Many engineers assume this tag works like an array index. On simple test datasets, instance 1 is often the top slice and instance 100 is the bottom slice.
In production hospital environments, this assumption breaks for 4 concrete reasons:
-
Acquisition order differs from anatomical order. Scanners acquire slices from feet to head, or head to feet. If an operator scans in reverse order,
Instance Number1 sits at the patient’s feet. If your viewer expects the head first, the anatomy renders upside down. -
Interleaved MRI acquisition sequences. MRI scanners often acquire odd slices first (1, 3, 5, 7), then even slices (2, 4, 6, 8) to prevent radiofrequency bleeding into adjacent tissue. The scanner tags instances in acquisition order. Sorting by
Instance Numberturns your brain scan into an alternating zigzag. -
Multi-phase contrast studies. In dynamic CT liver studies, the scanner images the same anatomy 4 times as contrast dye flows through blood vessels. The study contains 4 slices at the same physical position, but with different timestamps.
-
Missing or non-sequential numbers. Modalities may skip numbers after a reconstruction failure, or restart indexing at 1 for secondary reconstructions.
To build reliable medical imaging software, you must rely on physical geometry rather than sequence numbers.
How do you sort DICOM slices using Image Position (Patient)?
The DICOM standard defines patient coordinates in the Image Plane Module (PS3.3 Section C.7.6.2). The coordinate system uses millimeters based on 3 axes:
- X-axis: Points from the patient’s right side to their left side.
- Y-axis: Points from the patient’s anterior (front) to posterior (back).
- Z-axis: Points from the patient’s feet to their head.
Two tags give you the spatial position of every slice in that space:
-
Image Position (Patient) (0020,0032): A vector of 3 numbers[Px, Py, Pz]. This gives the 3D coordinate of the upper-left corner of the first pixel in millimeters. -
Image Orientation (Patient) (0020,0037): A vector of 6 direction cosines[Xx, Xy, Xz, Yx, Yy, Yz]. The first 3 values describe the row direction. The last 3 values describe the column direction.
Row Direction X [Xx, Xy, Xz]
(Px, Py, Pz) ───────────────────>
│
│ Column Direction Y [Yx, Yy, Yz]
│
v
Normal Vector N = X × Y (Slice normal)
───> Direction perpendicular to image plane
To sort slices along their physical trajectory, follow 3 mathematical steps:
1. Compute the slice normal vector
The row vector $\vec{X}$ and column vector $\vec{Y}$ form the plane of the image. The cross product of these 2 vectors gives the normal vector $\vec{N}$, pointing perpendicular to the slice plane:
$$\vec{N} = \vec{X} \times \vec{Y} = \begin{bmatrix} X_y Y_z - X_z Y_y \ X_z Y_x - X_x Y_z \ X_x Y_y - X_y Y_x \end{bmatrix}$$
2. Project the slice position onto the normal
Take the dot product of the slice origin vector $\vec{P}$ and the normal vector $\vec{N}$. This calculates the scalar distance $d$ of the slice along its normal axis:
$$d = \vec{P} \cdot \vec{N} = (P_x \cdot N_x) + (P_y \cdot N_y) + (P_z \cdot N_z)$$
3. Sort by projected distance
Sort the instances in your series in ascending order of $d$. This places every slice in strict anatomical sequence, regardless of network arrival order or scanner acquisition order.
Here is a minimal TypeScript implementation:
interface DicomPlane {
instanceUid: string;
position: [number, number, number]; // Tag (0020,0032)
orientation: [number, number, number, // Tag (0020,0037)
number, number, number];
}
export function sortSlices(slices: DicomPlane[]): DicomPlane[] {
if (slices.length <= 1) return slices;
const [Xx, Xy, Xz, Yx, Yy, Yz] = slices[0].orientation;
// Cross product: Normal = X x Y
const Nx = Xy * Yz - Xz * Yy;
const Ny = Xz * Yx - Xx * Yz;
const Nz = Xx * Yy - Xy * Yx;
return [...slices].sort((a, b) => {
const distA = a.position[0] * Nx + a.position[1] * Ny + a.position[2] * Nz;
const distB = b.position[0] * Nx + b.position[1] * Ny + b.position[2] * Nz;
return distA - distB;
});
}
Why simple Z-axis sorting fails for oblique scans and gantry tilt
Some developers skip vector math and sort directly by the Z component of Image Position (Patient) (Pz). This works only for pure axial scans where the imaging plane is perpendicular to the scanner table.
It fails as soon as a hospital sends an oblique or tilted study:
-
Cardiac MRI: Cardiac views (short axis, 4-chamber, 2-chamber) align with the heart muscle, not the patient’s body axes. The normal vector has non-zero components across X, Y, and Z. Sorting solely by
Pzcompares arbitrary height offsets rather than slice depth. -
CT with gantry tilt: Head CT protocols often tilt the gantry 15 to 20 degrees to avoid exposing the patient’s eye lenses to direct radiation. Slices progress along an angled plane. Sorting by Z distorts the true spacing between adjacent slices.
By calculating the cross product from Image Orientation (Patient), your sorting math adapts automatically to any rotation, tilt, or anatomical plane.
Handling common edge cases: scouts, interleaved MRI, and multi-phase scans
Before running your sorting algorithm, you must clean your dataset. Hospital modalities group different types of image data under a single examination:
1. Separate scout views and localizers
Scout views (also called topograms or scanograms) are 2D projection radiograph images taken to plan the scan. Modalities occasionally store them inside the same study or series. A scout view has an orthogonal orientation to the cross-sectional slices.
Before sorting, check that Image Orientation (Patient) matches across the series. If a slice has a normal vector that differs by more than 0.01 from the series mode, remove it from the 3D volume queue.
2. Verify uniform slice spacing
In a valid 3D volume, the distance between adjacent slices should remain constant. After sorting, calculate the step size:
$$\Delta d = d_{i+1} - d_i$$
Compare $\Delta d$ against the Slice Thickness (0018,0050) or Spacing Between Slices (0018,0088) tags. If $\Delta d$ drops to 0, you have duplicate slices. If $\Delta d$ doubles, an instance was dropped during network transmission.
3. Partition 4D time series
For dynamic perfusion CT or multi-phase MRI, multiple slices share the same spatial position across time. Group instances by Temporal Position Identifier (0020,0100) or Acquisition Time (0008,0032) first. Sort each temporal volume independently.
How to structure slice sorting in your cloud ingestion pipeline
A modern cloud imaging product does not sort files inside the web server’s request handler. When a scanner sends 2,000 CT slices over classic DIMSE C-STORE, your network receiver needs to acknowledge each file quickly to avoid association timeouts.
Handling these connections yourself means operating a stateful C-STORE listener, handling dropped packets, and keeping TCP ports open. A managed gateway such as Dicomly handles this connectivity layer for you. It terminates the hospital’s mTLS association. Then it forwards each slice as a standard STOW-RS HTTP POST to your webhook, as outlined in our guide to receiving deliveries.
This setup separates network reception from spatial processing. You give up bare-metal socket control and pay a monthly usage fee. In return, your team avoids debugging association aborts at 2 a.m.
Once instances arrive at your webhook, adopt an asynchronous assembly pipeline:
Hospital Scanner Managed Gateway Webhook Receiver Object Store & Worker
│ │ │ │
│── 1. C-STORE slice ───>│ │ │
│ │── 2. STOW-RS POST ───>│ │
│ │<── 3. HTTP 202 ───────│ │
│<── 4. C-STORE-RSP ─────│ │── 4. Store raw bytes ────>│
│ │ │ │
│ │ │ [Study debounce done] │
│ │ │── 5. Run sortSlices() ───>│
│ │ │── 6. Build 3D volume ────>│
-
Acknowledge immediately: Your webhook stores the raw instance to cloud object storage and returns
HTTP 202 Accepted. -
Track series instances: Record the
Series Instance UID (0020,000E)andSOP Instance UID (0008,0018)in your application records. -
Debounce completion: Wait for an idle timeout, such as 60 seconds, after the last slice arrives. Our guide on handling large DICOM studies details this pattern.
-
Sort and reconstruct: Pull the spatial metadata for all instances in the series. Run the projection algorithm to order the instances. Then pass the sorted array to your volume generator or AI inference pipeline.
Next steps for building your 3D volume pipeline
The DICOM standard provides all the geometric data you need to organize medical images cleanly. You do not need to guess scanner behavior from vendor-specific tags.
To start testing your pipeline today:
-
Download a sample CT series from a public research repository like The Cancer Imaging Archive (TCIA).
-
Extract tags
(0020,0032)and(0020,0037)from 10 consecutive files using DCMTK’sdcmdumpor a tool likepydicom. -
Implement the
sortSlicesvector function above and verify that the calculated normal distances match the scanner’s expected slice spacing. -
Review our overview of DICOM instances, series, and studies to structure your data models before connecting your first hospital scanner.
Dicomly builds infrastructure for healthcare software teams that receive DICOM studies from hospitals. Why we built Dicomly →