go-dicom

command module
v1.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 20, 2026 License: MIT Imports: 3 Imported by: 0

README

go-dicom

A comprehensive, high-performance Go library for reading, writing, manipulating, and networking DICOM (Digital Imaging and Communications in Medicine) data. The Go equivalent of Python's pydicom + pynetdicom.

Overview

go-dicom is designed for healthcare IT systems, medical imaging applications, PACS systems, and clinical data management. It provides:

  • Complete DICOM file I/O with support for all transfer syntaxes (.dcm, .ima, DICOMDIR, raw)
  • DICOM networking — SCU/SCP with C-ECHO, C-STORE, C-FIND, C-MOVE, C-GET, and all N-DIMSE services
  • Thread-safe dataset operations for concurrent processing
  • 5,000+ standard DICOM tags with O(1) lookup
  • 10,500+ private vendor tags (GE, Siemens, Philips, Toshiba, and more)
  • De-identification / anonymization per DICOM PS3.15 Annex E
  • Pixel data extraction with multi-frame and multi-bit-depth support
  • 30+ international character encodings (Japanese, Chinese, Korean, Arabic, etc.)
  • TLS support for encrypted DICOM communication (HIPAA compliance)
  • CLI tools for file inspection, conversion, and network operations (echoscu, storescu, storescp, findscu, movescu)

Quick Start

Installation
go get github.com/amrshadid/go-dicom
DICOM Networking (SCU Client)
package main

import (
    "context"
    "fmt"
    "log"

    "github.com/amrshadid/go-dicom/network"
)

func main() {
    ctx := context.Background()

    // Create SCU (client) — equivalent to pynetdicom's AE().associate()
    scu := network.NewSCU(network.SCUConfig{
        CallingAE: "MY_APP",
        CalledAE:  "PACS",
        Address:   "pacs.hospital.com:11112",
    })

    // Associate with the server
    if err := scu.Associate(ctx, nil); err != nil {
        log.Fatal(err)
    }
    defer scu.Release(ctx)

    // C-ECHO (verification/ping)
    if err := scu.Echo(ctx); err != nil {
        log.Fatal(err)
    }
    fmt.Println("Server is reachable!")

    // C-STORE (send a dataset)
    // err = scu.Store(ctx, dataset)

    // C-FIND (query) — results stream on a Go channel
    // results, _ := scu.Find(ctx, queryDataset)
    // for result := range results {
    //     fmt.Println(result.DataSet)
    // }

    // C-MOVE (retrieve to another AE)
    // err = scu.Move(ctx, queryDataset, "DEST_AE")
}
DICOM Networking (SCP Server)
package main

import (
    "context"
    "fmt"
    "log"

    "github.com/amrshadid/go-dicom/dataset"
    "github.com/amrshadid/go-dicom/network"
)

func main() {
    ctx := context.Background()

    // Create SCP (server) — equivalent to pynetdicom's AE().start_server()
    scp := network.NewSCP(network.SCPConfig{
        AETitle: "MY_SCP",
        Port:    11112,
    })

    // Set handler for incoming requests
    scp.SetHandler(&network.StorageHandler{
        OnStore: func(ctx context.Context, sopClass, sopInstance string, ds *dataset.Dataset) uint16 {
            fmt.Printf("Received: %s\n", sopInstance)
            // Save to disk, database, forward to another PACS, etc.
            return network.StatusSuccess
        },
    })

    // Listen and serve (blocks, handles associations in goroutines)
    log.Fatal(scp.ListenAndServe(ctx))
}
Read a DICOM File
package main

import (
    "fmt"
    "log"
    "os"

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

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

    dicomFile, err := filereader.ReadDICOMFile(file)
    if err != nil {
        log.Fatal(err)
    }

    ds := dicomFile.GetDataset()

    // Access elements by tag
    name, _ := ds.GetStringValue(tag.New(0x0010, 0x0010)) // Patient Name
    fmt.Println("Patient:", name)
}
Command-Line Tools
# Build the CLI
go build -o dicom .

# === File Operations ===
./dicom show patient.dcm          # Display DICOM file contents
./dicom info patient.dcm           # Display file metadata
./dicom convert patient.dcm out.json  # Convert to JSON

# === Network Operations (like pynetdicom CLI) ===
# Verification (ping a PACS)
./dicom echoscu pacs.hospital.com:11112

# Send DICOM files (.dcm, .ima, any DICOM format)
./dicom storescu -aec PACS pacs:11112 study/*.dcm

# Start a storage server (receive files)
./dicom storescp -port 11112 -output ./received/

# Query for patients/studies
./dicom findscu -patient-name "Smith*" -level STUDY pacs:11112

# Retrieve studies to a destination
./dicom movescu -dest MY_SCP -study 1.2.3.4 pacs:11112

# Get help
./dicom -h

Architecture

Module Organization

The library is organized into focused packages, each handling a specific DICOM aspect:

Core I/O
Package Description
filebase Low-level binary I/O with byte order handling
filereader DICOM file reading (preamble, meta info, dataset)
filewriter DICOM file writing with validation
fileutil Byte order detection, padding, caching, codec integration
fileset DICOM file collection management
Data Model
Package Description
dataset Thread-safe in-memory dataset with rich query API
dataelem Data element representation with all 28+ VRs
tag Tag definitions, dictionary (5,000+ standard + 10,500+ private)
element Value encoding, decoding, and conversion
sequence Thread-safe ordered sequence container
uid UID management, validation, and classification
valuerep Value representation validation and parsing
values Value conversion and encoding
multival Type-safe multi-value lists
Networking (DICOM Upper Layer Protocol)
Package Description
network DICOM networking — SCU/SCP, DIMSE services, PDU encoding, TLS
Encoding and Compression
Package Description
charset 30+ character set encodings (ISO 2022, Unicode, CJK)
compress Compression/decompression (DEFLATE, RLE, JPEG)
encaps Encapsulated pixel data parsing and frame extraction
Imaging and Clinical
Package Description
pixels Pixel data access and statistical analysis
overlays Overlay groups, ROI analysis, graphics
waveforms Physiological signals (ECG, EEG) with QRS detection
sr Structured reports with coded concepts (SNOMED-CT, LOINC)
anonymize De-identification per DICOM PS3.15 Annex E
Serialization and Utilities
Package Description
jsonrep DICOM JSON Model (Part 18) with bulk data support
config Thread-safe global configuration
errors DICOM-specific error types
hooks Extensible callback/plugin system
util General utilities (hex dump, dataset info)
cli Command-line interface framework

Networking Features

pynetdicom Feature Parity

go-dicom's network package provides feature parity with pynetdicom, reimplemented in Go with goroutines, channels, and context.Context.

Feature pynetdicom go-dicom Notes
C-ECHO (Verification) Yes Yes scu.Echo(ctx)
C-STORE (Storage) Yes Yes scu.Store(ctx, ds)
C-FIND (Query) Yes Yes scu.Find(ctx, ds) — streams via Go channel
C-MOVE (Retrieve) Yes Yes scu.Move(ctx, ds, dest)
C-GET (Get) Yes Yes scu.Get(ctx, ds)
N-EVENT-REPORT Yes Yes Full N-DIMSE service support
N-GET Yes Yes
N-SET Yes Yes
N-ACTION Yes Yes
N-CREATE Yes Yes
N-DELETE Yes Yes
SCU (Client) Yes Yes network.NewSCU()
SCP (Server) Yes Yes network.NewSCP() with goroutine-per-association
TLS Encryption Yes Yes network.DialTLS() / network.ListenTLS()
Association Negotiation Yes Yes Full A-ASSOCIATE-RQ/AC/RJ state machine
Presentation Context Negotiation Yes Yes Abstract + Transfer Syntax negotiation
Extended Negotiation Yes Yes Async ops, SCP/SCU role selection, user identity
Storage SOP Classes 100+ 80+ CT, MR, US, PET, RT, XR, SR, waveforms, encapsulated docs
Transfer Syntax Support 15+ 15 All standard + compressed syntaxes
Query/Retrieve Models Patient/Study Root Yes Find, Move, Get for both models
Modality Worklist Yes Yes MWL SOP Class with WorklistHandler
MPPS Yes Yes Via N-CREATE/N-SET
Print Management Yes Yes SOP Class UIDs defined
Handler Interface evt_handlers Handler interface Go-idiomatic with BaseHandler embedding
CLI Tools 7 tools 5 tools echoscu, storescu, storescp, findscu, movescu
Async Operations Thread pool Goroutines Native Go concurrency
Context/Cancellation N/A context.Context Timeouts, graceful shutdown
Supported File Formats

The network module works with any DICOM data regardless of source format:

Format Extension Support
Standard DICOM .dcm Full
Siemens IMA .ima Full
DICOMDIR DICOMDIR Full
Raw DICOM (none) Full
DICOM Part 10 .dicom Full
Handler Patterns
// 1. Echo-only (verification server)
scp.SetHandler(&network.EchoHandler{})

// 2. Storage with callback
scp.SetHandler(&network.StorageHandler{
    OnStore: func(ctx context.Context, sopClass, sopInstance string, ds *dataset.Dataset) uint16 {
        // Save to disk, database, cloud storage, etc.
        return network.StatusSuccess
    },
})

// 3. Query/Retrieve with callbacks
scp.SetHandler(&network.QueryRetrieveHandler{
    OnFind: func(ctx context.Context, sopClass string, query *dataset.Dataset) ([]*dataset.Dataset, error) {
        // Search database, return matching results
        return results, nil
    },
})

// 4. Modality Worklist
scp.SetHandler(&network.WorklistHandler{
    OnWorklist: func(ctx context.Context, query *dataset.Dataset) ([]*dataset.Dataset, error) {
        // Return scheduled procedures
        return procedures, nil
    },
})

// 5. Composite handler (mix & match)
h := network.NewCompositeHandler()
h.SetStoreHandler(myStoreHandler)
h.SetFindHandler(myFindHandler)
scp.SetHandler(h)

// 6. Custom handler (implement the interface)
type MyHandler struct { network.BaseHandler }
func (h *MyHandler) HandleCStore(ctx context.Context, req *network.CStoreRequest) (*network.CStoreResponse, error) {
    // Full control over request processing
}

Features

DICOM Standards Compliance
Standard Status
DICOM PS3.5 - Data Structures and Encoding Supported
DICOM PS3.6 - Data Dictionary Supported (5,000+ tags)
DICOM PS3.7 - Message Exchange (DIMSE) Supported
DICOM PS3.8 - Network Communication (Upper Layer) Supported
DICOM PS3.10 - Media Storage and File Format Supported
DICOM PS3.15 - Security (TLS, de-identification) Supported
DICOM JSON Model (Part 18) Supported
ISO 2022 - Character set escape sequences Supported
Transfer Syntax Support
Transfer Syntax File I/O Network
Implicit VR Little Endian Read/Write Yes
Explicit VR Little Endian Read/Write Yes
Explicit VR Big Endian Read/Write Yes
Deflated Explicit VR LE Read Yes
RLE Lossless Read Yes
JPEG Baseline Read Yes
JPEG Extended Read Yes
JPEG Lossless Read Yes
JPEG-LS Lossless Read Yes
JPEG-LS Near-Lossless Read Yes
JPEG 2000 Lossless Read Yes
JPEG 2000 Read Yes
Thread Safety

All mutable data structures use sync.RWMutex for concurrent access. Datasets, sequences, and managers are safe for concurrent reads with exclusive writes. The SCP server spawns a goroutine per association for concurrent client handling.

De-identification Profiles

The anonymize package supports multiple de-identification profiles per DICOM PS3.15:

  • Basic Profile - Standard tag removal/replacement
  • Clean Descriptors - Remove text descriptions
  • Clean Graphics - Remove burned-in annotations
  • Retain Long Full Dates - Keep dates for longitudinal studies
  • Retain Patient Characteristics - Keep age, sex, size, weight
  • Retain Device Identity - Keep device information
  • Retain UIDs - Keep original UIDs
  • Retain Safe Private - Keep safe private tags

Building

# Build the library
go build ./...

# Build the CLI tool
go build -o dicom .

# Run all tests (71 network tests + file I/O tests)
go test -race ./...

# Run network tests specifically
go test -v ./network/...

# Run tests with coverage
go test -race -coverprofile=coverage.out ./... && go tool cover -html=coverage.out

# Run linter
golangci-lint run ./...

Examples

See the examples directory for complete working examples:

Contributing

Contributions are welcome. Please read CONTRIBUTING.md for guidelines.

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/my-feature)
  3. Make your changes with tests
  4. Run make all to verify
  5. Submit a pull request

Security

For security concerns, especially regarding Protected Health Information (PHI), please see SECURITY.md.

License

MIT License - see LICENSE for details.

Acknowledgments

  • DICOM Standard - The foundation this library is built on
  • pydicom - Python DICOM library that inspired the API design
  • pynetdicom - Python DICOM networking library that inspired the network module
  • Go Community - Excellent standard library and ecosystem

Resources

Documentation

The Go Gopher

There is no documentation for this package.

Directories

Path Synopsis
Package anonymize provides DICOM de-identification (anonymization) support per DICOM PS3.15 Annex E.
Package anonymize provides DICOM de-identification (anonymization) support per DICOM PS3.15 Annex E.
Package charset provides DICOM character set encoding and decoding support.
Package charset provides DICOM character set encoding and decoding support.
Package cli provides a command-line interface framework for DICOM tools.
Package cli provides a command-line interface framework for DICOM tools.
Package compress provides comprehensive compression and encapsulation handling for DICOM pixel data.
Package compress provides comprehensive compression and encapsulation handling for DICOM pixel data.
Package config provides centralized, thread-safe global configuration management for DICOM operations.
Package config provides centralized, thread-safe global configuration management for DICOM operations.
Package dataelem provides core DICOM data element structures and operations.
Package dataelem provides core DICOM data element structures and operations.
Package dataset provides high-level data structure and operations for in-memory DICOM datasets.
Package dataset provides high-level data structure and operations for in-memory DICOM datasets.
Package encaps provides DICOM encapsulation parsing and frame extraction.
Package encaps provides DICOM encapsulation parsing and frame extraction.
Package errors provides comprehensive error handling for DICOM operations.
Package errors provides comprehensive error handling for DICOM operations.
examples
input_output/read_element_values command
Example: Read and Access DICOM Element Values
Example: Read and Access DICOM Element Values
networking command
Example: DICOM Networking with go-dicom
Example: DICOM Networking with go-dicom
Package filebase provides low-level file I/O abstractions for DICOM file operations.
Package filebase provides low-level file I/O abstractions for DICOM file operations.
Package filereader provides comprehensive DICOM file reading support.
Package filereader provides comprehensive DICOM file reading support.
Package fileset provides comprehensive management of DICOM file collections organized in directory structures.
Package fileset provides comprehensive management of DICOM file collections organized in directory structures.
Package fileutil provides comprehensive file and data utilities for DICOM processing.
Package fileutil provides comprehensive file and data utilities for DICOM processing.
Package filewriter provides comprehensive DICOM file writing support.
Package filewriter provides comprehensive DICOM file writing support.
Package hooks provides DICOM parsing and processing hook support.
Package hooks provides DICOM parsing and processing hook support.
Package jsonrep provides DICOM JSON Model representation support.
Package jsonrep provides DICOM JSON Model representation support.
Package multival provides type-safe multi-value lists with constructor-based type enforcement.
Package multival provides type-safe multi-value lists with constructor-based type enforcement.
Package network provides DICOM networking capabilities implementing the DICOM Upper Layer Protocol (DICOM Part 8).
Package network provides DICOM networking capabilities implementing the DICOM Upper Layer Protocol (DICOM Part 8).
Package overlays provides comprehensive support for DICOM overlay management.
Package overlays provides comprehensive support for DICOM overlay management.
Package pixels provides comprehensive access to and manipulation of DICOM pixel data.
Package pixels provides comprehensive access to and manipulation of DICOM pixel data.
Package sequence provides a thread-safe ordered sequence container for DICOM datasets.
Package sequence provides a thread-safe ordered sequence container for DICOM datasets.
Package sr provides comprehensive support for DICOM Structured Reports.
Package sr provides comprehensive support for DICOM Structured Reports.
Package tag provides DICOM tag handling and dictionary lookup functionality.
Package tag provides DICOM tag handling and dictionary lookup functionality.
Package uid provides utilities for DICOM Unique Identifier (UID) management.
Package uid provides utilities for DICOM Unique Identifier (UID) management.
Package util provides utility functions for DICOM data manipulation and analysis.
Package util provides utility functions for DICOM data manipulation and analysis.
Package valuerep provides utilities for DICOM Value Representation (VR) handling and validation.
Package valuerep provides utilities for DICOM Value Representation (VR) handling and validation.
Package values provides utilities for DICOM value conversion and handling.
Package values provides utilities for DICOM value conversion and handling.
Package waveforms provides support for managing and analyzing DICOM waveform data.
Package waveforms provides support for managing and analyzing DICOM waveform data.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL