Skip to Content
go-dicom(3)

Media and DICOMDIR

How go-dicom reads the DICOMDIR of a file-set, such as a CD or a USB stick of studies, and writes one, in Go and with go-dicom dicomdir. It is for anyone who reads media made elsewhere or makes media for others.

Overview

A file-set is a directory tree of DICOM files with a DICOMDIR at its root (PS3.10, PS3.3 Annex F). The DICOMDIR is itself a DICOM file: a sequence of directory records, linked by byte offsets into a tree of patients, studies, series and instances. Each instance record names its file by a File ID, the path from the root as components.

fileset.ReadDICOMDIR reads the tree from a file already read with filereader. fileset.Builder writes one from the instances' headers alone.

PS3.10 8.5 allows a File ID of at most eight components, each at most eight characters from A-Z, 0-9 and _: no lower case, no extension. Most directories on disk do not keep to it (ct.dcm), and the library refuses such names unless told otherwise.

Read a DICOMDIR

func listDICOMDIR(path string) error {
	f, err := os.Open(path)
	if err != nil {
		return err
	}
	defer f.Close()
	df, err := filereader.ReadDICOMFileWithOptions(filebase.NewFileReader(f), filereader.ReadOptions{
		MaxValueLength: 1 << 20,
		MaxHeaderBytes: 256 << 20,
	})
	if err != nil {
		return err
	}
	dir, err := fileset.ReadDICOMDIRWithOptions(df, fileset.ReadOptions{MaxRecords: 100000})
	if err != nil {
		return err // errors.Is(err, fileset.ErrTooManyRecords) for a DICOMDIR over the bound
	}
	fmt.Println("File-set:", dir.FileSetID, len(dir.Records), "records")
	root := filepath.Dir(path)
	for _, image := range dir.RecordsOfType(fileset.RecordImage) {
		if !image.InUse || !image.HasValidFileID() {
			continue
		}
		file := filepath.Join(root, image.Path(string(filepath.Separator)))
		fmt.Println(file, image.StringValue(tag.New(0x0020, 0x0013)))
	}
	return nil
}

On dicomdirtests/DICOMDIR from pydicom's test files:

File-set: PYDICOM_TEST 52 records
dicomdirtests/77654033/CR1/6154 1
dicomdirtests/77654033/CR2/6247 1
…
dicomdirtests/98892003/MR700/4648 7

What a DICOMDIR holds:

Field or methodWhat it is
FileSetIDThe File-set ID (0004,1130), the label of the media
RootsThe top-level records, usually one per patient, each with its Children
RecordsEvery record in stored order, reachable from a root or not
OffsetsWereUsedWhether the tree came from the byte offsets, or was rebuilt from record order because the file had none
RecordsOfType(t)The records of one type: RecordPatient, RecordStudy, RecordSeries, RecordImage, RecordRTDose and the rest
Walk(fn)Every record, depth first; returning false skips what is below

Each Record has its Type, its Offset in the file, InUse (the Record In-use Flag; a record not in use describes an entry deleted without rewriting the file), ReferencedFileID as components, every attribute in Dataset, and its Children. StringValue(tag) reads one attribute.

Warning

Record.Path joins the File ID without checking it. A crafted DICOMDIR can name .. or an absolute path. Check HasValidFileID() before you open the file it names, as above.

MaxRecords bounds the records built, not the parse: the records are items of a file already read, so for media you do not trust, bound the read of the DICOMDIR itself too, with MaxValueLength and MaxHeaderBytes (Reading and writing).

Write a DICOMDIR

Builder indexes each instance from its header; it needs no Pixel Data and keeps only the record keys of PS3.3 F.5, about 720 bytes an instance, so a file-set of tens of thousands of instances can be indexed as the files are written. Its methods may be called from several goroutines.

b := fileset.NewBuilder(fileset.DICOMDIROptions{FileSetID: "EXAMPLE"})
for i, path := range []string{"ct.dcm", "mr.dcm"} {
	header, err := readHeader(path) // ReadDICOMFileWithOptions with SkipBulkData, then GetDataset
	if err != nil {
		return err
	}
	fileID := []string{"DICOM", fmt.Sprintf("IM%06d", i+1)} // where the file is on the media
	if err := b.Add(fileID, header); err != nil {
		return err
	}
}

out, err := os.Create("DICOMDIR")
if err != nil {
	return err
}
if _, err := b.WriteTo(out); err != nil {
	out.Close()
	return err
}
if err := out.Close(); err != nil {
	return err
}

Add refuses an instance, and changes nothing, when:

ErrorWhy
wraps ErrInvalidFileIDThe File ID breaks PS3.10 8.5, unless AllowNonConformantFileIDs is set
*MissingUIDError (ErrMissingUID)No Study, Series, SOP Class, SOP Instance or Transfer Syntax UID
wraps ErrDuplicateFileIDThat File ID was added already
wraps ErrDuplicateSOPInstanceThat SOP Instance UID was added already

For example:

fileset: not a valid PS3.10 File ID: ["DICOM" "ct.dcm"] (PS3.10 8.5 allows 1 to 8 components of 1 to 8 characters from A-Z, 0-9 and _)
fileset: the SOP Instance UID is already in the file-set: 1.3.6.1.4.1.5962.1.1.1.1.1.20040119072730.12322 (at DICOM/IM000009)

The Transfer Syntax UID is taken from header.TransferSyntaxUID(), which a data set read from a file has, or from a (0002,0010) element. An instance that is not an image gets the record type of its SOP class (SR DOCUMENT, RT DOSE and so on). Bytes() gives the DICOMDIR in memory instead of writing it, and Len() counts the instances added.

DICOMDIROptions.AllowNonConformantFileIDs indexes files whose names break the rule. Such a DICOMDIR indexes a local directory, but is not valid on media. SOPInstanceUID names the DICOMDIR itself; it is generated when empty.

fileset.FileSet (NewFileSet, Scan, WriteDICOMDIR) does the same for a directory it scans, holding a record for each file found; Builder is the one to use when you know the File IDs and do not want every header held.

On the command line

$ go-dicom dicomdir export/
Error: dicomdir: 2 file(s) are not named as a File ID must be (PS3.10 8.5: components of at most 8 characters from A-Z, 0-9 and _, no extension), so a DICOMDIR could not index them for media; nothing was written. Rename them, or copy them under names that do with --copy-to <new directory>:
  ct.dcm
  mr.dcm
$ go-dicom dicomdir --copy-to media/ export/
Wrote media/DICOMDIR: 2 patient, 2 study, 2 series, 2 image
$ find media | sort
media
media/DICOM
media/DICOM/IM000001
media/DICOM/IM000002
media/DICOMDIR
$ go-dicom dicomdir --list media/
DICOMDIR media/DICOMDIR
PATIENT  PatientName=CompressedSamples^CT1  PatientID=1CT1
  STUDY  StudyDate=20040119  StudyID=1CT1  StudyInstanceUID=1.3.6.1.4.1.5962.1.2.1.20040119072730.12322
    SERIES  Modality=CT  SeriesNumber=1  SeriesInstanceUID=1.3.6.1.4.1.5962.1.3.1.1.20040119072730.12322
      IMAGE  DICOM/IM000001  InstanceNumber=1  ReferencedSOPInstanceUIDInFile=1.3.6.1.4.1.5962.1.1.1.1.1.20040119072730.12322
PATIENT  PatientName=CompressedSamples^MR1  PatientID=4MR1
  STUDY  StudyDate=20040826  StudyID=4MR1  StudyInstanceUID=1.3.6.1.4.1.5962.1.2.4.20040826185059.5457
    SERIES  Modality=MR  SeriesNumber=1  SeriesInstanceUID=1.3.6.1.4.1.5962.1.3.4.1.20040826185059.5457
      IMAGE  DICOM/IM000002  InstanceNumber=1  ReferencedSOPInstanceUIDInFile=1.3.6.1.4.1.5962.1.1.4.1.1.20040826185059.5457
2 patient, 2 study, 2 series, 2 image
  • Without --list the command indexes the files under the directory and writes a DICOMDIR at its root. It never renames a file: names that break the File ID rule are listed and nothing is written.
  • --copy-to <dir> copies the files, in the order of their paths, into a new or empty directory as DICOM/IM000001, DICOM/IM000002 and so on, and writes the DICOMDIR there. The originals are left as they were.
  • --force replaces a DICOMDIR already there; it is never indexed itself.
  • --file-set-id sets the label, at most 16 characters.
  • --list takes a DICOMDIR or the directory holding one; --json prints the records with "schemaVersion": 1.

Files that are not DICOM are left out and named on standard error.

Limits and gotchas

  • File IDs are strict. Lower case and extensions are refused unless you allow them, and then the result is not valid on media.
  • A DICOMDIR is an index, not the data. Records can be out of date: check InUse, and that the file is there before trusting a record.
  • Unreachable records stay in Records and are not in the tree from Roots.
  • Bound both the read and the records for media you did not make.
  • De-identifying media: go-dicom anonymize reports a DICOMDIR and does not write it; build a new one over the de-identified files (De-identification).

What the Builder writes, and the readers it has been checked against, is in CONFORMANCE.md §8.6.

See also

On this page