Skip to Content
go-dicom(3)

Getting started

Install go-dicom, read a file, print a few of its attributes, change one and write the file back: once in Go and once on the command line. It is for someone who has not used the library before.

Overview

A file is read into a DICOMFile, the file meta group and the elements as stored. GetDataset turns those into a Dataset, which is what you query and change. filewriter writes a data set back as a file.

The command line does the same jobs without code: info and show read, modify changes, diff compares.

Install

go-dicom is a Go library and a command line. The command line is one static binary with nothing to install beside it, published for each platform with every release:

PlatformBuildInstall with
macOS, Apple Silicongo-dicom-macos-arm64the install script
macOS, Intelgo-dicom-macos-amd64the install script
Linux, x86-64go-dicom-linux-amd64the install script
Linux, ARM64go-dicom-linux-arm64the install script
Linux, x86 32-bitgo-dicom-linux-386the install script
Windows, x86-64go-dicom-windows-amd64.exePowerShell, below
Anything else Go builds forfrom sourcego install, below

As a library

In a Go module, with Go 1.25 or later:

go get github.com/amrshadid/go-dicom

macOS

The install script picks the build for your Mac (Apple Silicon or Intel), checks it against the checksums published with the release, and puts it in a directory already on your PATH:

curl -fsSL https://raw.githubusercontent.com/amrshadid/go-dicom/main/install.sh | sh
go-dicom version

Tip

If you download the binary through a browser instead, macOS marks it as quarantined and Gatekeeper refuses to run it. Clear the flag with xattr -d com.apple.quarantine ~/.local/bin/go-dicom (or wherever you put it).

Linux

The same script. It is POSIX sh, so it also runs in a minimal container, and the Linux builds are statically linked:

curl -fsSL https://raw.githubusercontent.com/amrshadid/go-dicom/main/install.sh | sh
go-dicom version

It installs to ~/.local/bin or ~/bin when one is on your PATH, and to /usr/local/bin otherwise (asking for sudo only then). To choose the place or the version, download the script and run it yourself:

curl -fsSL -O https://raw.githubusercontent.com/amrshadid/go-dicom/main/install.sh
less install.sh                          # about a hundred lines
sh install.sh v1.12.0                    # a given release
PREFIX=/usr/local/bin sh install.sh      # a given directory

Windows

The install script does not run on Windows. In PowerShell, download the build and the release's checksums, and compare them before you run it:

$r = "https://github.com/amrshadid/go-dicom/releases/latest/download"
Invoke-WebRequest "$r/go-dicom-windows-amd64.exe" -OutFile go-dicom.exe
Invoke-WebRequest "$r/SHA256SUMS" -OutFile SHA256SUMS
(Get-FileHash go-dicom.exe -Algorithm SHA256).Hash.ToLower()
Select-String go-dicom-windows-amd64.exe SHA256SUMS

The hash printed by Get-FileHash must equal the one on the SHA256SUMS line. Then move go-dicom.exe to a folder on your PATH and run go-dicom version.

From source

On any platform Go builds for:

go install github.com/amrshadid/go-dicom@latest

Or from a clone, which stamps the version into the binary:

git clone https://github.com/amrshadid/go-dicom
cd go-dicom
make build
./go-dicom version

The samples on this page use CT_small.dcm from pydicom's test files, saved as ct.dcm.

Read a file in Go

package main

import (
	"fmt"
	"log"
	"os"

	"github.com/amrshadid/go-dicom/filebase"
	"github.com/amrshadid/go-dicom/filereader"
)

func main() {
	f, err := os.Open("ct.dcm")
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()

	df, err := filereader.ReadDICOMFile(filebase.NewFileReader(f))
	if err != nil {
		log.Fatal(err)
	}
	ds := df.GetDataset()

	fmt.Println("Patient:  ", ds.GetStringByKeyword("PatientName"))
	fmt.Println("Modality: ", ds.GetStringByKeyword("Modality"))
	fmt.Println("Study:    ", ds.GetStringByKeyword("StudyInstanceUID"))
	fmt.Println("Syntax:   ", df.FileMetaInfo.TransferSyntaxUID)

	info, err := ds.GetPixelDataInfo()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Image:    ", info.Columns, "x", info.Rows, "at", info.BitsStored, "bits")
}

It prints:

Patient:   CompressedSamples^CT1
Modality:  CT
Study:     1.3.6.1.4.1.5962.1.2.1.20040119072730.12322
Syntax:    1.2.840.10008.1.2.1
Image:     128 x 128 at 16 bits

GetStringByKeyword returns an empty string for an attribute that is not there; ContainsByKeyword says whether it is.

Read a file on the command line

$ go-dicom info ct.dcm
=== DICOM File Information ===
File:         ct.dcm
Size:         39206 bytes
…
Key DICOM Elements:
─────────────────────────────────────
Patient Name:    CompressedSamples^CT1
Patient ID:      1CT1
Study Date:      20040119
Modality:        CT
Study Desc:      e+1

Image Dimensions:
─────────────────────────────────────
Rows:            128
Columns:         128
$ go-dicom show ct.dcm::PatientName
0010,0010    PN  22      CompressedSamples^CT1
$ go-dicom show ct.dcm | head -6
=== DICOM File: ct.dcm ===
Tag          VR  Length  Value
─────────────────────────────────────────────
0002,0000    UL  4       192
0002,0001    OB  2       <2 bytes>
0002,0002    UI  26      1.2.840.10008.5.1.4.1.1.2

show prints every element as stored, nested items indented under their sequence. show file::Element takes a keyword, a tag (0010,0010) or the dictionary name, and prints that one element whole.

Change an attribute and write the file

In Go, change the data set and write it with filewriter:

package main

import (
	"log"
	"os"

	"github.com/amrshadid/go-dicom/filebase"
	"github.com/amrshadid/go-dicom/filereader"
	"github.com/amrshadid/go-dicom/filewriter"
)

func main() {
	f, err := os.Open("ct.dcm")
	if err != nil {
		log.Fatal(err)
	}
	df, err := filereader.ReadDICOMFile(filebase.NewFileReader(f))
	f.Close()
	if err != nil {
		log.Fatal(err)
	}
	ds := df.GetDataset()

	if err := ds.SetStringByKeyword("PatientName", "Roe^Richard"); err != nil {
		log.Fatal(err)
	}
	ds.RemoveByKeyword("PatientBirthDate")

	out, err := os.Create("ct-changed.dcm")
	if err != nil {
		log.Fatal(err)
	}
	w := filewriter.NewDICOMFileWriter(filebase.NewFileWriter(out))
	w.SetFileMetaInfo(&filewriter.FileMetaInfo{
		MediaStorageSOPClassUID:    ds.GetStringByKeyword("SOPClassUID"),
		MediaStorageSOPInstanceUID: ds.GetStringByKeyword("SOPInstanceUID"),
		TransferSyntaxUID:          filewriter.StorageTransferSyntax(ds),
	})
	if err := w.AddDataElements(filewriter.ElementsFromDataset(ds)); err != nil {
		log.Fatal(err)
	}
	if err := w.Write(); err != nil {
		log.Fatal(err)
	}
	if err := out.Close(); err != nil {
		log.Fatal(err)
	}
}

ElementsFromDataset carries the nested sequence items with it, and StorageTransferSyntax keeps a compressed file in its own syntax and writes an uncompressed one as Explicit VR Little Endian.

On the command line, modify does the same, and diff shows what changed:

$ go-dicom modify -set PatientName='Roe^Richard' -delete PatientBirthDate ct.dcm ct-changed.dcm
Wrote ct-changed.dcm: 2 change(s), transfer syntax 1.2.840.10008.1.2.1
$ go-dicom diff ct.dcm ct-changed.dcm --ignore-meta
--- ct.dcm
+++ ct-changed.dcm
(0008,0005) Specific Character Set
- CS ISO_IR 100
+ CS ISO_IR 192
(0010,0010) Patient's Name
- PN CompressedSamples^CT1
+ PN Roe^Richard
(0010,0030) Patient's Birth Date
- DA

The Specific Character Set changes because text is read into UTF-8 and written back as UTF-8; Character sets explains why.

Limits and gotchas

  • GetStringByKeyword is for text. Numbers stored in binary (US, UL, FL and the rest) are bytes, and reading them as a string gives nonsense. The image attributes are gathered by GetPixelDataInfo; Reading and writing shows how to read the others.
  • SetStringByKeyword changes an attribute that is there. To add one, use AddByKeyword with its VR; see Reading and writing.
  • A file from someone else is untrusted input. ReadDICOMFile sets no limit on how large a value or a header may be. Reading and writing shows the options that bound a read.
  • Errors are returned, not logged away. Every call that can fail says so, and the samples here stop at the first one.

See also

On this page