Vision Systems & Engineering
DICOM
The standard for storing and exchanging medical images, from its information model, data elements, value representations and transfer syntaxes to Part 10 files, UIDs, encapsulated pixel data and network services, with a section on the NIfTI-1 and NIfTI-2 headers, checked by writing a synthetic CT series byte by byte and converting it to NIfTI.
intermediate
DICOM (Digital Imaging and Communications in Medicine) is the standard in which scanners, archives and viewers store and exchange medical images. A DICOM object is not a picture with a header in front. It is a list of tagged, typed attributes describing the patient, the study, the series and the image, one of which happens to hold the pixels. The standard also defines how such objects are written to files and how devices send and query them over a network. It is published in numbered Parts (PS3.3, PS3.5, PS3.10 and others) by the National Electrical Manufacturers Association (NEMA), whose notices describe its development as a voluntary consensus process that NEMA administers (NEMA, 2026, PS3.5, Notice and Disclaimer). This article reads the 2026d edition, as of November 2026.
Vision code meets DICOM at the point where images leave the hospital system and become arrays. Several published articles already cover parts of that path. Medical Image Preprocessing covers the geometry (Image Position and Orientation, Pixel Spacing, the patient coordinate system, slice ordering) and the Modality LUT rescale. Hounsfield Units covers the CT rescale to HU and the display window. Medical Computer Vision covers DICOM’s history, PACS integration and the de-identification profiles. Whole-Slide Imaging covers tiled pathology images. This article covers the layer underneath: how attributes are encoded as bytes, what a Part 10 file contains, what a transfer syntax changes, how UIDs are built, and how the research format NIfTI stores a volume. The example writes and reads a synthetic CT series byte by byte with NumPy and Python’s struct, and converts it to NIfTI-1.
Purpose
A medical image is useless without its context. A CT slice needs its position in the patient, the spacing of its pixels and the rescale that turns stored integers into Hounsfield units. It needs to know which series and study it belongs to, and which device made it. DICOM’s answer is to make that context part of the object. Every object is a Data Set, a set of Data Elements, each the encoded value of one attribute of a real-world information object (PS3.5, Chapter 7). Which attributes an image of a given kind must carry is defined by an Information Object Definition (IOD) in PS3.3.
The same encoding serves files and networks. PS3.10 places one Data Set, representing one instance, in each file after a small header (PS3.10, Chapter 7). PS3.7’s message services carry the same Data Sets between devices (PS3.7, Chapter 9). PS3.18 defines web services over HTTP for the same objects (PS3.18, Chapter 1).
Core Capabilities
The information model
PS3.3 describes a model of the real world from which the IODs are derived. It notes that a composite IOD combines attributes of several real-world objects, among them the series, the equipment, the frame of reference, the study and the patient (PS3.3, Chapter 7). The CT Image IOD shows the structure. Its module table groups modules by information entity (IE): Patient, Study, Series, Frame of Reference, Equipment, Acquisition and Image (PS3.3, Table A.3-1). Each module is mandatory (M), conditional (C) or user-optional (U). For a CT image the mandatory modules include Patient, General Study, General Series, Frame of Reference, General Equipment, General Acquisition, General Image, Image Plane, Image Pixel, CT Image and SOP Common.
An IOD is used in SOP Classes, which pair it with a service. The Segmentation IOD, for example, is used in two SOP Classes of the Storage Service Class in PS3.4: one for binary and fractional segmentations and one for label maps (PS3.3, A.51.1). Each SOP Class has a UID in the registry of PS3.6 Annex A, such as 1.2.840.10008.5.1.4.1.1.2 for CT Image Storage. Each object written is a SOP Instance with its own SOP Instance UID, inside a series and a study identified by their own UIDs.
Vision outputs have their own objects. The Segmentation IOD specifies a multi-frame image that classifies the pixels of referenced images as binary, fractional or label-map segmentations. When the referenced images have a Frame of Reference, the segmentation shares it but need not share their sampling or extent. It does not include the referenced images’ full acquisition parameters, so software may need the referenced images as well (PS3.3, A.51.1). The UID registry also lists storage SOP Classes for RT Structure Set Storage and Parametric Map Storage (PS3.6, Annex A).
Data elements and value representations
Each Data Element has a tag, an ordered pair of 16-bit unsigned integers, the group number followed by the element number. It has an optional two-character value representation (VR), a value length, and a value field of an even number of bytes (PS3.5, §7.1.1). Elements in a Data Set are ordered by increasing tag, and each occurs at most once (§7.1). Standard elements have even group numbers other than 0000, 0002, 0004 and 0006. Private elements have odd group numbers, with a few excluded (§7.1).
The VR is the element’s data type (PS3.5, §6.2). The ones a CT slice uses are:
- UI (UID): digits and dots, at most 64 bytes.
- CS (code string): upper case, digits, space and underscore, at most 16 bytes.
- DS (decimal string): a fixed or floating-point number of at most 16 bytes.
- IS (integer string): at most 12 bytes.
- LO (long string) and PN (person name): PN has five components separated by “^”.
- US and UL: unsigned 16- and 32-bit binary integers.
- OB and OW: byte and 16-bit word streams; Pixel Data is one of these.
The data dictionary in PS3.6 gives each standard element its VR and value multiplicity (VM). For example, Image Position (Patient) (0020,0032) is DS with VM 3, and Pixel Data (7FE0,0010) is “OB or OW”. Multiple string values are separated by a backslash, and only the whole value field must have even length (§6.4).
Even length is reached by padding. Character strings get a trailing space (20H). UI values get a single trailing NULL (00H), and so do OB values (§6.2).
Explicit and implicit VR
A Data Element has one of three byte layouts (PS3.5, §7.1.2–7.1.3):
| Layout | Tag | VR | Length | Header bytes |
|---|---|---|---|---|
| Explicit VR, VRs AE, AS, AT, CS, DA, DS, DT, FL, FD, IS, LO, LT, PN, SH, SL, SS, ST, TM, UI, UL, US | 4 | 2 | 2 (16-bit) | 8 |
| Explicit VR, all other VRs (OB, OW, SQ, UN, UT, …) | 4 | 2 + 2 reserved (0000H) | 4 (32-bit) | 12 |
| Implicit VR | 4 | — | 4 (32-bit) | 8 |
Implicit and explicit elements may not be mixed in one Data Set (§7.1). In Implicit VR the reader has to take each element’s VR from the data dictionary. The 16-bit length of the short layout also limits what it can hold. PS3.5 notes, for example, that multi-valued DS elements may not be properly encoded in an Explicit VR transfer syntax if their length exceeds 65534 bytes (§6.2). Any VR defined in the future will use the 12-byte layout with a 32-bit length (§6.2).
A value length may also be undefined (FFFFFFFFH) for SQ and UN, and for OB depending on the transfer syntax (§7.1.1). A sequence (VR SQ) holds zero or more items, each a nested Data Set encoded under the Data Element Tag (FFFE,E000) (§7.5, §7.5.1). An item has either an explicit length or an undefined length closed by an Item Delimitation element (FFFE,E00D). These item and delimitation elements are always encoded as Implicit VR, whatever the transfer syntax (§7.5). Since a delimiter’s bytes may occur inside a value, a decoder must walk the items rather than scan for the delimiter (§7.1.2). Group Length elements (gggg,0000) are retired for ordinary groups. Readers must still be able to parse them, and PS3.5 recommends removing them during storage or transfer. Groups 0000 and 0002 have their own requirements (§7.2).
Part 10 files
A DICOM file holds one SOP Instance (PS3.10, Chapter 7). It begins with a 128-byte File Preamble, which is all 00H if unused. Readers may not use the preamble’s content to decide whether a file is DICOM. Next come the four bytes “DICM”, which are not a data element. Then comes the File Meta Information, group 0002, whose Type 1 elements are:
- (0002,0000) File Meta Information Group Length (UL): the number of bytes after this element up to the end of group 0002;
- (0002,0001) File Meta Information Version (OB): the two bytes 00H 01H;
- (0002,0002) Media Storage SOP Class UID and (0002,0003) Media Storage SOP Instance UID;
- (0002,0010) Transfer Syntax UID, which identifies the encoding of the Data Set that follows and does not apply to the File Meta Information itself;
- (0002,0012) Implementation Class UID, which identifies the implementation that wrote the file.
Except for the preamble and prefix, the File Meta Information is always encoded in Explicit VR Little Endian (PS3.10, §7.1). A note under Transfer Syntax UID recommends “one of the DICOM Transfer Syntaxes supporting explicit Value Representation encoding”, to facilitate interpretation of File Meta Element Values. Group 0002 elements may not appear in data sets outside the file meta.
Transfer syntaxes and encapsulated pixel data
A transfer syntax fixes the explicit or implicit VR, the byte order and any compression of the pixel data (PS3.5, Annex A). Implicit VR Little Endian, UID 1.2.840.10008.1.2, is named DICOM’s default transfer syntax in the PS3.6 registry. Explicit VR Little Endian is 1.2.840.10008.1.2.1, and Explicit VR Big Endian (1.2.840.10008.1.2.2) is retired (PS3.6, Annex A; PS3.5, A.1 and A.2). In both little-endian syntaxes, Pixel Data with more than 8 bits allocated is OW, written uncompressed (in the standard’s term, Native Format) in little-endian byte order (A.1, A.2).
Compressed transfer syntaxes encapsulate the pixel data (A.4):
- Pixel Data is OB with undefined length, and the encoded stream is cut into fragments.
- Each fragment is an item (FFFE,E000) with an explicit even length of at least 2 bytes.
- The first item is the Basic Offset Table. It may be empty. If filled, it holds 32-bit offsets of each frame’s first fragment, measured from the first item after the table, so its first entry is always 0. It must be empty when an Extended Offset Table (7FE0,0001) is present.
- A Sequence Delimitation Item (FFFE,E0DD) ends the sequence.
The data set around the pixel data stays Explicit VR Little Endian. The registry names the encodings: JPEG Baseline and Extended, JPEG Lossless, JPEG-LS, JPEG 2000 and High-Throughput JPEG 2000, RLE Lossless, JPEG XL, and MPEG-2, H.264 and HEVC video. Image Compression covers JPEG and JPEG 2000 as codecs.
UIDs
A UID is a string of numeric components separated by dots: an organization’s root followed by a suffix it keeps unique (PS3.5, Chapter 9). The rules are:
- No component may start with 0 unless it is the single digit 0.
- An odd-length UID gets one trailing NULL.
- A UID may not exceed 64 characters, padding included (§9.1).
- The root 1.2.840.10008 is reserved for items the standard defines, such as transfer syntaxes. Implementations should not assume that a UID carries meaning, and should not parse UIDs to extract it (Chapter 9).
An implementation without a registered root can build a UID from a UUID: “2.25.” followed by the UUID’s 128 bits as a decimal integer, up to 39 digits (B.2). B.2 says this may suit dynamically created UIDs such as SOP Instance UIDs. It also says such a UID is “usually not appropriate” for UIDs fixed when software is designed, such as private SOP Class, Transfer Syntax or Implementation Class UIDs.
Network services and DICOMweb
PS3.7 defines the DIMSE-C services on composite SOP Instances (PS3.7, Chapter 9):
- C-STORE stores an instance on a peer.
- C-FIND matches a set of attributes against the instances a peer holds.
- C-GET and C-MOVE match and retrieve instances. Both trigger C-STORE sub-operations: C-GET on the same association, C-MOVE on a separate one.
- C-ECHO verifies end-to-end communication.
Each is a confirmed service. PS3.18 specifies web services over HTTP for managing and distributing DICOM objects. It uses the name DICOMweb for its REST services and leaves security to PS3.15 (PS3.18, Chapter 1).
Medical Computer Vision describes de-identification through the attribute confidentiality profiles of PS3.15, and Digital Pathology and Whole-Slide Imaging describe DICOM’s whole-slide images.
NIfTI
Research pipelines, especially in neuroimaging, often convert DICOM series to NIfTI. A NIfTI file holds one volume with a fixed-size binary header. Medical Image Preprocessing explains what its qform and sform transforms mean and how its RAS+ axes relate to DICOM’s LPS. This section describes the bytes, as nifti1.h and nifti2.h in nifti_clib v3.0.1 define them.
- Header.
struct nifti_1_headeris 348 bytes, withsizeof_hdr= 348, 4-byte ints and floats and 2-byte shorts. It is laid out over the ANALYZE 7.5 header, taking over most of that header’s unused or lesser-used fields. Among the offsets:dim(eight shorts) at byte 40 anddatatypeat 70;pixdim(eight floats) at 76 andvox_offset(a float) at 108;scl_slopeandscl_interat 112;qform_codeandsform_codeat 252 and 254;- the quaternion
quatern_b,quatern_c,quatern_dat 256 and the offsetsqoffset_x,qoffset_y,qoffset_zat 268; - the three sform rows
srow_x,srow_y,srow_zat 280.
- Magic. The last four bytes are “ni1\0” (data in a separate
.imgfile) or “n+1\0” (data in the same.niifile). A header without the magic is treated as ANALYZE 7.5. - Data offset. In a
.niifile the data start at(int)vox_offset, which is at least 352 and, for compatibility, a multiple of 16. - Extensions. The four bytes after the header are an extension flag. If the first byte is nonzero, extensions follow, each a multiple of 16 bytes and starting with two ints,
esizeandecode. Code 2 is registered for DICOM attribute data. - Byte order. It is not stored as a field. If
dim[0](the number of dimensions) is outside 1 to 7, the header must be byte-swapped. - Orientation. The qform stores a rotation as three quaternion parameters, with required to be non-negative. A factor , stored in
pixdim[0], flips the third axis for left-handed grids, andpixdim[0]= 0 is read as 1. Rotation Representations covers quaternions themselves.
NIfTI-2 widens the header to 540 bytes (nifti2.h):
dim,vox_offset,slice_startandslice_endbecome 64-bit integers.pixdim, the scaling, the quaternion and the sform rows become doubles.- The codes become 32-bit integers.
- The magic grows to 8 bytes and moves to just after
sizeof_hdr. - Unused ANALYZE fields are dropped.
- Byte order is now tested on
sizeof_hdr, which reads 348 or 540 in the native order and as a byte-swapped value otherwise.
Minimal Example
No DICOM toolkit is installed for this article. The example therefore writes and parses the bytes itself, following the standard’s encoding rules and nifti1.h. Its outcomes test this reproduction, not pydicom, GDCM, DCMTK, ITK or any other DICOM software.
Data. A synthetic phantom of ellipsoids in Hounsfield units, generated in code, fills 8 slices of 64 × 64 voxels:
- air at −1000 HU;
- a body at 40 HU;
- bone at 1000 HU;
- fat at −100 HU.
No patient data, downloaded DICOM or NIfTI file, or image of a person is used. The identifiers are obviously synthetic: PatientName “SYNTHETIC^PHANTOM”, Patient ID “SYNTH-0001”, and study, series and instance UIDs of the “2.25.” form built from seeded UUIDs. The script writes its files into an out folder in the working directory.
Encoding.
- Pixels. Stored values are HU + 1024 as unsigned 16-bit integers, with Rescale Intercept “-1024”, Rescale Slope “1” and Rescale Type “HU”. Bits Allocated is 16, Bits Stored 12 and High Bit 11, within the CT Image Module’s rules (C.8.2.1.1.4–6).
- Geometry.
- Pixel Spacing is “0.75\0.6”: 0.75 mm between rows, then 0.6 mm between columns.
- Slices are 2.5 mm apart along the normal, and the first slice’s position is (−120.3, −95.7, 40.25) mm.
- Two conditions share everything except orientation. The oblique condition uses the rotation about the patient axes. The axis-aligned condition uses the identity.
- The row and column direction cosines are the first two columns of the rotation, and the normal is its third.
- Elements. Each slice carries 26 data elements:
- the image type, the SOP Class and Instance UIDs, the modality, the patient’s name and ID;
- slice thickness, the study and series UIDs, the instance number;
- Image Position and Orientation, Slice Location, Pixel Spacing;
- the Image Pixel attributes;
- the rescale;
- Pixel Data (OW). These are the attributes the example needs, not a conforming CT Image instance. The attribute tables of the PS3.3 C.7.x modules and the SOP Common Module (C.12.1) were not read, so mandatory attributes such as a Frame of Reference UID are absent.
- Implementation Class UID. The file meta needs this UID. The example has no registered organization root, and 1.2.840.10008 is reserved for items the standard defines, so it uses a fixed “2.25.” UID made from a name-based UUID. B.2 says a UUID-derived UID is “usually not appropriate” for an Implementation Class UID. In our reading, that is acceptable for a synthetic example, and a real implementation would use a UID under its organization’s registered root (PS3.5, B.1).
- Two copies. Each slice is written twice, with the data set in Explicit VR Little Endian and in Implicit VR Little Endian. The file meta is Explicit VR in both. The files are written in a shuffled order.
Reading back. A parser written separately from the writer, with its own VR tables and its own small tag-to-VR dictionary for implicit data sets, reads every file. It chooses the data set encoding from (0002,0010). The slices are then sorted by projecting each Image Position onto the cross product of the row and column cosines, as Medical Image Preprocessing derives.
NIfTI-1 conversion. The volume is written as one .nii:
DT_UINT16, withscl_slope1 andscl_inter−1024;vox_offset352 and magic “n+1\0”;qform_code=sform_code= 1 (scanner anatomical);- both a qform and an sform. The sform is the voxel-to-RAS affine, built from the parsed DICOM geometry after negating x and y as
nifti1.hprescribes, and rounded to float32. The qform is the quaternion of that affine’s rotation.
The matrix-to-quaternion and quaternion-to-matrix conversions are ported from nifti_mat44_to_quatern and nifti_quatern_to_mat44 in nifti1_io.c (nifti_clib commit 96b9954, public domain). nifti1.h itself refers the case , a 180° rotation, to that function, and the axis-aligned condition is exactly that case: DICOM’s identity orientation becomes the NIfTI rotation diag(−1, −1, 1). The port makes four simplifications. It computes in float64. It omits the polar decomposition that nifti1_io.c applies to make a non-orthogonal input orthogonal. It omits the float32 casts of the normalized matrix, and the guards against zero column lengths and non-positive spacings. The rotation’s columns are orthonormal here by construction. The header is read back by fixed byte offsets.
Measures.
- M1: mismatches in stored values and in HU, for both DICOM copies and the NIfTI file.
- M2: (a) each Group Length against the bytes after it; (b) the number of odd value lengths; (c) element header sizes per encoding; (d) the explicit-minus-implicit size differences, with the data set’s difference predicted from the (VR, length) pairs by §7.1.
- M3: what the explicit-VR parser reports when handed the implicit data set without consulting (0002,0010).
- M4: the recovered slice order.
- M5: the maximum position error over all 32,768 voxels, in mm, of the qform (Method 2) and of the sform (Method 3). The reference is the float64 position from the parsed DICOM strings (Equation C.7.6.2.1-1, as Medical Image Preprocessing gives it), after the sign flip. Header fields are read as float32 and evaluated in float64.
M5 is also expressed as a ratio to . Here is the unit roundoff of float32. is the largest, over voxels, of the Euclidean norm of the per-coordinate sums , where are the entries of the 3 × 4 voxel-to-RAS affine and .
Hypotheses. These come from the batch plan and were written before any script ran.
- H1: M1 is exact.
- H2: derived from §7.1 and PS3.10 §7.1.
- Elements whose VR has a 16-bit length take 8 header bytes in both encodings. OB and OW take 12 in Explicit VR and 8 in Implicit VR.
- The data set has one such element, Pixel Data, so the explicit data set is 4 bytes longer.
- The file meta differs only in the Transfer Syntax UID’s value: “1.2.840.10008.1.2.1” padded to 20 bytes against “1.2.840.10008.1.2” padded to 18. So the group and its Group Length are 2 bytes longer.
- H3: the explicit parser takes the two low bytes of the first element’s 4-byte length as a VR and fails; the failure is printed.
- H4: M4 recovers the true order.
- H5: both M5 errors are at float32 level, and each is smaller for the axis-aligned orientation than for the oblique one. Whether the qform error exceeds the sform error is left open, because the sources do not settle it. ITK’s NIfTI reader, for instance, comments that the conversion to the qform is lossy and can occasionally be a problem where DICOM’s physical space must be matched very precisely (
itkNiftiImageIO.cxx, ITK v5.4.7).
Checks.
- C-meta: the version bytes and the six Type 1 file meta elements are present in every file.
- C-pad: every text value in the files equals its source string padded by the §6.2 rule.
- C-UID: the §9.1 rules hold for every UID.
- C-ds: every DS value is at most 16 characters.
- C-nifti:
sizeof_hdris 348,vox_offsetis at least 352 and a multiple of 16,dim[0]is in 1..7, and the magic is “n+1\0”. - C-sform: the sform error is at most . This bound follows from rounding each of the 12 affine entries to float32 with relative error at most .
- C-data: the phantom’s voxel counts are printed, and the stored values fit in 12 bits.
Bars set after a planning script. Before the pilot, a planning script computed the reachable M5 values on the same geometry, with SciPy’s quaternion conversion in place of the port. It printed the values from which two bars were first written:
- C-sform’s ratio of at most 1;
- H5’s “float32 level”, defined as a ratio of at most 10 for both forms.
That script printed equal sform errors (4.316e-06 mm) for the two orientations, so the sform half of H5 was expected to fail before the pilot ran. Nothing in the set-up was changed because of it.
Departures from the batch plan. All were approved before the first run:
- Rescale Type is written.
nifti1_io.cwas added as a source, ported with the simplifications above.- M1 is extended to the NIfTI file.
- Several checks were added: C-data, C-ds, C-sform and the magic bytes.
- M5 prints and the ratio, and is evaluated in float64.
- M2 prints a header-size histogram.
- Both parts run in both orientations.
- The file shuffle has its own seed.
- The Implementation Class UID is the fixed name-based UID described above.
Runs.
- Pilot and first run. The pilot and the first run used the same script and the same seeds. The only change between them, approved before the first run, was the print format of the first line, which now shows plain integers instead of NumPy scalar reprs. The pilot and first-run outcomes agree.
- Comment change. After the first run, the comment crediting
nifti1_io.cwas extended with the commit and the public-domain statement. This was a comment-only change at the editor’s request, and the output is unchanged. - Reproducibility. Two runs printed identical output. The script runs in well under a second with NumPy 2.3.5 and the standard library.
import os
for v in ("OPENBLAS_NUM_THREADS", "OMP_NUM_THREADS", "MKL_NUM_THREADS", "VECLIB_MAXIMUM_THREADS"):
os.environ[v] = "1"
import struct, uuid
from collections import Counter
import numpy as np
EXPLICIT, IMPLICIT = "1.2.840.10008.1.2.1", "1.2.840.10008.1.2" # PS3.5 A.2 and A.1
CT_STORAGE = "1.2.840.10008.5.1.4.1.1.2" # PS3.6 Annex A
# Fixed name-based UID for this writer (no registered root; PS3.5 B.2 calls UUID-derived
# Implementation Class UIDs "usually not appropriate").
IMPL_UID = "2.25." + str(uuid.uuid5(uuid.NAMESPACE_OID, "cvo-dicom-example-writer").int)
# ---- synthetic CT phantom in HU (voxel indices i column, j row, k slice) ----
n_i = n_j = 64; n_k = 8
k, j, i = np.meshgrid(np.arange(n_k), np.arange(n_j), np.arange(n_i), indexing="ij")
hu = np.full((n_k, n_j, n_i), -1000, np.int32)
for c, a, value in [((31.5, 31.5, 3.5), (28, 22, 5), 40), # body
((20, 31.5, 3.5), (6, 6, 3), 1000), # bone
((42, 28, 3.5), (8, 5, 2.5), -100)]: # fat
hu[((i - c[0]) / a[0]) ** 2 + ((j - c[1]) / a[1]) ** 2 + ((k - c[2]) / a[2]) ** 2 <= 1] = value
sv = (hu + 1024).astype(np.uint16) # stored values; Rescale Intercept -1024, Slope 1
print("data:", {int(v): int(c) for v, c in zip(*np.unique(hu, return_counts=True))}, "| stored range",
sv.min(), "to", sv.max(), "| within 12 bits:", bool(sv.max() < 4096))
# ---- writer (PS3.5 6.2, 6.4, 7.1; PS3.10 7.1) ----
SHORT_LEN = set("AE AS AT CS DA DS DT FL FD IS LO LT PN SH SL SS ST TM UI UL US".split())
def encode(vr, value):
if vr == "US": return struct.pack("<H", value)
if vr == "UL": return struct.pack("<I", value)
if vr in ("OB", "OW"): return value + b"\x00" * (len(value) % 2)
s = ("\\".join(value) if isinstance(value, list) else value).encode("ascii")
return s + (b"\x00" if vr == "UI" else b" ") * (len(s) % 2)
def element(tag, vr, value, explicit):
val = encode(vr, value)
if not explicit: return struct.pack("<HHI", *tag, len(val)) + val
if vr in SHORT_LEN: return struct.pack("<HH2sH", *tag, vr.encode(), len(val)) + val
return struct.pack("<HH2sHI", *tag, vr.encode(), 0, len(val)) + val
def write_part10(path, meta, dataset, ts):
group = b"".join(element(t, vr, v, True) for t, vr, v in meta) # file meta: always explicit
data = b"".join(element(t, vr, v, ts == EXPLICIT) for t, vr, v in dataset)
with open(path, "wb") as f:
f.write(b"\x00" * 128 + b"DICM" + element((2, 0), "UL", len(group), True) + group + data)
def ds(v): # Decimal String, at most 16 characters
return format(0.0 if abs(v) < 1e-12 else float(v), ".10g")
# ---- parser, written separately: its own tables ----
LEN16 = {"AE", "AS", "AT", "CS", "DA", "DS", "DT", "FL", "FD", "IS", "LO", "LT", "PN",
"SH", "SL", "SS", "ST", "TM", "UI", "UL", "US"}
KNOWN = LEN16 | {"OB", "OD", "OF", "OL", "OV", "OW", "SQ", "SV", "UC", "UN", "UR", "UT", "UV"}
DICT = dict(zip([(8, 8), (8, 0x16), (8, 0x18), (8, 0x60), (0x10, 0x10), (0x10, 0x20), (0x18, 0x50),
(0x20, 0xD), (0x20, 0xE), (0x20, 0x13), (0x20, 0x32), (0x20, 0x37), (0x20, 0x1041),
(0x28, 2), (0x28, 4), (0x28, 0x10), (0x28, 0x11), (0x28, 0x30), (0x28, 0x100),
(0x28, 0x101), (0x28, 0x102), (0x28, 0x103), (0x28, 0x1052), (0x28, 0x1053),
(0x28, 0x1054), (0x7FE0, 0x10)],
"CS UI UI CS PN LO DS UI UI IS DS DS DS US CS US US DS US US US US DS DS LO OW".split()))
class BadVR(ValueError): pass
def parse_dataset(buf, pos, end, explicit, group=None):
out = []
while pos < end:
g, e = struct.unpack_from("<HH", buf, pos)
if group is not None and g != group: break
if explicit:
raw = buf[pos + 4:pos + 6]
if not (raw.isalpha() and raw.isupper() and raw.decode() in KNOWN):
raise BadVR(raw, f"({g:04X},{e:04X}) at byte {pos}: VR field {raw!r} is not a VR")
vr = raw.decode()
h = 8 if vr in LEN16 else 12
n = struct.unpack_from("<H" if h == 8 else "<I", buf, pos + h - (2 if h == 8 else 4))[0]
else:
vr, h, n = DICT[(g, e)], 8, struct.unpack_from("<I", buf, pos + 4)[0]
out.append({"tag": (g, e), "vr": vr, "raw": buf[pos + h:pos + h + n], "hdr": h})
pos += h + n
return out, pos
def parse_part10(path):
buf = open(path, "rb").read()
assert buf[128:132] == b"DICM"
meta, start = parse_dataset(buf, 132, len(buf), True, group=2)
ts = meta[[m["tag"] for m in meta].index((2, 0x10))]["raw"].rstrip(b"\x00").decode()
data, _ = parse_dataset(buf, start, len(buf), ts == EXPLICIT)
return buf, meta, start, ts, data
text = lambda el: el["raw"].decode("ascii").rstrip("\x00 ")
def value(els, tag):
el = next(x for x in els if x["tag"] == tag)
if el["vr"] == "US": return struct.unpack("<H", el["raw"])[0]
if el["vr"] == "OW": return np.frombuffer(el["raw"], "<u2")
return [float(t) for t in text(el).split("\\")] if el["vr"] in ("DS", "IS") else text(el)
def predict_sizes(pairs): # (VR, value length) -> bytes, PS3.5 7.1.2-7.1.3
exp = sum((8 if vr in SHORT_LEN else 12) + n for vr, n in pairs)
return exp, sum(8 + n for vr, n in pairs)
# ---- NIfTI-1 (nifti1.h, nifti_clib v3.0.1) ----
HDR = "<i10s18sihbb8h3f4h8f3fhbb4f2i80s24s2h6f12f16s4s"
assert struct.calcsize(HDR) == 348
# nifti_mat44_to_quatern and nifti_quatern_to_mat44 ported from nifti_clib v3.0.1
# (commit 96b9954), niftilib/nifti1_io.c, whose header reads "This code is released
# to the public domain." Modified: float64 throughout; polar decomposition, float
# casts and the guards for zero column lengths and non-positive spacings omitted
# (the columns here are orthonormal by construction).
def mat_to_quatern(M):
R = M[:, :3] / np.linalg.norm(M[:, :3], axis=0)
qfac = 1.0 if np.linalg.det(R) > 0 else -1.0
if qfac < 0: R[:, 2] = -R[:, 2]
(r11, r12, r13), (r21, r22, r23), (r31, r32, r33) = R
a = r11 + r22 + r33 + 1.0
if a > 0.5:
a = 0.5 * np.sqrt(a); b, c, d = 0.25 * (r32 - r23) / a, 0.25 * (r13 - r31) / a, 0.25 * (r21 - r12) / a
else:
xd, yd, zd = 1 + r11 - (r22 + r33), 1 + r22 - (r11 + r33), 1 + r33 - (r11 + r22)
if xd > 1.0:
b = 0.5 * np.sqrt(xd); c, d, a = 0.25 * (r12 + r21) / b, 0.25 * (r13 + r31) / b, 0.25 * (r32 - r23) / b
elif yd > 1.0:
c = 0.5 * np.sqrt(yd); b, d, a = 0.25 * (r12 + r21) / c, 0.25 * (r23 + r32) / c, 0.25 * (r13 - r31) / c
else:
d = 0.5 * np.sqrt(zd); b, c, a = 0.25 * (r13 + r31) / d, 0.25 * (r23 + r32) / d, 0.25 * (r21 - r12) / d
if a < 0: b, c, d = -b, -c, -d
return (b, c, d), qfac
def quatern_to_rot(b, c, d):
b, c, d = float(b), float(c), float(d)
a = 1.0 - (b * b + c * c + d * d)
if a < 1e-7:
s = 1.0 / np.sqrt(b * b + c * c + d * d); b, c, d, a = b * s, c * s, d * s, 0.0
else:
a = np.sqrt(a)
return np.array([[a*a + b*b - c*c - d*d, 2*(b*c - a*d), 2*(b*d + a*c)],
[2*(b*c + a*d), a*a + c*c - b*b - d*d, 2*(c*d - a*b)],
[2*(b*d - a*c), 2*(c*d + a*b), a*a + d*d - c*c - b*b]])
def write_nifti1(path, vol, A): # A: 3x4 voxel-to-RAS affine, float64
(b, c, d), qfac = mat_to_quatern(A)
pix = np.linalg.norm(A[:, :3], axis=0)
hdr = struct.pack(HDR, 348, b"", b"", 0, 0, 0, 0, 3, *vol.shape[::-1], 1, 1, 1, 1, 0, 0, 0,
0, 512, 16, 0, qfac, *pix, 0, 0, 0, 0, 352.0, 1.0, -1024.0, 0, 0, 2,
0, 0, 0, 0, 0, 0, b"SYNTHETIC PHANTOM", b"", 1, 1, b, c, d, *A[:, 3],
*A.ravel(), b"", b"n+1\x00")
with open(path, "wb") as f:
f.write(hdr + b"\x00" * 4 + vol.astype("<u2").tobytes())
def read_nifti1(path): # by byte offsets of struct nifti_1_header
b = open(path, "rb").read()
f = lambda fmt, off: struct.unpack_from("<" + fmt, b, off)
h = {"sizeof_hdr": f("i", 0)[0], "dim": f("8h", 40), "pixdim": f("8f", 76),
"vox_offset": f("f", 108)[0], "scl": f("2f", 112), "quat": f("3f", 256),
"qoffset": np.array(f("3f", 268)), "srow": np.array(f("12f", 280)).reshape(3, 4),
"magic": b[344:348]}
assert 1 <= h["dim"][0] <= 7, "dim[0] outside 1..7: header needs byte swapping (nifti1.h)"
n = h["dim"][1:4]
h["vox"] = np.frombuffer(b, "<u2", n[0] * n[1] * n[2], int(h["vox_offset"])).reshape(n[::-1])
return h
# ---- run both orientations ----
def rot(axis, deg):
t = np.radians(deg); c, s = np.cos(t), np.sin(t)
return {"x": np.array([[1, 0, 0], [0, c, -s], [0, s, c]]),
"y": np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]]),
"z": np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]])}[axis]
rng = np.random.default_rng(47)
new_uid = lambda: "2.25." + str(uuid.UUID(bytes=rng.bytes(16), version=4).int)
P0, d_row, d_col, step = np.array([-120.3, -95.7, 40.25]), 0.75, 0.6, 2.5
u = 2.0 ** -24
F = np.diag([-1.0, -1.0, 1.0]) # LPS -> RAS (nifti1.h)
results = {}
for cond, R in [("oblique", rot("z", 20) @ rot("x", 15) @ rot("y", -10)), ("axis-aligned", np.eye(3))]:
print(f"== {cond}")
out = os.path.join("out", cond); os.makedirs(out, exist_ok=True)
study, series = new_uid(), new_uid()
order = np.random.default_rng(470).permutation(n_k) # shuffled file order
src, uids, dslen = {}, [study, series, IMPL_UID, CT_STORAGE], []
for pos_in_dir, kk in enumerate(order):
sop = new_uid(); uids.append(sop)
ipp = [ds(x) for x in P0 + kk * step * R[:, 2]]
iop = [ds(x) for x in np.concatenate([R[:, 0], R[:, 1]])]
loc = ds(float((P0 + kk * step * R[:, 2]) @ R[:, 2]))
dataset = [((8, 8), "CS", ["ORIGINAL", "PRIMARY", "AXIAL"]), ((8, 0x16), "UI", CT_STORAGE),
((8, 0x18), "UI", sop), ((8, 0x60), "CS", "CT"), ((0x10, 0x10), "PN", "SYNTHETIC^PHANTOM"),
((0x10, 0x20), "LO", "SYNTH-0001"), ((0x18, 0x50), "DS", "2.5"), ((0x20, 0xD), "UI", study),
((0x20, 0xE), "UI", series), ((0x20, 0x13), "IS", str(kk + 1)), ((0x20, 0x32), "DS", ipp),
((0x20, 0x37), "DS", iop), ((0x20, 0x1041), "DS", loc), ((0x28, 2), "US", 1),
((0x28, 4), "CS", "MONOCHROME2"), ((0x28, 0x10), "US", n_j), ((0x28, 0x11), "US", n_i),
((0x28, 0x30), "DS", [ds(d_row), ds(d_col)]), ((0x28, 0x100), "US", 16),
((0x28, 0x101), "US", 12), ((0x28, 0x102), "US", 11), ((0x28, 0x103), "US", 0),
((0x28, 0x1052), "DS", "-1024"), ((0x28, 0x1053), "DS", "1"), ((0x28, 0x1054), "LO", "HU"),
((0x7FE0, 0x10), "OW", sv[kk].astype("<u2").tobytes())]
for ts, tag in [(EXPLICIT, "exp"), (IMPLICIT, "imp")]:
meta = [((2, 1), "OB", b"\x00\x01"), ((2, 2), "UI", CT_STORAGE), ((2, 3), "UI", sop),
((2, 0x10), "UI", ts), ((2, 0x12), "UI", IMPL_UID)]
write_part10(os.path.join(out, f"{tag}_{pos_in_dir:02d}.dcm"), meta, dataset, ts)
src[(tag, pos_in_dir)] = meta + dataset
dslen += [len(s) for _, vr, v in dataset if vr == "DS" for s in (v if isinstance(v, list) else [v])]
if pos_in_dir == 0: first_dataset = dataset
# read everything back
files = {tag: [parse_part10(os.path.join(out, f"{tag}_{p:02d}.dcm")) for p in range(n_k)] for tag in ("exp", "imp")}
m1, gl_ok, odd, version_ok, type1_ok, n_text, pad_bad = Counter(), 0, 0, 0, 0, 0, 0
for tag, parsed in files.items():
for p, ((buf, meta, start, ts, data), kk) in enumerate(zip(parsed, order)):
m1["stored " + tag] += int(np.sum(value(data, (0x7FE0, 0x10)) != sv[kk].ravel()))
hu_back = value(data, (0x28, 0x1053))[0] * value(data, (0x7FE0, 0x10)) + value(data, (0x28, 0x1052))[0]
m1["HU " + tag] += int(np.sum(hu_back != hu[kk].ravel()))
gl_ok += struct.unpack("<I", meta[0]["raw"])[0] == start - 144
odd += sum(len(el["raw"]) % 2 for el in meta + data)
version_ok += next(el["raw"] for el in meta if el["tag"] == (2, 1)) == b"\x00\x01"
type1_ok += {(2, 0), (2, 1), (2, 2), (2, 3), (2, 0x10), (2, 0x12)} <= {el["tag"] for el in meta}
in_file = {el["tag"]: el["raw"] for el in meta + data}
for t, vr, v in src[(tag, p)]: # C-pad: the rule applied to the source string
if vr in ("US", "UL", "OB", "OW"): continue
s = ("\\".join(v) if isinstance(v, list) else v).encode("ascii")
n_text += 1
pad_bad += in_file[t] != s + ((b"\x00" if vr == "UI" else b" ") if len(s) % 2 else b"")
bad_uid = sum(len(x) + len(x) % 2 > 64 or not all(p.isdigit() and (p == "0" or p[0] != "0")
for p in x.split(".")) for x in uids)
print(f"C-meta version 00 01 in {version_ok}/16 files; six Type 1 elements in {type1_ok}/16")
print(f"C-pad {n_text} text values, {pad_bad} violations | C-UID {len(uids)} UIDs, longest "
f"{max(len(x) for x in uids)}, {bad_uid} violations | C-ds longest DS {max(dslen)} characters")
print("M1 ", dict(m1))
(be, me, se, _, de), (bi, mi, si, _, di) = files["exp"][0], files["imp"][0]
print(f"M2 (a) group length equals bytes after it in {gl_ok}/16 files (first files: explicit "
f"{struct.unpack('<I', me[0]['raw'])[0]} = {se - 144}, implicit {struct.unpack('<I', mi[0]['raw'])[0]} "
f"= {si - 144}); (b) odd value lengths: {odd}")
print(" (c) header bytes, explicit meta", dict(Counter(e["hdr"] for e in me)), "data",
dict(Counter(e["hdr"] for e in de)), "| implicit meta", dict(Counter(e["hdr"] for e in mi)),
"data", dict(Counter(e["hdr"] for e in di)))
meta_e, meta_i, data_e, data_i = se - 132, si - 132, len(be) - se, len(bi) - si
pe, pi = predict_sizes([(vr, len(encode(vr, v))) for _, vr, v in first_dataset])
print(f" (d) file meta {meta_e} vs {meta_i} bytes (diff {meta_e - meta_i}); data set {data_e} vs "
f"{data_i} (diff {data_e - data_i}, predicted {pe - pi}); files {len(be)} vs {len(bi)} "
f"(diff {len(be) - len(bi)})")
try:
parse_dataset(bi, si, len(bi), explicit=True)
print("M3 no error")
except BadVR as err:
low = struct.unpack_from("<I", bi, si + 4)[0].to_bytes(4, "little")[:2]
print(f"M3 {err.args[1]}; first length {struct.unpack_from('<I', bi, si + 4)[0]}, "
f"its two low bytes {low!r}; equal: {err.args[0] == low}")
# assemble: sort by projection of Image Position on the slice normal
slices = [(value(d, (0x20, 0x32)), value(d, (0x20, 0x37)), value(d, (0x20, 0x13))[0], value(d, (0x7FE0, 0x10)))
for _, _, _, _, d in files["exp"]]
X, Y = np.array(slices[0][1][:3]), np.array(slices[0][1][3:])
in_file_order = [int(s[2]) for s in slices]
slices.sort(key=lambda s: np.dot(s[0], np.cross(X, Y)))
print("M4 Instance Numbers in file order", in_file_order, "-> after sorting", [int(s[2]) for s in slices])
P = np.array([s[0] for s in slices])
vol = np.stack([s[3].reshape(n_j, n_i) for s in slices])
# NIfTI-1: affine from the DICOM geometry, x and y negated
A = F @ np.column_stack([d_col * X, d_row * Y, (P[-1] - P[0]) / (n_k - 1), P[0]])
write_nifti1(os.path.join(out, "volume.nii"), vol, A)
h = read_nifti1(os.path.join(out, "volume.nii"))
print(f"C-nifti sizeof_hdr {h['sizeof_hdr']}, vox_offset {h['vox_offset']} (multiple of 16: "
f"{h['vox_offset'] % 16 == 0}), dim[0] {h['dim'][0]}, magic {h['magic'].hex(' ')}, qfac {h['pixdim'][0]}")
m1n = (int(np.sum(h["vox"] != sv)), int(np.sum(h["scl"][0] * h["vox"] + h["scl"][1] != hu)))
print(f"M1 NIfTI stored mismatches {m1n[0]}, HU mismatches {m1n[1]}")
I, J, K = np.meshgrid(np.arange(n_i), np.arange(n_j), np.arange(n_k), indexing="ij")
ijk = np.stack([I.ravel(), J.ravel(), K.ravel()], 1).astype(np.float64)
truth = (P[ijk[:, 2].astype(int)] + ijk[:, :1] * d_col * X + ijk[:, 1:2] * d_row * Y) @ F.T
hom = np.column_stack([ijk, np.ones(len(ijk))])
S = np.max(np.linalg.norm(np.abs(hom[:, None, :] * A[None]).sum(2), axis=1))
pd = np.array(h["pixdim"][1:4], np.float64) * np.array([1, 1, h["pixdim"][0]])
qform = ijk * pd @ quatern_to_rot(*h["quat"]).T + h["qoffset"]
sform = hom @ h["srow"].T
e = {f: float(np.max(np.linalg.norm(x - truth, axis=1))) for f, x in (("qform", qform), ("sform", sform))}
results[cond] = e
print(f"M5 S = {S:.4g} mm; qform error {e['qform']:.4g} mm (ratio {e['qform'] / (u * S):.3g}), "
f"sform error {e['sform']:.4g} mm (ratio {e['sform'] / (u * S):.3g}); "
f"float32 level (ratio <= 10): {max(e.values()) / (u * S) <= 10}; sform ratio <= 1: {e['sform'] / (u * S) <= 1}")
for f in ("qform", "sform"):
dif = results["oblique"][f] - results["axis-aligned"][f]
print(f"H5 {f}: oblique - axis-aligned = {dif:.3e} mm; axis-aligned smaller: {dif > 0}")
data: {-1000: 20496, -100: 402, 40: 11422, 1000: 448} | stored range 24 to 2024 | within 12 bits: True
== oblique
C-meta version 00 01 in 16/16 files; six Type 1 elements in 16/16
C-pad 352 text values, 0 violations | C-UID 12 UIDs, longest 44, 0 violations | C-ds longest DS 13 characters
M1 {'stored exp': 0, 'HU exp': 0, 'stored imp': 0, 'HU imp': 0}
M2 (a) group length equals bytes after it in 16/16 files (first files: explicit 180 = 180, implicit 178 = 178); (b) odd value lengths: 0
(c) header bytes, explicit meta {8: 5, 12: 1} data {8: 25, 12: 1} | implicit meta {8: 5, 12: 1} data {8: 26}
(d) file meta 192 vs 190 bytes (diff 2); data set 8792 vs 8788 (diff 4, predicted 4); files 9116 vs 9110 (diff 6)
M3 (0008,0008) at byte 322: VR field b'\x16\x00' is not a VR; first length 22, its two low bytes b'\x16\x00'; equal: True
M4 Instance Numbers in file order [3, 2, 6, 1, 7, 4, 8, 5] -> after sorting [1, 2, 3, 4, 5, 6, 7, 8]
C-nifti sizeof_hdr 348, vox_offset 352.0 (multiple of 16: True), dim[0] 3, magic 6e 2b 31 00, qfac 1.0
M1 NIfTI stored mismatches 0, HU mismatches 0
M5 S = 244.1 mm; qform error 1.898e-05 mm (ratio 1.3), sform error 4.316e-06 mm (ratio 0.297); float32 level (ratio <= 10): True; sform ratio <= 1: True
== axis-aligned
C-meta version 00 01 in 16/16 files; six Type 1 elements in 16/16
C-pad 352 text values, 0 violations | C-UID 12 UIDs, longest 44, 0 violations | C-ds longest DS 6 characters
M1 {'stored exp': 0, 'HU exp': 0, 'stored imp': 0, 'HU imp': 0}
M2 (a) group length equals bytes after it in 16/16 files (first files: explicit 180 = 180, implicit 178 = 178); (b) odd value lengths: 0
(c) header bytes, explicit meta {8: 5, 12: 1} data {8: 25, 12: 1} | implicit meta {8: 5, 12: 1} data {8: 26}
(d) file meta 192 vs 190 bytes (diff 2); data set 8700 vs 8696 (diff 4, predicted 4); files 9024 vs 9018 (diff 6)
M3 (0008,0008) at byte 322: VR field b'\x16\x00' is not a VR; first length 22, its two low bytes b'\x16\x00'; equal: True
M4 Instance Numbers in file order [3, 2, 6, 1, 7, 4, 8, 5] -> after sorting [1, 2, 3, 4, 5, 6, 7, 8]
C-nifti sizeof_hdr 348, vox_offset 352.0 (multiple of 16: True), dim[0] 3, magic 6e 2b 31 00, qfac 1.0
M1 NIfTI stored mismatches 0, HU mismatches 0
M5 S = 220.8 mm; qform error 4.316e-06 mm (ratio 0.328), sform error 4.316e-06 mm (ratio 0.328); float32 level (ratio <= 10): True; sform ratio <= 1: True
H5 qform: oblique - axis-aligned = 1.466e-05 mm; axis-aligned smaller: True
H5 sform: oblique - axis-aligned = 0.000e+00 mm; axis-aligned smaller: False
Checks. All checks held:
- C-data: the phantom has its four HU values, and the stored values span 24 to 2024, within 12 bits.
- C-meta: the version bytes and the six Type 1 file meta elements are present in 16 of 16 files per orientation.
- C-pad: none of the 352 text values per orientation breaks the padding rule.
- C-UID: no UID breaks §9.1; the longest is 44 characters.
- C-ds: the longest Decimal String has 13 characters in the oblique condition and 6 in the axis-aligned one.
- C-nifti: the header reads back with
sizeof_hdr348,vox_offset352.0,dim[0]3 and magic 6e 2b 31 00. - C-sform: the sform ratio is at most 1 in both orientations.
Values and bytes. H1 held. The stored values and the HU computed from the parsed Rescale Slope and Intercept matched the phantom at every voxel, in both DICOM copies and in the NIfTI file through scl_slope and scl_inter.
H2 held in both orientations:
- In Explicit VR the data set had 25 elements with 8-byte headers and one, Pixel Data, with 12. In Implicit VR all 26 had 8-byte headers.
- The file meta had five 8-byte headers and one 12-byte header (the OB version element) in both copies, since group 0002 is explicit in both.
- The data sets differed by 4 bytes, the predicted value. The file meta groups differed by 2 bytes, and their Group Lengths, 180 and 178, matched the bytes that followed them.
- Each explicit file was 6 bytes longer than its implicit twin.
In our reading, the choice of encoding barely shows in the size of a 9 KB slice. What it changes is whether the file can be read without a data dictionary.
Misparse. H3 held. Handed the implicit data set as if it were explicit, the parser read the first element’s tag correctly. It then took bytes 16H 00H as the VR: the two low bytes of the 32-bit length 22, the length of “ORIGINAL\PRIMARY\AXIAL”. They are not letters, so the strict parser stopped at the first element. In our reading, a lenient reader that went on would take every later length from the wrong bytes. A reader avoids this by finding the Transfer Syntax UID first, in the file meta, which is always explicit.
Slice order. H4 held. Files read in shuffled order (Instance Numbers 3, 2, 6, 1, 7, 4, 8, 5) came out as 1 to 8 after sorting by position along the normal, in both orientations.
Positions.
- Float32 level: held for both forms in both orientations. The largest ratio was the oblique qform’s, 1.3, against the bar of 10.
- Ordering, qform: held. The qform error was 1.466e-05 mm larger for the oblique orientation than for the axis-aligned one.
- Ordering, sform: failed. The sform error was the same in both orientations, 4.316e-06 mm, a printed difference of 0.000e+00 mm. As stated above, the planning script had shown the equal values before the pilot.
- Open question. In the oblique condition the qform error was 1.898e-05 mm and the sform error 4.316e-06 mm. In the axis-aligned condition both were 4.316e-06 mm.
All four errors are below mm, against voxel spacings of 0.6 mm and more, and the ratios place them within a small factor of float32 rounding at these coordinates. In our reading, a pipeline that compares a converted volume’s affine with the DICOM geometry therefore needs a tolerance at least that large, and should not expect the two NIfTI transforms to agree bit for bit.
Ecosystem and Integrations
In our reading, code normally reads DICOM through a library rather than its own parser. pydicom is a pure-Python DICOM library under the MIT licence. Its source at commit 370ba29 (read November 2026) follows the rules the example uses:
filewriter.pywrites the 128-byte preamble and “DICM” when writing a standard file.- It sets the File Meta Information Group Length to the bytes written after it (
buffer.tell() - 12). - It pads UI values with a NULL and other strings with a space.
valuerep.pylists the same 21 VRs with 16-bit explicit lengths as PS3.5 §7.1.2.- Its data dictionaries are generated from the 2024d edition of the standard (
__dicom_version__).
One trap is in uid.py. Two comments there swap the names of the implicit and explicit little-endian syntaxes, while the constants below them (Implicit = 1.2.840.10008.1.2, Explicit = 1.2.840.10008.1.2.1) agree with PS3.6. pydicom was read, not run.
Other DICOM software includes the toolkits GDCM and DCMTK and the converter dcm2niix (not read).
Medical imaging toolkits read both formats. ITK has a DICOM image IO built on GDCM (itkGDCMImageIO) and a NIfTI image IO (itkNiftiImageIO). Its NIfTI reader at v5.4.7 has to choose between a file’s qform and sform. It prefers the sform under stated conditions:
- when the qform’s code is unknown and the sform’s is known and orthonormal;
- when the sform is labelled scanner-anatomical and orthonormal;
- when the two are numerically very similar.
Its comments say the sform can match DICOM’s directions more closely, since DICOM uses double precision (itkNiftiImageIO.cxx). SimpleITK, built on ITK, and NiBabel are the libraries Medical Image Preprocessing uses for its NIfTI example.
Inside the standard, a NIfTI-1 file can carry DICOM data: extension code 2 is registered for DICOM attribute tags and values (nifti1.h).
Alternatives
- NIfTI-1 and NIfTI-2 trade DICOM’s per-slice objects and rich metadata for one volume per file and a fixed binary header. Neuroimaging Analysis describes research pipelines converting scanners’ DICOM to NIfTI. NIfTI-1 itself grew out of ANALYZE 7.5, whose header layout it keeps.
- General image containers such as PNG and TIFF are covered in Image File Formats. They hold pixels but not the patient geometry or the rescale. Writing a CT slice to PNG drops both unless they are stored elsewhere.
- Microscopy formats such as OME-TIFF, and vendor whole-slide formats, are described in Bioimage Analysis and Whole-Slide Imaging. DICOM also has a whole-slide IOD.
Versions and Compatibility
Every page read for this article carries the edition label “DICOM PS3.x 2026d” and was read on 16 November 2026. The parts read are:
- PS3.5: §6.2, §6.4, §7.1–7.1.3, §7.2, §7.5, Chapter 9, A.1, A.2, A.4 and Annex B;
- PS3.10: Chapter 7;
- PS3.6: Chapters 6 and 7 and Annex A;
- PS3.3: Chapter 7, A.3, A.51, C.8.2.1 and C.11.1;
- PS3.7: Chapter 9;
- PS3.18: Chapter 1.
For retired UIDs, the registry gives the edition in which the item last appeared before it was retired. Explicit VR Big Endian, for example, is marked retired with “PS3.5 (2011)” (PS3.6, Annex A).
The NIfTI headers are those of nifti_clib v3.0.1 (commit 96b9954). nifti2.h is dated 2 January 2014 in its header. pydicom is described at commit 370ba29 of its main branch, and ITK at v5.4.7. Nothing is claimed about versions not read.
The example ran with Python’s standard library and NumPy 2.3.5.
Limitations
- Encoding is not conformance. Files can follow every encoding rule and still not be valid instances of an IOD. The example’s files lack mandatory module attributes, such as the Frame of Reference UID, because the PS3.3 C.7.x and C.12.1 tables were not read.
- The transfer syntax must be known. An implicit-VR data set cannot be decoded without a data dictionary, and an explicit-VR parser misreads it from the first element. Software that strips the file meta, or copies a data set without its transfer syntax, loses that information.
- Geometry lives per slice. A DICOM series has no volume header. The volume is assembled from each slice’s position and orientation, a step Medical Image Preprocessing covers in depth, and converters must infer the third axis from slice positions.
- NIfTI stores geometry in float32. NIfTI-1’s quaternion and sform rows are float32, so a converted volume’s positions differ from the DICOM values at float32 rounding level. NIfTI-1 also keeps much less metadata than the DICOM series it came from.
- UIDs need a root. A UID that is unique in practice needs a registered organization root or a UUID-derived one. The standard calls UUID-derived UIDs “usually not appropriate” for identifiers fixed at design time, such as Implementation Class UIDs.
- Identifying data travels with the image. Names, IDs, dates and UIDs are attributes like any other, which is why de-identification profiles exist; see Medical Computer Vision.
Related
- Hounsfield Units
The scale on which CT scanners report attenuation, fixed at 0 for water and −1000 for air, how scanners are calibrated to it, why tissue values still depend on the X-ray energy and the scanner, and how windowing turns it into a displayed image.
- Computed Tomography (CT)
An X-ray imaging method that measures attenuation along many lines through the body and reconstructs cross-sectional images from them, with each voxel calibrated in Hounsfield units.
- Medical Computer Vision
An overview of computer vision on medical images, from X-ray, CT, MRI, ultrasound and microscopy to the tasks of reconstruction, segmentation, registration, detection and slide-level prediction, and the problems that set the field apart from vision on photographs, namely scarce and disputed labels, privacy, shift between scanners and sites, evaluation against clinical reference standards, and regulation.
- Whole-Slide Imaging
How slide scanners digitize glass microscope slides into gigapixel images, from tile and line scanning, stitching and focus to resolution in micrometers per pixel, pyramidal vendor, DICOM and OME-TIFF files, compression, color calibration and image quality, and how vision code reads them.
- Neuroimaging Analysis
Computer vision on brain MRI; the structural pipeline of skull stripping, bias-field correction, registration to a template, tissue segmentation and cortical parcellation, lesion and tumor analysis, functional and diffusion MRI in outline, the main software suites, the large datasets and their access terms, and published results with their study designs.
- Rotation Representations
The ways a 3D rotation can be written down (rotation matrices, Euler angles, rotation vectors, unit quaternions, 6D vectors and the Lie algebra), how they convert into each other, and where each one fails.
References
- National Electrical Manufacturers Association (2026). DICOM PS3.5 2026d: Data Structures and Encoding. Section 6.2 (Value Representation), Section 6.4 (Value Multiplicity and Delimitation), Chapter 7 (The Data Set; Sections 7.1–7.1.3), Section 7.2 (Group Length), Section 7.5 (Nesting of Data Sets), Chapter 9 (Unique Identifiers), Annex A (Sections A.1, A.2 and A.4) and Annex B (Sections B.1 and B.2).
- National Electrical Manufacturers Association (2026). DICOM PS3.10 2026d: Media Storage and File Format for Media Interchange. Chapter 7 (DICOM File Format), Section 7.1 and Table 7.1-1.
- National Electrical Manufacturers Association (2026). DICOM PS3.6 2026d: Data Dictionary. Chapter 6 (Registry of DICOM Data Elements), Chapter 7 (Registry of DICOM File Meta Elements) and Annex A (Registry of DICOM Unique Identifiers).
- National Electrical Manufacturers Association (2026). DICOM PS3.3 2026d: Information Object Definitions. Chapter 7 (DICOM Model of the Real World), Section A.3 (CT Image IOD, Table A.3-1), Section A.51 (Segmentation IOD), Section C.8.2.1 (CT Image Module) and Section C.11.1 (Modality LUT Module).
- National Electrical Manufacturers Association (2026). DICOM PS3.7 2026d: Message Exchange. Chapter 9 (DIMSE-C).
- National Electrical Manufacturers Association (2026). DICOM PS3.18 2026d: Web Services. Chapter 1 (Scope).
- National Electrical Manufacturers Association (2026). DICOM PS3.4 2026d: Service Class Specifications and PS3.8 2026d: Network Communication Support for Message Exchange (not read).
- Cox, R. W. nifti1.h: Official Definition of the NIfTI-1 Header, from the meetings of the NIfTI Data Format Working Group (31 March and 2 September 2003). In the NIfTI C library nifti_clib, tag v3.0.1 (7 August 2020).
- Cox, R. W., with revisions by M. Jenkinson, R. Reynolds and K. Fissell. nifti1_io.c (functions nifti_mat44_to_quatern and nifti_quatern_to_mat44). In nifti_clib at commit 96b9954 (tag v3.0.1); public domain.
- nifti2.h: Header Structure for NIFTI-2 Format (header comment dated 2 January 2014). In nifti_clib at commit 96b9954 (tag v3.0.1).
- Insight Software Consortium / NumFOCUS. Modules/IO/NIFTI/src/itkNiftiImageIO.cxx, ITK v5.4.7 source code (Apache-2.0).
- Mason, D. and pydicom contributors. src/pydicom/filewriter.py, valuerep.py and uid.py, pydicom source code at commit 370ba29 (MIT licence; read November 2026).