Skip to Content
go-dicom(3)
Packages

compress

The pixel codecs and the encapsulation format. Every compressed transfer syntax but the video ones is decoded here in pure Go, with no CGO: RLE, JPEG Baseline and Extended, JPEG Lossless, JPEG-LS, JPEG 2000 and HTJ2K, JPEG XL and Deflated Image Frame Compression. Sixteen syntaxes are also encoded.

import "github.com/amrshadid/go-dicom/compress" · pkg.go.dev

When to use it

Most programs do not call it: dataset.Dataset decodes and encodes through it (PixelArrayInterpreted, RenderFrame, DecompressInPlace, CompressJPEG2000LosslessInPlace, Transcode), as do the network and DICOMweb transcoders. Call it directly to:

  • code or decode one frame you already hold as bytes (EncodeJPEGLS, EncodeJPEG2000Lossless, NewJPEGLSDecompressor().DecompressFrame, …);
  • read a codestream's size from its header before decoding it (FrameHeaderReader);
  • build or take apart encapsulated Pixel Data (EncapsulateFrames, ParseFragments);
  • substitute your own decoder for one of the bundled ones (ExternalDecoderRegistry).

The JPEG 2000 and JPEG XL codecs themselves are compress/jpeg2000 and compress/jpegxl. Splitting encapsulated data into frames is also in encaps.

Key types and functions

NameWhat it is for
Decoding
Decompressor, FrameDecompressorA decoder; DecompressFrame writes samples at the width Bits Allocated says.
FrameHeaderReader, FrameHeaderA frame's columns, rows, components and precision, read without decoding.
NewJPEGLSDecompressor, NewJPEGLosslessDecompressor, NewJPEG2000Decompressor, NewJPEGXLDecompressor, NewJPEGDecompressor, NewRLEDecompressorThe bundled decoders.
InflateFrameDecode a Deflated Image Frame Compression frame, held to its size.
GetExternalRegistry, ExternalDecoderRegistryReplace the JPEG‑LS, lossless JPEG, JPEG 2000 or JPEG XL decoder with your own.
Encoding
EncodeJPEGLS, EncodeJPEGLSNearLosslessJPEG‑LS, lossless or within NEAR.
EncodeJPEG2000Lossless, EncodeJPEG2000, JPEG2000RateJPEG 2000, lossless or to a ratio or PSNR; EncodeHTJ2K… and EncodeJPEG2000Part2… likewise.
EncodeJPEGLossless, EncodeJPEGBaseline, EncodeJPEGExtendedThe JPEG processes.
EncodeJPEGXLLossless, DeflateFrame, NewRLECompressorJPEG XL Lossless, Deflated frames, RLE.
Encapsulation and syntaxes
EncapsulateFrames, EncapsulateExtendedFrames to an encapsulated Pixel Data value, with a Basic or Extended Offset Table.
ParseFragments, ParseBasicOffsets, EncapsulatedDataTake an encapsulated value apart.
IsEncapsulated, IsCompressedQuestions about a transfer syntax UID.
ErrFrameMismatch, ErrJPEGXLNotDecoded, MaxDecompressedSizeRefusals and the bound on decoded size.

Example

// Code one frame of native pixel data as lossless JPEG-LS and decode it back.
package main

import (
	"bytes"
	"fmt"
	"log"
	"os"

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

func main() {
	f, err := os.Open(os.Args[1]) // a native (uncompressed) 16-bit grayscale image
	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()
	info, err := ds.GetPixelDataInfo()
	if err != nil {
		log.Fatal(err)
	}
	frame, err := ds.DecodedPixelData() // native samples, little endian
	if err != nil {
		log.Fatal(err)
	}

	coded, err := compress.EncodeJPEGLS(frame, info.Columns, info.Rows, info.SamplesPerPixel, info.BitsStored)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%d bytes -> %d bytes\n", len(frame), len(coded))

	dec := compress.NewJPEGLSDecompressor()
	header, err := dec.FrameHeader(coded) // the size, without decoding
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("header:", header.Columns, "x", header.Rows, header.Precision, "bits")

	back, err := dec.DecompressFrame(coded, info.BitsAllocated, info.BitsStored, info.PixelRepresentation)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("same samples:", bytes.Equal(back, frame))
	fmt.Println("1.2.840.10008.1.2.4.80 encapsulated:", compress.IsEncapsulated("1.2.840.10008.1.2.4.80"))
}

On CT_small.dcm it prints 32768 bytes -> 14145 bytes, header: 128 x 128 16 bits and same samples: true.

Notes

  • Samples go in and come out the way native Pixel Data holds them: interleaved by pixel, little endian, one byte a sample at 8 bits and two above.
  • A decoder checks a frame's header against the data set's Rows, Columns and Samples per Pixel before decoding, and the decoded size is bounded by MaxDecompressedSize (256 MiB) and MaxInflateRatio. A frame that would need a feature a decoder does not have is refused by name, not decoded approximately.
  • No encoder chooses a quality or a NEAR for you. The lossy encoders take the loss as an argument, and a request to encode to a syntax with no encoder fails rather than writing bytes described as that syntax.
  • Decoders hold no state between calls; a registry is guarded by a lock.
  • What each decoder covers, and how it is checked against other implementations, is in CONFORMANCE.md §8.1; the syntaxes read and written in §3.2.

Warning

The lossy encoders (EncodeJPEGBaseline, EncodeJPEGExtended, EncodeJPEG2000, EncodeHTJ2K, EncodeJPEGLSNearLossless with NEAR above 0) lose detail for good. A data set coded so must say so in Lossy Image Compression (0028,2110); the dataset methods do that, the bare functions do not.

Note

The package documentation's usage sections predate several API changes (for example EncapsulateBuffer takes []io.ReadSeeker, and GenerateFragments sends []byte). JPEGLSDecoderSkeleton, JPEGLosslessDecoderSkeleton and JPEG2000DecoderSkeleton are empty placeholders.

See also

compress/jpeg2000 · compress/jpegxl · encaps · dataset · Pixel data

On this page