Pixel data
How go-dicom decodes, compresses and transcodes pixel data: which transfer syntaxes it reads and writes, the calls that move between them, and the rules that stop it losing detail you did not agree to lose. It is for anyone who needs the samples of an image, or a file in another syntax.
Overview
The transfer syntax of a file says how its Pixel Data is held. In the native syntaxes it is the samples themselves. In the compressed ones it is encapsulated: a sequence of fragments, each frame a codestream of its syntax, with an optional offset table saying where each frame starts. Every codec in the library is pure Go; there is no CGO and nothing to register.
Decoded samples come out one pixel after another, little endian, whatever the planar configuration, with 4:2:2 chroma expanded and a JPEG 2000 color transform undone.
Transfer syntaxes
| Syntax | UID | Decoded | Encoded by | Lossy |
|---|---|---|---|---|
| Implicit VR Little Endian | 1.2.840.10008.1.2 | native | native | no |
| Explicit VR Little Endian | 1.2.840.10008.1.2.1 | native | native | no |
| Explicit VR Big Endian | 1.2.840.10008.1.2.2 | native | native | no |
| Deflated Explicit VR Little Endian | 1.2.840.10008.1.2.1.99 | native | native | no |
| RLE Lossless | 1.2.840.10008.1.2.5 | yes | CompressRLELosslessInPlace | no |
| JPEG Baseline | 1.2.840.10008.1.2.4.50 | yes | CompressJPEGBaselineInPlace(quality), CompressJPEGBaseline422InPlace(quality) | yes |
| JPEG Extended | 1.2.840.10008.1.2.4.51 | yes | CompressJPEGExtendedInPlace(quality) | yes |
| JPEG Lossless, Process 14 | 1.2.840.10008.1.2.4.57 | yes | CompressJPEGLosslessInPlace | no |
| JPEG Lossless, Selection Value 1 | 1.2.840.10008.1.2.4.70 | yes | CompressJPEGLosslessSV1InPlace | no |
| JPEG‑LS Lossless | 1.2.840.10008.1.2.4.80 | yes | CompressJPEGLSLosslessInPlace | no |
| JPEG‑LS Near-Lossless | 1.2.840.10008.1.2.4.81 | yes | CompressJPEGLSNearLosslessInPlace(near) | above NEAR 0 |
| JPEG 2000 Lossless | 1.2.840.10008.1.2.4.90 | yes | CompressJPEG2000LosslessInPlace | no |
| JPEG 2000 | 1.2.840.10008.1.2.4.91 | yes | CompressJPEG2000InPlace(rate) | yes |
| JPEG 2000 Part 2 Lossless | 1.2.840.10008.1.2.4.92 | yes | CompressJPEG2000Part2LosslessInPlace | no |
| JPEG 2000 Part 2 | 1.2.840.10008.1.2.4.93 | yes | CompressJPEG2000Part2InPlace(rate) | yes |
| HTJ2K Lossless | 1.2.840.10008.1.2.4.201 | yes | CompressHTJ2KLosslessInPlace | no |
| HTJ2K Lossless RPCL | 1.2.840.10008.1.2.4.202 | yes | CompressHTJ2KLosslessRPCLInPlace | no |
| HTJ2K | 1.2.840.10008.1.2.4.203 | yes | CompressHTJ2KInPlace(rate) | yes |
| JPEG XL Lossless | 1.2.840.10008.1.2.4.110 | yes | CompressJPEGXLLosslessInPlace | no |
| JPEG XL JPEG Recompression | 1.2.840.10008.1.2.4.111 | yes | no | no |
| JPEG XL | 1.2.840.10008.1.2.4.112 | yes, most features | no | yes |
| Deflated Image Frame Compression | 1.2.840.10008.1.2.8.1 | yes | CompressDeflatedImageFrameInPlace | no |
| MPEG-2, MPEG-4 AVC/H.264, HEVC/H.265 | 1.2.840.10008.1.2.4.100 to .108 | no | no | yes |
The encoders are listed at run time by dataset.PixelEncoders(), and one is
found by dataset.PixelEncoderFor(uid). Each encoder accepts only some
images: JPEG Baseline takes 8-bit unsigned grayscale and color; JPEG Extended
takes those and unsigned grayscale of up to 12 bits stored; JPEG-LS above NEAR
0 takes unsigned images only; JPEG XL Lossless takes gray or RGB at 8 or 16
bits allocated. An image an encoder does not take is refused with an error.
The details, decoder by decoder and feature by feature, are in CONFORMANCE.md §3.2 and §8.1.
Read the samples
DecodedPixelData returns all the frames as native bytes, decoding them when
the syntax is compressed. DecodedPixelSize says how many bytes that will be,
from the header alone, so you can refuse an image before decoding it:
size, err := dataset.DecodedPixelSize(ds)
if err != nil {
return err
}
if size > 512<<20 {
return fmt.Errorf("image of %d bytes is larger than this program decodes", size)
}
pixels, err := ds.DecodedPixelData()
if err != nil {
return err
}
fmt.Println(ds.TransferSyntaxUID(), len(pixels)) // 1.2.840.10008.1.2.4.91 524288 for JPEG2000.dcmRawPixelData is the element as stored, which for a compressed image is
fragments, not pixels.
For numbers rather than bytes:
| Call | Shape | Notes |
|---|---|---|
PixelArrayInterpreted() | [frame][row][column] | Signed when Pixel Representation says so, sign-extended from Bits Stored |
PixelArrayBySample() | [frame][row][column][sample] | Color samples kept apart; PixelDataShape() gives the shape |
PixelArray() | [frame][row][column] | The Go type follows Bits Allocated, so a signed image arrives unsigned; color samples are flattened into the columns |
Samples are in the color space the Photometric Interpretation names: a
YBR_FULL image gives YBR, not RGB, as pydicom does. RenderFrame converts
for display (Rendering).
Read one frame at a time
For a large multi-frame image, read the header with SkipBulkData, and the
frames from the file one by one. DecodeFrame decodes a frame's codestream
with the data set describing it; Pixel Data itself need not be in the data
set:
f, err := os.Open("SC_rgb_rle_2frame.dcm")
if err != nil {
return err
}
defer f.Close()
df, err := filereader.ReadDICOMFileWithOptions(filebase.NewFileReader(f),
filereader.ReadOptions{SkipBulkData: true})
if err != nil {
return err
}
ds := df.GetDataset() // the header; Pixel Data stays in the file
frames, err := df.FrameReader(df.ValueSource(f))
if err != nil {
return err
}
for i := 0; i < frames.Frames(); i++ {
codestream, err := frames.ReadFrame(i) // as stored: RLE here
if err != nil {
return err
}
samples, err := ds.DecodeFrame(codestream)
if err != nil {
return err
}
fmt.Printf("frame %d: %d bytes stored, %d decoded\n", i, len(codestream), len(samples))
}frame 0: 664 bytes stored, 30000 decoded
frame 1: 664 bytes stored, 30000 decodeddf.ValueSource(f) is the file itself, or for a deflated file a reader that
inflates it. A native frame comes out little endian whatever the file's byte
order; ReadFrameBytes reads part of one. DecodedFrameSize(ds) is the size
of one decoded frame.
Frames and offset tables
FrameRanges says where each frame's fragments lie in the file. It finds them
from the Extended Offset Table (7FE0,0001), then the Basic Offset Table, then
the fragment count and the end-of-image markers. The encaps package does the
same for fragments in memory (encaps.FrameRanges, encaps.Frames).
The frames of a video are one bitstream, not frames one after another, so
FrameReader and FrameRanges refuse them with an error that is both
filereader.ErrVideoFrames and dataset.ErrUndecodedSyntax to errors.Is.
Decompress and compress in place
if err := ds.CompressJPEGLSLosslessInPlace(); err != nil {
return err
}
// ... and back to native
if err := ds.DecompressInPlace(); err != nil {
return err
}DecompressInPlace makes the data set describe what it now holds: the transfer
syntax becomes Explicit VR Little Endian, Planar Configuration 0,
YBR_FULL_422 becomes YBR_FULL, YBR_RCT and YBR_ICT become RGB, and the
Extended Offset Table goes. Lossy Image Compression is kept: decoding does not
undo a loss. A data set already native is left alone, and on an error nothing
changes.
A Compress…InPlace method decodes first when the pixel data is compressed in
another syntax, and sets the attributes the new syntax needs. A lossy one sets
Lossy Image Compression to 01 and adds its ratio and method; it does not
change the SOP Instance UID, which is yours to do (the compress command does
it).
To choose the syntax at run time, take its encoder:
enc, ok := dataset.PixelEncoderFor("1.2.840.10008.1.2.4.81") // JPEG-LS Near-Lossless
if !ok {
return errors.New("no encoder")
}
params := dataset.EncoderParams{JPEGLSNear: 2}
fmt.Println(enc.Name, enc.Lossy, enc.Loses(params)) // JPEG-LS Near-Lossless true true
err := enc.EncodeInPlace(ds, params)EncoderParams carries the one parameter a lossy coder takes: JPEGQuality
(1 to 100), JPEGChroma422, JPEGLSNear, or JPEG2000Rate
(compress.JPEG2000Rate{Ratio: 10} or {PSNR: 45}, exactly one set).
Transcode
Transcode returns a copy in another syntax and leaves the original alone. It
decodes, codes, or only changes the recorded syntax, as the pair needs:
_, err := ds.Transcode("1.2.840.10008.1.2.4.50", dataset.TranscodeOptions{})
fmt.Println(errors.Is(err, dataset.ErrLossyNotAllowed)) // true: JPEG Baseline needs a quality
j2k, err := ds.Transcode("1.2.840.10008.1.2.4.90", dataset.TranscodeOptions{})
if err != nil {
return err
}
lossy, err := ds.Transcode("1.2.840.10008.1.2.4.91", dataset.TranscodeOptions{
JPEG2000Rate: compress.JPEG2000Rate{Ratio: 10},
})
if err != nil {
return err
}
_, err = lossy.Transcode("1.2.840.10008.1.2.4.203", dataset.TranscodeOptions{
JPEG2000Rate: compress.JPEG2000Rate{Ratio: 5},
})
fmt.Println(errors.Is(err, dataset.ErrLossyNotAllowed)) // true: never a second loss
_ = j2kThe rules:
- No loss without consent.
TranscodeOptions{}allows none. Each lossy syntax is allowed by its own field:JPEGQualityfor JPEG Baseline and Extended,JPEGLSNearabove 0 for JPEG-LS Near-Lossless,JPEG2000Ratefor lossy JPEG 2000 and HTJ2K. - Never a second loss. Pixel data that has been lossily coded, as Lossy
Image Compression
01or a lossy source syntax says, is not coded lossily again. Decoding it, or coding it again losslessly, is allowed and keeps01. Asking for the syntax it is already in changes nothing. - No UID changes. A lossy copy that is to be stored as an instance of its own needs a new SOP Instance UID from the caller (PS3.3 C.7.6.1.1.5).
The errors, through errors.Is: ErrNoEncoder (no coder for the target),
ErrUndecodedSyntax (the source cannot be decoded), ErrLossyNotAllowed.
network.ErrLossyNotAllowed is the same error, so a send refused for the same
reason matches either.
Caution
The never-a-second-loss rule belongs to Transcode and to sending over the
network. The Compress…InPlace methods, PixelEncoder.EncodeInPlace and the
compress command code what they are asked to, even pixel data that was
lossily coded before. Check Lossy Image Compression first if that matters.
What is refused
- Video (MPEG-2, H.264, HEVC) is read, stored, de-identified and sent as it
is. Decoding, rendering, redacting and frame access fail with
ErrUndecodedSyntax. - Some JPEG XL features are not decoded: splines, blended or cropped
frames, floating point samples, some patch modes, the HLG transfer function,
and XYB images with an ICC profile or primaries other than sRGB's. The error
is
ErrUndecodedSyntaxand names the feature. - JPEG 2000 features outside the decoder's set (Part 2 extensions other than the multiple component transformations, deeper than 16 bits, subsampled components in a DICOM frame, and others) are refused by name rather than guessed at (CONFORMANCE.md §8.1).
- A frame that does not match its data set (other columns, rows or components, or samples wider than Bits Allocated) is refused before it is decoded, so a small codestream cannot make the decoder allocate a large image.
- A single frame of a JPEG 2000 Part 2 image held as one codestream cannot be decoded alone; the whole image can.
A file that cannot be decoded still reads, writes and travels: only its pixels cannot be had.
On the command line
$ go-dicom compress -syntax jpeg-ls ct.dcm ct-jls.dcm
Wrote ct-jls.dcm: JPEG-LS Lossless (1.2.840.10008.1.2.4.80)
$ go-dicom compress -syntax htj2k ct.dcm ct-htj2k.dcm
Wrote ct-htj2k.dcm: HTJ2K Lossless (1.2.840.10008.1.2.4.201)
$ go-dicom compress -syntax jpeg ct.dcm ct-jpeg.dcm
Error: compress: JPEG Baseline is lossy; give -quality from 1 to 100 to accept that
$ go-dicom compress -syntax jpeg2000-lossy -ratio 10 ct.dcm ct-j2kl.dcm
Wrote ct-j2kl.dcm: JPEG 2000 (1.2.840.10008.1.2.4.91)
lossy: Lossy Image Compression is 01, and the instance has a new SOP Instance UID, 2.25.271662734467119809120465317127288282391
$ go-dicom decompress ct-jls.dcm ct-back.dcm
Wrote ct-back.dcm: Explicit VR Little Endian (1.2.840.10008.1.2.1)
$ go-dicom diff ct.dcm ct-back.dcm --ignore-meta --ignore SpecificCharacterSet
$ echo $?
0The -syntax names:
| Name (aliases) | Syntax | Parameter |
|---|---|---|
rle | RLE Lossless | |
jpeg-ls (jpegls, jls) | JPEG‑LS Lossless | |
jpeg-ls-near (jls-near) | JPEG‑LS Near-Lossless | -near |
jpeg2000 (j2k) | JPEG 2000 Lossless | |
jpeg2000-lossy (j2k-lossy) | JPEG 2000 | -ratio or -psnr |
jpeg2000-part2 (j2k-part2) | JPEG 2000 Part 2 Lossless | |
jpeg2000-part2-lossy (j2k-part2-lossy) | JPEG 2000 Part 2 | -ratio or -psnr |
htj2k | HTJ2K Lossless | |
htj2k-rpcl | HTJ2K Lossless RPCL | |
htj2k-lossy | HTJ2K | -ratio or -psnr |
jpeg-lossless | JPEG Lossless, Process 14 | |
jpeg-lossless-sv1 | JPEG Lossless, Selection Value 1 | |
deflated-frame (deflated-image-frame) | Deflated Image Frame Compression | |
jpeg-xl (jpegxl, jxl) | JPEG XL Lossless | |
jpeg (jpeg-baseline) | JPEG Baseline | -quality, -chroma 422 |
jpeg-extended (jpeg-12bit) | JPEG Extended | -quality |
A UID works as well as a name. A lossy syntax is used only when its parameter
is given, and the command then gives the instance a new SOP Instance UID.
decompress writes Explicit VR Little Endian and keeps the UID and any record
of an earlier loss. Both take -in-place, which writes a new file and renames
it over the input.
Limits and gotchas
compress.MaxDecompressedSize(256 MiB) bounds what stored pixel data may decode to, and a small input may not claim more than a 1000:1 expansion (compress.MaxInflateRatio, with an 8 MiB floor). CheckDecodedPixelSizeyourself for a tighter bound.PixelArray's Go type follows Bits Allocated, not Pixel Representation. UsePixelArrayInterpretedfor signed images.- A transcoded lossy copy keeps its UID. Give it a new one before storing it as its own instance.
- Planar Configuration, Photometric Interpretation and the offset tables change with decompression and compression; the data set is updated to match, so write the data set the call left, not a copy taken before.
- Deflated Image Frame Compression is not the Deflated transfer syntax. The first compresses each frame; the second the whole data set (Reading and writing).
See also
- Rendering: frames as images
- Reading and writing: reading without the pixels, writing the result
- Examples: compress and decompress
- dataset, compress, encaps on pkg.go.dev
- CONFORMANCE.md §3.2 and §8.1
Reading and writing files
How go-dicom reads a DICOM file, what you get back, how to query and change its attributes, and how to write it again, in Go and on the command line. It is for anyone who handles files with the library, and above all for code that reads files it did not make.
Rendering
How go-dicom turns a frame into a picture a screen can show (windowing, lookup tables, MONOCHROME1, color and ICC profiles), how to write it as a PNG or JPEG, and how the volume package puts the slices of a series in order. It is for anyone who needs to look at images, or hand them to something that is not DICOM.