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.
Overview
Dataset.RenderFrame gives an 8-bit image.Image: an *image.Gray for a
grayscale image, an *image.NRGBA for a color one. A grayscale frame goes
through the three lookup stages of PS3.3 C.11; a color frame is converted to
RGB.
Rendering decodes the frame first when it is compressed, in any syntax the library decodes (Pixel data).
Render a frame
img, err := ds.RenderFrame(0, &dataset.RenderOptions{
Window: &dataset.Window{Center: 40, Width: 400}, // Hounsfield units
})
if err != nil {
return err
}
out, err := os.Create("ct.png")
if err != nil {
return err
}
defer out.Close()
if err := png.Encode(out, img); err != nil {
return err
}Frames are counted from 0. Pass nil options to use what the file says. What
each stage takes, in order of preference:
| Stage | Used, first that is present |
|---|---|
| Modality | Modality LUT Sequence; Rescale Slope and Intercept |
| VOI | RenderOptions.Window; the first VOI LUT Sequence item; the first Window Center and Width, with its VOI LUT Function (LINEAR, LINEAR_EXACT, SIGMOID); the range of the values across all frames |
| Presentation | Presentation LUT Sequence; Presentation LUT Shape (IDENTITY or INVERSE); MONOCHROME1 inverted |
An enhanced multi-frame image takes its rescale, window and VOI LUT from the
frame's functional group, then the shared one. Where a data set has both a VOI
LUT Sequence and a window, which C.11.2 leaves to the viewer, the table is
used, as pydicom does; your Window wins over both.
RenderOptions:
| Field | What it does |
|---|---|
Window | A window in the units the Modality LUT produces (Hounsfield units for CT); Function is LINEAR when empty. Grayscale only |
StoredRange | For an image with no window and no VOI LUT: show the range Bits Stored can hold, put through the rescale, instead of the range the values reach. The same for every frame, found without reading a pixel |
ColorSpace | Convert through the image's ICC profile into RenderSRGB, RenderAdobeRGB, RenderROMMRGB or RenderDisplayP3 |
ICCProfile | The profile to convert from, in place of the data set's, for a data set read without its binary values |
Color
YBR_FULL and YBR_FULL_422 are converted to RGB by the standard's equations,
and PALETTE COLOR through its tables (segmented ones expanded). Samples wider
than 8 bits keep their most significant 8.
ICC profiles
Without ColorSpace, color is shown as the samples say, and
ds.ICCProfile() returns the profile for the PNG or JPEG to carry, so that a
viewer that manages color does the managing. With it, the picture is converted,
relative colorimetric with clipping, and
RenderColorSpace.ICCProfile(gray) gives the profile of the space converted
into:
img, err := ds.RenderFrame(0, &dataset.RenderOptions{ColorSpace: dataset.RenderSRGB})
if err != nil {
return err // an *ICCProfileError for a profile that cannot be applied
}
profile, err := dataset.RenderSRGB.ICCProfile(false) // false: an RGB profileMatrix and tone curve profiles, RGB or gray, version 2 or 4, are applied. A
profile built from lookup tables is refused with an *ICCProfileError that is
ErrUnsupportedICCProfile to errors.Is; whole-slide images often carry one.
An image with no profile is taken to be in the space its Color Space
(0028,2002) names, otherwise sRGB.
Render many frames
RenderFrames returns every frame at once. RenderEachFrame hands each to a
function as it is made and lets it go, and decodes a compressed image once:
err := ds.RenderEachFrame(nil, func(frame int, img image.Image) error {
fmt.Println("frame", frame, img.Bounds())
return nil
})For an image too large to hold, read the header with SkipBulkData and render
from the file with RenderFramesFrom. A native frame is read in bands of rows,
about a megabyte at a time, so memory follows a band and not the frame:
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
}
frames, err := df.FrameReader(df.ValueSource(f))
if err != nil {
return err
}
ds := df.GetDataset()
err = ds.RenderFramesFrom(frames, []int{0, 1}, &dataset.RenderOptions{StoredRange: true},
func(frame int, img image.Image) error {
out, err := os.Create(fmt.Sprintf("frame-%d.png", frame+1))
if err != nil {
return err
}
if err := png.Encode(out, img); err != nil {
out.Close()
return err
}
return out.Close()
})The picture RenderFramesFrom hands over for a native frame draws its rows on
demand: read it only until the function returns. It is neither an
*image.Gray nor an *image.NRGBA, and image/jpeg codes a grayscale picture
in one component only when it is an *image.Gray, so copy it into one before
encoding it as JPEG. StoredRange saves reading every frame once beforehand to
find the range of an image without a window.
On the command line
$ go-dicom convert ct.dcm ct.png --format png --window 40,400
Wrote ct.png
$ go-dicom convert JPEG2000.dcm j.jpg --format jpeg --quality 85
Wrote j.jpg
$ go-dicom convert SC_rgb_rle_2frame.dcm frames.png --format png --frame all
Wrote frames-0001.png
Wrote frames-0002.png
$ go-dicom convert examples_rgb_color.dcm us-srgb.png --format png --icc srgb
Wrote us-srgb.pngconvert --format png|jpeg is RenderFrame, read a frame at a time and a
native frame a band at a time. --frame counts from 1. Without --icc the
image's own ICC profile goes into the PNG (iCCP) or JPEG (APP2) unchanged.
share renders the same picture and is meant for handing on: it refuses an
image that may hold burned-in text until you say where the text is, or that
there is none:
$ go-dicom share ct.dcm ct-share.png --window 40,400
Wrote ct-share.png
The picture holds pixels only: no name, date or identifier from the file is in it.
Nothing looked at the picture itself. Text drawn into it is still there unless you redacted it.
$ go-dicom share examples_rgb_color.dcm us.png
Error: share: examples_rgb_color.dcm may hold text burned into the pixels: its modality is US (ultrasound), and Burned In Annotation (0028,0301) does not say there is none. Give -redact x,y,width,height for where the text is, -redact auto to fill what a detector finds, -preview to see what it finds, or -allow-burned-in if there is none-redact, -redact auto, -preview and -detect are described in
De-identification.
Note
A PNG or JPEG holds pixels only, apart from an ICC profile. None of the file's attributes go into it; text burned into the picture does.
Assemble a volume
volume.Assemble puts the data sets of a series in stack order and checks that
they form a regular stack: one slice after another along their normal, evenly
spaced, the same size, no tilt. It reads geometry only, so the data sets need
not hold Pixel Data. An Enhanced CT, Enhanced MR or Legacy Converted
multi-frame image gives a slice for each frame.
var series []*dataset.Dataset
for _, p := range paths {
ds, err := readHeader(p) // ReadDICOMFileWithOptions with SkipBulkData, then GetDataset
if err != nil {
return err
}
series = append(series, ds)
}
v, err := volume.Assemble(series, volume.Options{})
var refused *volume.Error
if errors.As(err, &refused) {
return fmt.Errorf("not a regular stack: %s (slice %d): %s", refused.Kind, refused.Source, refused.Detail)
}
if err != nil {
return err
}
fmt.Println(len(v.Frames), "slices,", v.Rows, "x", v.Columns, "spacing", v.Spacing, "mm")
for i, fr := range v.Frames {
fmt.Printf("slice %d: %s at %.1f mm\n", i, filepath.Base(paths[fr.Source]), fr.Offset)
}On the five slices of dicomdirtests/98892001/CT5N in pydicom's test files:
5 slices, 16 x 16 spacing 2.5 mm
slice 0: 3353 at 0.0 mm
slice 1: 3023 at 2.5 mm
slice 2: 2693 at 5.0 mm
slice 3: 2392 at 7.5 mm
slice 4: 2062 at 10.0 mmVolume holds Rows, Columns, PixelSpacing, Orientation, Normal,
Spacing, the pixel Padding and the Frames in order, each with the index
of its data set (Source), its frame (Index), Position and Offset.
v.ReadFrame(read, i) gets slice i's pixels through a function of yours, so
the pixels can stay on disk until they are wanted.
What Assemble refuses
A series that is not a regular stack is refused with a *volume.Error;
volume.IsKind(err, kind) tests for one. On other series of the same test
files:
| Kind | Meaning | Example |
|---|---|---|
KindNoSlices | An empty series | |
KindMissingGeometry | Image Position, Image Orientation, Pixel Spacing, Rows or Columns missing or malformed | missing geometry (slice 0): Rows (0028,0010) or Columns (0028,0011) is missing |
KindMixedGeometry | Slices differ in Rows, Columns, Pixel Spacing, orientation or padding | mixed geometry (slice 1): Pixel Spacing [1.171875 1.171875], where data set 0 has [1.367188 1.367188] |
KindDuplicatePosition | Two slices at one position | |
KindGap | A slice or more missing | gap (slice 1): 202.5 mm from the slice before it, where the usual is 1.25 mm |
KindUnevenSpacing | Distances that differ, not by a whole number of slices | |
KindTilt | Gantry tilt, or slices stacked off their normal |
Options.SpacingTolerance (millimeters, default 0.01) and AngleTolerance
(degrees, default 0.1) set how strict it is. The package does not resample:
a refused series is yours to resample, or to report.
Overlays
The overlays package holds overlay groups, ROIs and graphics in memory
(overlays.NewOverlayManager), and extracts and merges bit planes. It does not
read overlays from a data set, and RenderFrame does not draw them: an
overlay plane (60xx,3000) in a file is not in the rendered picture.
Limits and gotchas
- 8 bits out. Rendering is for display. For measurements use the samples (Pixel data).
- Refused: 64-bit samples, a Presentation LUT Shape other than IDENTITY or
INVERSE, an ICC profile of lookup tables when
ColorSpaceis set, and any frame the library cannot decode (ErrUndecodedSyntax). - Without a window the range is the data's, found across all frames. Two
series rendered that way are not on the same scale; use
WindoworStoredRange. ApplyWindowingis notRenderFrame. It reads samples as unsigned and applies no rescale.- Overlays and burned-in text. Overlay planes are not drawn; burned-in text is part of the pixels and is rendered.
What is applied and what is not is listed in CONFORMANCE.md §8.1.
See also
- Pixel data
- De-identification: redacting burned-in text before sharing a picture
- Examples: make a picture
- dataset.RenderFrame, volume on pkg.go.dev
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.
De-identification
How go-dicom removes identifying information from DICOM files: the PS3.15 Annex E profiles and what each one changes, per-attribute overrides and templates, UID remapping, recording the method, and text burned into the pixels. It is for anyone preparing data to leave the place it was made, and it says plainly what is not removed.