| Title: | Read, Write and Decode DICOM Medical Image Files |
|---|---|
| Description: | A native reader and writer for DICOM (Digital Imaging and Communications in Medicine) files, the standard format for medical images, published by the National Electrical Manufacturers Association <https://www.dicomstandard.org/current>. Modeled on the 'Python' package 'pydicom' and checked against it. Parses the file format in C++ (implicit and explicit value representations, both byte orders, deflated data sets, nested sequences and encapsulated pixel data), gives keyword and tag based access to data elements, writes data sets back to disk, and decodes pixel data into R arrays: uncompressed, RLE Lossless and JPEG Baseline (through 'libjpeg'), with YBR to RGB color conversion. Includes helpers for cardiac and other ultrasound, such as calibration from the Sequence of Ultrasound Regions and frame timing for cine loops. |
| Authors: | Matt Segar [aut, cre, cph], Darcy Mason [ctb, cph] (author of 'pydicom', from which the DICOM data dictionary is derived), pydicom contributors [ctb, cph] (DICOM data dictionary derived from 'pydicom') |
| Maintainer: | Matt Segar <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.1.0 |
| Built: | 2026-11-26 20:57:10 UTC |
| Source: | https://github.com/cran/dicomr |
One row per element, with sequence items flattened and marked by 'depth' and 'path'. Values are formatted as text in the 'value' column.
## S3 method for class 'dicom_dataset' as.data.frame(x, row.names = NULL, optional = FALSE, ...)## S3 method for class 'dicom_dataset' as.data.frame(x, row.names = NULL, optional = FALSE, ...)
x |
A 'dicom_dataset'. |
row.names, optional
|
Unused, for compatibility with the generic. |
... |
Unused. |
A data frame with columns 'tag', 'keyword', 'name', 'vr', 'vm', 'value', 'depth' and 'path'.
echo <- read_dicom(system.file("extdata", "echo_synthetic.dcm", package = "dicomr")) df <- as.data.frame(echo) head(df[, c("tag", "keyword", "vr", "value")])echo <- read_dicom(system.file("extdata", "echo_synthetic.dcm", package = "dicomr")) df <- as.data.frame(echo) head(df[, c("tag", "keyword", "vr", "value")])
Converts stored values to output units such as Hounsfield units, using Rescale Slope (0028,1053) and Rescale Intercept (0028,1052).
dcm_apply_rescale(arr, ds)dcm_apply_rescale(arr, ds)
arr |
An array from [dcm_pixel_array()]. |
ds |
The data set it came from. |
A double array.
ct <- read_dicom(system.file("extdata", "ct_synthetic.dcm", package = "dicomr")) hu <- dcm_apply_rescale(dcm_pixel_array(ct), ct) range(hu)ct <- read_dicom(system.file("extdata", "ct_synthetic.dcm", package = "dicomr")) hu <- dcm_apply_rescale(dcm_pixel_array(ct), ct) range(hu)
Runs pydicom (through Python) on the same file and compares every data element, including nested sequence items, and the decoded pixel array. Useful for checking your own files. Requires Python 3 with 'pydicom' and ‘numpy' installed, plus the ’jsonlite' package.
dcm_compare_pydicom( file, python = "python3", pixels = TRUE, jpeg_plugin = "pillow", ... )dcm_compare_pydicom( file, python = "python3", pixels = TRUE, jpeg_plugin = "pillow", ... )
file |
Path to a DICOM file. |
python |
The Python executable. |
pixels |
Also compare the decoded pixel arrays. |
jpeg_plugin |
pydicom decoding plugin for JPEG Baseline/Extended data: '"pillow"' (the default, which 'jpeg_mode = "pydicom"' reproduces) or '"pylibjpeg"', or '"default"' to let pydicom choose. |
... |
Passed to [dcm_pixel_array()], for example 'jpeg_mode'. |
A list with 'elements' (number compared), 'issues' (a data frame of differences), and 'pixels': a list with 'status' ("equal", "close", "different", "pydicom_failed", "dicomr_failed", "both_failed" or "none"), 'max_abs_diff', 'fraction_equal' and any error messages.
# Needs Python 3 with pydicom and numpy, so it is not run here ## Not run: r <- dcm_compare_pydicom(system.file("extdata", "ct_synthetic.dcm", package = "dicomr")) r$issues r$pixels$status ## End(Not run)# Needs Python 3 with pydicom and numpy, so it is not run here ## Not run: r <- dcm_compare_pydicom(system.file("extdata", "ct_synthetic.dcm", package = "dicomr")) r$issues r$pixels$status ## End(Not run)
File level information of a data set read from disk
dcm_file_meta(ds) dcm_transfer_syntax(ds)dcm_file_meta(ds) dcm_transfer_syntax(ds)
ds |
A 'dicom_dataset' from [read_dicom()]. |
'dcm_file_meta()' returns the File Meta Information (group 0002) as a 'dicom_dataset'. 'dcm_transfer_syntax()' returns the transfer syntax UID with its name as the 'name' attribute.
ct <- read_dicom(system.file("extdata", "ct_synthetic.dcm", package = "dicomr")) dcm_transfer_syntax(ct) dcm_file_meta(ct)ct <- read_dicom(system.file("extdata", "ct_synthetic.dcm", package = "dicomr")) dcm_transfer_syntax(ct) dcm_file_meta(ct)
Returns the time of each frame in milliseconds from the first frame, from Frame Time Vector (0018,1065) if present, otherwise Frame Time (0018,1063), otherwise Cine Rate (0018,0040) or Recommended Display Frame Rate.
dcm_frame_times(ds)dcm_frame_times(ds)
ds |
A 'dicom_dataset'. |
A numeric vector with one time per frame (ms), or 'NULL' if the file has no timing information. The frame rate (frames per second) is in the 'frame_rate' attribute.
echo <- read_dicom(system.file("extdata", "echo_synthetic.dcm", package = "dicomr")) dcm_frame_times(echo)echo <- read_dicom(system.file("extdata", "echo_synthetic.dcm", package = "dicomr")) dcm_frame_times(echo)
‘dcm_get()' returns an element’s value, 'dcm_element()' the whole element (group, element, VR and value), 'dcm_has()' tests for presence, and 'dcm_set()' adds or replaces an element. The usual R operators also work: 'ds$PatientName', 'ds[["PatientName"]]', 'ds[["0010,0010"]]', 'ds[[c(0x0010, 0x0010)]]', and the same forms on the left of '<-'. Assigning 'NULL' removes the element.
dcm_get(ds, tag, default = NULL) dcm_element(ds, tag) dcm_has(ds, tag) dcm_set(ds, tag, value, vr = NULL)dcm_get(ds, tag, default = NULL) dcm_element(ds, tag) dcm_has(ds, tag) dcm_set(ds, tag, value, vr = NULL)
ds |
A 'dicom_dataset'. |
tag |
A keyword or tag (see [dcm_tag()]). |
default |
Returned when the element is absent. |
value |
The new value. |
vr |
The value representation. Taken from the existing element or the dictionary when missing; required for private tags. |
'dcm_get()' the value; 'dcm_element()' a 'dicom_element' or 'NULL'; 'dcm_has()' a logical; 'dcm_set()' the modified data set.
ct <- read_dicom(system.file("extdata", "ct_synthetic.dcm", package = "dicomr")) dcm_get(ct, "Modality") dcm_get(ct, "(0028,1050)") # Window Center dcm_get(ct, "BodyPartExamined", default = NA) dcm_has(ct, "PixelData") dcm_element(ct, "PixelSpacing") ct <- dcm_set(ct, "BodyPartExamined", "HEAD") ct$PatientName <- "Anonymous" ct$PatientNamect <- read_dicom(system.file("extdata", "ct_synthetic.dcm", package = "dicomr")) dcm_get(ct, "Modality") dcm_get(ct, "(0028,1050)") # Window Center dcm_get(ct, "BodyPartExamined", default = NA) dcm_has(ct, "PixelData") dcm_element(ct, "PixelSpacing") ct <- dcm_set(ct, "BodyPartExamined", "HEAD") ct$PatientName <- "Anonymous" ct$PatientName
Keywords of the elements in a data set
dcm_keywords(ds)dcm_keywords(ds)
ds |
A 'dicom_dataset'. |
A character vector (empty strings for private or unknown tags).
ct <- read_dicom(system.file("extdata", "ct_synthetic.dcm", package = "dicomr")) head(dcm_keywords(ct))ct <- read_dicom(system.file("extdata", "ct_synthetic.dcm", package = "dicomr")) head(dcm_keywords(ct))
Returns pixel data with the same axis order as pydicom's 'pixel_array': 'frames x rows x columns x samples'. With 'drop = TRUE' (the default) the frame axis is dropped for single-frame images and the sample axis is dropped for monochrome images, so a single-frame greyscale image is a 'rows x columns' matrix and a 30-frame colour echo clip is a '30 x rows x columns x 3' array. 'arr[f, r, c, s]' in R is 'arr[f-1, r-1, c-1, s-1]' in Python.
dcm_pixel_array( ds, frames = NULL, as_rgb = TRUE, drop = TRUE, correct_unused_bits = FALSE, jpeg_mode = c("pydicom", "accurate") )dcm_pixel_array( ds, frames = NULL, as_rgb = TRUE, drop = TRUE, correct_unused_bits = FALSE, jpeg_mode = c("pydicom", "accurate") )
ds |
A 'dicom_dataset' from [read_dicom()]. |
frames |
Optional 1-based frame numbers to decode, for example '1:10'. Only these frames are decoded, which saves time and memory on long cine loops. |
as_rgb |
Convert YBR colour data to RGB. |
drop |
Drop length-one frame and sample axes as pydicom does. |
correct_unused_bits |
Clear (or sign-extend) the bits above Bits Stored. pydicom's default is 'FALSE'. |
jpeg_mode |
How to decode colour JPEG. '"pydicom"' (the default) reproduces pydicom with its Pillow plugin exactly: libjpeg-turbo decodes without a colour transform, then pydicom's YBR to RGB formula is applied. Use it when results must match a Python pipeline, such as a model trained on pydicom output. '"accurate"' lets libjpeg-turbo do the colour conversion in integer arithmetic; values can differ from '"pydicom"' by a grey level or two. |
Supported encodings: uncompressed (implicit/explicit VR, little/big endian, deflated), RLE Lossless, and 8-bit JPEG Baseline / Extended through libjpeg-turbo. YBR_FULL and YBR_FULL_422 data are converted to RGB when 'as_rgb = TRUE', using the same float formula as pydicom.
The values are the stored values. Apply [dcm_apply_rescale()] for Hounsfield units and similar.
An integer array (double for 32-bit unsigned or float data), with attribute 'photometric_interpretation' giving the colour space of the returned values.
echo <- read_dicom(system.file("extdata", "echo_synthetic.dcm", package = "dicomr")) clip <- dcm_pixel_array(echo) # frames x rows x cols x 3 dim(clip) first <- dcm_pixel_array(echo, frames = 1) # rows x cols x 3 dim(first) ct <- read_dicom(system.file("extdata", "ct_synthetic.dcm", package = "dicomr")) dim(dcm_pixel_array(ct)) # rows x colsecho <- read_dicom(system.file("extdata", "echo_synthetic.dcm", package = "dicomr")) clip <- dcm_pixel_array(echo) # frames x rows x cols x 3 dim(clip) first <- dcm_pixel_array(echo, frames = 1) # rows x cols x 3 dim(first) ct <- read_dicom(system.file("extdata", "ct_synthetic.dcm", package = "dicomr")) dim(dcm_pixel_array(ct)) # rows x cols
Image geometry and pixel description
dcm_pixel_info(ds)dcm_pixel_info(ds)
ds |
A 'dicom_dataset'. |
A list with 'rows', 'columns', 'samples_per_pixel', 'frames', 'bits_allocated', 'bits_stored', 'pixel_representation', 'planar_configuration', 'photometric_interpretation' and 'transfer_syntax'.
echo <- read_dicom(system.file("extdata", "echo_synthetic.dcm", package = "dicomr")) str(dcm_pixel_info(echo))echo <- read_dicom(system.file("extdata", "echo_synthetic.dcm", package = "dicomr")) str(dcm_pixel_info(echo))
The inverse of [dcm_pixel_array()]: writes 'arr' into Pixel Data and sets Rows, Columns, Samples per Pixel, Number of Frames, Bits Allocated/Stored, High Bit, Pixel Representation, Photometric Interpretation and Planar Configuration to match. The data set's transfer syntax becomes Explicit VR Little Endian if it was compressed.
dcm_set_pixel_data( ds, arr, photometric_interpretation = NULL, bits_allocated = NULL )dcm_set_pixel_data( ds, arr, photometric_interpretation = NULL, bits_allocated = NULL )
ds |
A 'dicom_dataset'. |
arr |
An integer array: 'rows x cols' (one greyscale frame), 'frames x rows x cols' (greyscale cine), 'rows x cols x 3' (one colour frame) or 'frames x rows x cols x 3'. |
photometric_interpretation |
'"MONOCHROME2"', '"MONOCHROME1"' or '"RGB"'. Guessed from the array when missing. |
bits_allocated |
8, 16 or 32. Chosen from the value range when missing. |
The modified data set.
img <- matrix(as.integer(seq(0, 4095, length.out = 64 * 64)), 64, 64) ds <- dicom_dataset(Modality = "OT") ds <- dcm_set_pixel_data(ds, img) ds$BitsAllocated identical(as.vector(dcm_pixel_array(ds)), as.vector(img))img <- matrix(as.integer(seq(0, 4095, length.out = 64 * 64)), 64, 64) ds <- dicom_dataset(Modality = "OT") ds <- dcm_set_pixel_data(ds, img) ds$BitsAllocated identical(as.vector(dcm_pixel_array(ds)), as.vector(img))
A quick look at one frame with base graphics.
dcm_show(ds, frame = 1, ...)dcm_show(ds, frame = 1, ...)
ds |
A 'dicom_dataset'. |
frame |
Frame number (1-based). |
... |
Passed to [graphics::plot()] (colour) or [graphics::image()] (greyscale). |
'NULL', invisibly.
echo <- read_dicom(system.file("extdata", "echo_synthetic.dcm", package = "dicomr")) dcm_show(echo, frame = 2) ct <- read_dicom(system.file("extdata", "ct_synthetic.dcm", package = "dicomr")) dcm_show(ct)echo <- read_dicom(system.file("extdata", "echo_synthetic.dcm", package = "dicomr")) dcm_show(echo, frame = 2) ct <- read_dicom(system.file("extdata", "ct_synthetic.dcm", package = "dicomr")) dcm_show(ct)
Accepts a keyword ('"PatientName"'), a tag string ('"(0010,0010)"', '"0010,0010"', '"00100010"', '"0x00100010"'), a single number ('0x00100010') or a group/element pair ('c(0x0010, 0x0010)').
dcm_tag(x) dcm_tag_number(x)dcm_tag(x) dcm_tag_number(x)
x |
A tag specification. |
'dcm_tag()' returns the tag as an 8-character hex string such as '"00100010"', which is how elements are named inside a data set. 'dcm_tag_number()' returns the tag as a number.
dcm_tag("PatientName") dcm_tag(c(0x0028, 0x0010)) dcm_tag("(7FE0,0010)") dcm_tag_number("Rows")dcm_tag("PatientName") dcm_tag(c(0x0028, 0x0010)) dcm_tag("(7FE0,0010)") dcm_tag_number("Rows")
Format a tag as "(gggg,eeee)"
dcm_tag_string(x)dcm_tag_string(x)
x |
A tag specification (see [dcm_tag()]). |
A character string.
dcm_tag_string("PatientName") dcm_tag_string(0x7FE00010)dcm_tag_string("PatientName") dcm_tag_string(0x7FE00010)
For 2D regions where both axes share units (cm in echo), returns the straight-line distance, for example a caliper measurement of an LV dimension. Both points must fall in the same region.
dcm_us_distance(ds, p1, p2, region = NULL)dcm_us_distance(ds, p1, p2, region = NULL)
ds |
A 'dicom_dataset' or a data frame from [dcm_us_regions()]. |
p1, p2
|
Points as 'c(row, col)', 1-based array indices. |
region |
Optional region number. |
A number with a 'units' attribute.
echo <- read_dicom(system.file("extdata", "echo_synthetic.dcm", package = "dicomr")) dcm_us_distance(echo, p1 = c(row = 5, col = 10), p2 = c(row = 25, col = 40))echo <- read_dicom(system.file("extdata", "echo_synthetic.dcm", package = "dicomr")) dcm_us_distance(echo, p1 = c(row = 5, col = 10), p2 = c(row = 25, col = 40))
Uses the ultrasound region that contains each point (or the one you name) to turn pixel positions into physical values: 'physical = reference_physical + (pixel - (region_origin + reference_pixel)) * delta'.
dcm_us_pixel_to_physical(ds, row, col, region = NULL)dcm_us_pixel_to_physical(ds, row, col, region = NULL)
ds |
A 'dicom_dataset', or a data frame from [dcm_us_regions()]. |
row, col
|
Pixel positions as R array indices (1-based), matching 'arr[row, col]' on a frame from [dcm_pixel_array()]. |
region |
Optional region number to use for every point. |
A data frame with 'row', 'col', 'region', 'x', 'y', 'units_x' and 'units_y'; 'x' runs across the image and 'y' down it.
echo <- read_dicom(system.file("extdata", "echo_synthetic.dcm", package = "dicomr")) dcm_us_pixel_to_physical(echo, row = c(1, 11), col = c(33, 33))echo <- read_dicom(system.file("extdata", "echo_synthetic.dcm", package = "dicomr")) dcm_us_pixel_to_physical(echo, row = c(1, 11), col = c(33, 33))
Parses the Sequence of Ultrasound Regions (0018,6011) into a data frame, one row per region. Each region says where it sits in the image (in 0-based pixel coordinates, as in the standard), what it shows (2D tissue, colour flow, spectral Doppler, M-mode, ECG trace...), and how pixels map to physical units: 'delta_x' and 'delta_y' are the physical size of one pixel in 'units_x' and 'units_y' (for 2D echo usually cm per pixel; for spectral Doppler usually seconds per pixel across and cm/sec per pixel up).
dcm_us_regions(ds)dcm_us_regions(ds)
ds |
A 'dicom_dataset'. |
A data frame (zero rows if the file has no regions).
echo <- read_dicom(system.file("extdata", "echo_synthetic.dcm", package = "dicomr")) reg <- dcm_us_regions(echo) reg[, c("region", "data_type_label", "delta_x", "units_x_label")]echo <- read_dicom(system.file("extdata", "echo_synthetic.dcm", package = "dicomr")) reg <- dcm_us_regions(echo) reg[, c("region", "data_type_label", "delta_x", "units_x_label")]
Create an empty data set or a sequence item
dicom_dataset(...)dicom_dataset(...)
... |
Named values, using DICOM keywords as names. |
A 'dicom_dataset'.
item <- dicom_dataset(PhysicalDeltaX = 0.03, PhysicalUnitsXDirection = 3L) ds <- dicom_dataset(Modality = "US", SequenceOfUltrasoundRegions = list(item)) dsitem <- dicom_dataset(PhysicalDeltaX = 0.03, PhysicalUnitsXDirection = 3L) ds <- dicom_dataset(Modality = "US", SequenceOfUltrasoundRegions = list(item)) ds
Look up tags or keywords in the DICOM data dictionary
dicom_dictionary(x)dicom_dictionary(x)
x |
Character keywords or tag specifications. If missing, the whole dictionary is returned. |
A data frame with columns 'tag', 'vr', 'vm', 'name', 'keyword' and 'retired'.
dicom_dictionary(c("PatientName", "PhysicalDeltaX", "(7FE0,0010)")) nrow(dicom_dictionary())dicom_dictionary(c("PatientName", "PhysicalDeltaX", "(7FE0,0010)")) nrow(dicom_dictionary())
Parses a DICOM Part 10 file (or a raw data set without the 128-byte preamble when 'force = TRUE') into a 'dicom_dataset'.
read_dicom(file, stop_before_pixels = FALSE, force = FALSE)read_dicom(file, stop_before_pixels = FALSE, force = FALSE)
file |
Path to the file, or a raw vector holding the file's bytes. |
stop_before_pixels |
If 'TRUE', stop reading at the Pixel Data element, which is much faster when you only need the header. |
force |
Read files that lack the "DICM" prefix. |
Values are converted to R types following pydicom: text VRs become character vectors (split on backslash), 'IS' becomes integer, 'DS', 'FL', 'FD', 'UL' become double, 'US', 'SS', 'SL' become integer, 'AT' becomes a hex tag string, 'SQ' becomes a list of data sets, and 'OB'/'OW'/'UN' and other binary VRs stay as raw vectors. Encapsulated (compressed) pixel data is kept as its fragments; decode it with [dcm_pixel_array()].
A 'dicom_dataset'. File level information is available with [dcm_file_meta()] and [dcm_transfer_syntax()].
f <- system.file("extdata", "echo_synthetic.dcm", package = "dicomr") ds <- read_dicom(f) ds$Modality ds[["(0028,0008)"]] # Number of Frames, by tag hdr <- read_dicom(f, stop_before_pixels = TRUE) dcm_has(hdr, "PixelData")f <- system.file("extdata", "echo_synthetic.dcm", package = "dicomr") ds <- read_dicom(f) ds$Modality ds[["(0028,0008)"]] # Number of Frames, by tag hdr <- read_dicom(f, stop_before_pixels = TRUE) dcm_has(hdr, "PixelData")
Writes a DICOM Part 10 file: 128-byte preamble, "DICM", the File Meta Information group (rebuilt with a correct group length), then the data set. Sequences are written with undefined lengths. Compressed pixel data is written back as it was read; changing between compressed and uncompressed transfer syntaxes is not supported.
write_dicom(ds, file, transfer_syntax = NULL)write_dicom(ds, file, transfer_syntax = NULL)
ds |
A 'dicom_dataset'. |
file |
Output path. |
transfer_syntax |
Transfer syntax UID. Defaults to the one the data set was read with, or Explicit VR Little Endian. Uncompressed data sets can be written as Implicit VR Little Endian ('"1.2.840.10008.1.2"'), Explicit VR Little Endian ('"1.2.840.10008.1.2.1"'), Explicit VR Big Endian ('"1.2.840.10008.1.2.2"') or Deflated ('"1.2.840.10008.1.2.1.99"'). |
The path, invisibly.
ct <- read_dicom(system.file("extdata", "ct_synthetic.dcm", package = "dicomr")) out <- tempfile(fileext = ".dcm") write_dicom(ct, out, transfer_syntax = "1.2.840.10008.1.2.1") dcm_transfer_syntax(read_dicom(out)) unlink(out)ct <- read_dicom(system.file("extdata", "ct_synthetic.dcm", package = "dicomr")) out <- tempfile(fileext = ".dcm") write_dicom(ct, out, transfer_syntax = "1.2.840.10008.1.2.1") dcm_transfer_syntax(read_dicom(out)) unlink(out)