dcmstack Package

dcmstack Package

Package for stacking DICOM images into multi dimensional volumes, extracting the DICOM meta data, converting the result to Nifti files with the meta data stored in a header extension, and work with these extended Nifti files.

dcmstack Module

Stack DICOM datasets into volumes. The contents of this module are imported into the package namespace.

class dcmstack.dcmstack.DicomOrdering(key, abs_ordering=None, abs_as_str=False)

Bases: object

Object defining an ordering for a set of dicom datasets. Create a DicomOrdering with the given DICOM element keyword.

Parameters :

key : str

The DICOM keyword to use for ordering the datasets

abs_ordering : sequence

A sequence specifying the absolute order for values corresponding to the key. Instead of ordering by the value associated with the key, the index of the value in this sequence will be used.

abs_as_str : bool

If true, the values will be converted to strings before looking up the index in abs_ordering.

Methods

get_ordinate(ds) Get the ordinate for the given DICOM data set.
get_ordinate(ds)

Get the ordinate for the given DICOM data set.

Parameters :

ds : dict like

The DICOM data set we want the ordinate of. Should allow dict like access where DICOM keywords return the corresponing value.

Returns :

An ordinate for the data set. If `abs_ordering` is None then this will :

just be the value for the keyword `key`. Otherwise it will be an :

integer. :

class dcmstack.dcmstack.DicomStack(time_order=None, vector_order=None, allow_dummies=False, meta_filter=None)

Bases: object

Defines a method for stacking together DICOM data sets into a multi dimensional volume.

Tailored towards creating NiftiImage output, but can also just create numpy arrays. Can summarize all of the meta data from the input DICOM data sets into a Nifti header extension (see dcmmeta.DcmMetaExtension).

Parameters :

time_order : str or DicomOrdering

The DICOM keyword or DicomOrdering object specifying how to order the DICOM data sets along the time dimension.

vector_order : str or DicomOrdering

The DICOM keyword or DicomOrdering object specifying how to order the DICOM data sets along the vector dimension.

allow_dummies : bool

If True then data sets without pixel data can be added to the stack. The “dummy” voxels will have the maximum representable value for the datatype.

meta_filter : callable

A callable that takes a meta data key and value, and returns True if that meta data element should be excluded from the DcmMeta extension.

Notes

If both time_order and vector_order are None, the time_order will be guessed based off the data sets.

Methods

add_dcm(dcm[, meta]) Add a pydicom dataset to the stack.
clear() Remove any DICOM datasets from the stack.
get_affine() Get the affine transform for mapping row/column/slice indices
get_data() Get an array of the voxel values.
get_shape() Get the shape of the stack.
to_nifti([voxel_order, embed_meta]) Returns a NiftiImage with the data and affine from the stack.
to_nifti_wrapper([voxel_order]) Convienance method.
add_dcm(dcm, meta=None)

Add a pydicom dataset to the stack.

Parameters :

dcm : dicom.dataset.Dataset

The data set being added to the stack

meta : dict

The extracted meta data for the DICOM data set dcm. If None extract.default_extractor will be used.

Raises :

IncongruentImageError :

The provided dcm does not match the orientation or dimensions of those already in the stack.

ImageCollisionError :

The provided dcm has the same slice location and time/vector values.

clear()

Remove any DICOM datasets from the stack.

get_affine()

Get the affine transform for mapping row/column/slice indices to Nifti (RAS) patient space.

Returns :

A 4x4 numpy array containing the affine transform. :

Raises :

InvalidStackError :

The stack is incomplete or invalid.

get_data()

Get an array of the voxel values.

Returns :

A numpy array filled with values from the DICOM data sets’ pixels. :

Raises :

InvalidStackError :

The stack is incomplete or invalid.

get_shape()

Get the shape of the stack.

Returns :

A tuple of integers giving the size of the dimensions of the stack. :

Raises :

InvalidStackError :

The stack is incomplete or invalid.

sort_guesses = ['EchoTime', 'InversionTime', 'RepetitionTime', 'FlipAngle', 'TriggerTime', 'AcquisitionTime', 'ContentTime', 'AcquisitionNumber', 'InstanceNumber']

The meta data keywords used when trying to guess the sorting order. Keys that come earlier in the list are given higher priority.

to_nifti(voxel_order='LAS', embed_meta=False)

Returns a NiftiImage with the data and affine from the stack.

Parameters :

voxel_order : str

A three character string repsenting the voxel order in patient space (see the function reorder_voxels).

embed_meta : bool

If true a dcmmeta.DcmMetaExtension will be embedded in the Nifti header.

Returns :

A nibabel.nifti1.Nifti1Image created with the stack’s data and affine. :

to_nifti_wrapper(voxel_order='')

Convienance method. Calls to_nifti and returns a NiftiWrapper generated from the result.

exception dcmstack.dcmstack.ImageCollisionError

Bases: exceptions.Exception

An exception denoting that a DICOM which collides with one already in the stack was passed to a DicomStack.add_dcm.

dcmstack.dcmstack.axcodes2ornt(axcodes, labels=None)

Convert axis codes axcodes to an orientation

Parameters :

axcodes : (N,) tuple

axis codes - see ornt2axcodes docstring

labels : optional, None or sequence of (2,) sequences

(2,) sequences are labels for (beginning, end) of output axis. That is, if the first element in axcodes is front, and the second (2,) sequence in labels is (‘back’, ‘front’) then the first row of ornt will be [1, 1]. If None, equivalent to (('L','R'),('P','A'),('I','S')) - that is - RAS axes.

Returns :

ornt : (N,2) array-like

oritation array - see io_orientation docstring

Examples

>>> axcodes2ornt(('F', 'L', 'U'), (('L','R'),('B','F'),('D','U')))
[[1, 1],[0,-1],[2,1]]
dcmstack.dcmstack.dcm_time_to_sec(time_str)

Convert a DICOM time value (value representation of ‘TM’) to the number of seconds past midnight.

Parameters :

time_str : str

The DICOM time value string

Returns :

A floating point representing the number of seconds past midnight :

dcmstack.dcmstack.default_group_keys = ('SeriesInstanceUID', 'SeriesNumber', 'ProtocolName')

Default keys for grouping DICOM files from the same acquisition together.

dcmstack.dcmstack.default_key_excl_res = ['Patient', 'Physician', 'Operator', 'Date', 'Birth', 'Address', 'Institution', 'Station', 'SiteName', 'Age', 'Comment', 'Phone', 'Telephone', 'Insurance', 'Religious', 'Language', 'Military', 'MedicalRecord', 'Ethnic', 'Occupation', 'Unknown', 'PrivateTagData', 'UID', 'StudyDescription', 'DeviceSerialNumber', 'ReferencedImageSequence', 'RequestedProcedureDescription', 'PerformedProcedureStepDescription', 'PerformedProcedureStepID']

A list of regexes passed to make_key_regex_filter as exclude_res to create the default_meta_filter.

dcmstack.dcmstack.default_key_incl_res = ['ImageOrientationPatient', 'ImagePositionPatient']

A list of regexes passed to make_key_regex_filter as force_include_res to create the default_meta_filter.

dcmstack.dcmstack.default_meta_filter(key, value)

Default meta_filter for DicomStack.

dcmstack.dcmstack.make_key_regex_filter(exclude_res, force_include_res=None)

Make a meta data filter using regular expressions.

Parameters :

exclude_res : sequence

Sequence of regular expression strings. Any meta data where the key matches one of these expressions will be excluded, unless it matches one of the force_include_res.

force_include_res : sequence

Sequence of regular expression strings. Any meta data where the key matches one of these expressions will be included.

Returns :

A callable which can be passed to `DicomStack` as the `meta_filter`. :

dcmstack.dcmstack.ornt_transform(start_ornt, end_ornt)

Return the orientation that transforms from start_ornt to end_ornt.

Parameters :

start_ornt : (n,2) orientation array

Initial orientation.

end_ornt : (n,2) orientation array

Final orientation.

Returns :

orientations : (p, 2) ndarray

The orientation that will transform the start_ornt to the end_ornt.

dcmstack.dcmstack.parse_and_group(src_paths, group_by=('SeriesInstanceUID', 'SeriesNumber', 'ProtocolName'), extractor=None, force=False, warn_on_except=False)

Parse the given dicom files and group them together. Each group is stored as a (list) value in a dict where the key is a tuple of values corresponding to the keys in ‘group_by’

Parameters :

src_paths : sequence

A list of paths to the source DICOM files.

group_by : tuple

Meta data keys to group data sets with. Any data set with the same values for these keys will be grouped together. This tuple of values will also be the key in the result dictionary.

extractor : callable

Should take a dicom.dataset.Dataset and return a dictionary of the extracted meta data.

force : bool

Force reading source files even if they do not appear to be DICOM.

warn_on_except : bool

Convert exceptions into warnings, possibly allowing some results to be returned.

Returns :

groups : dict

A dict mapping tuples of values (corresponding to ‘group_by’) to groups of data sets. Each element in the list is a tuple containing the dicom object, the parsed meta data, and the filename.

dcmstack.dcmstack.parse_and_stack(src_paths, group_by=('SeriesInstanceUID', 'SeriesNumber', 'ProtocolName'), extractor=None, force=False, warn_on_except=False, **stack_args)

Parse the given dicom files into a dictionary containing one or more DicomStack objects.

Parameters :

src_paths : sequence

A list of paths to the source DICOM files.

group_by : tuple

Meta data keys to group data sets with. Any data set with the same values for these keys will be grouped together. This tuple of values will also be the key in the result dictionary.

extractor : callable

Should take a dicom.dataset.Dataset and return a dictionary of the extracted meta data.

force : bool

Force reading source files even if they do not appear to be DICOM.

warn_on_except : bool

Convert exceptions into warnings, possibly allowing some results to be returned.

stack_args : kwargs

Keyword arguments to pass to the DicomStack constructor.

dcmstack.dcmstack.reorder_voxels(vox_array, affine, voxel_order)

Reorder the given voxel array and corresponding affine.

Parameters :

vox_array : array

The array of voxel data

affine : array

The affine for mapping voxel indices to Nifti patient space

voxel_order : str

A three character code specifing the desired starting point for rows, columns, and slices in terms of the orthogonal axes of patient space: (l)eft, (r)ight, (a)nterior, (p)osterior, (s)uperior, and (i)nferior.

Returns :

out_vox : array

An updated view of vox_array.

out_aff : array

A new array with the updated affine

reorient_transform : array

The transform used to update the affine.

ornt_trans : tuple

The orientation transform used to update the orientation.

dcmmeta Module

DcmMeta header extension and NiftiWrapper for working with extended Niftis.

exception dcmstack.dcmmeta.MissingExtensionError

Bases: exceptions.Exception

Exception denoting that there is no DcmMetaExtension in the Nifti header.

class dcmstack.dcmmeta.NiftiWrapper(nii_img, make_empty=False)

Bases: object

Wraps a Nifti1Image object containing a DcmMeta header extension. Provides access to the meta data and the ability to split or merge the data array while updating the meta data.

Parameters :

nii_img : nibabel.nifti1.Nifti1Image

The Nifti1Image to wrap.

make_empty : bool

If True an empty DcmMetaExtension will be created if none is found.

Raises :

MissingExtensionError :

No valid DcmMetaExtension was found.

ValueError :

More than one valid DcmMetaExtension was found.

Methods

from_dicom(klass, dcm_data[, meta_dict]) Create a NiftiWrapper from a single DICOM dataset.
from_dicom_wrapper(klass, dcm_wrp[, meta_dict]) Create a NiftiWrapper from a nibabel DicomWrapper.
from_filename(klass, path) Create a NiftiWrapper from a file.
from_sequence(klass, seq[, dim]) Create a NiftiWrapper by joining a sequence of NiftiWrapper objects
get_meta(key[, index, default]) Return the meta data value for the provided key.
meta_valid(classification) Return true if the meta data with the given classification appears
remove_extension() Remove the DcmMetaExtension from the header of nii_img. The
replace_extension(dcmmeta_ext) Replace the DcmMetaExtension.
split([dim]) Generate splits of the array and meta data along the specified dimension.
to_filename(out_path) Write out the wrapped Nifti to a file
classmethod from_dicom(klass, dcm_data, meta_dict=None)

Create a NiftiWrapper from a single DICOM dataset.

Parameters :

dcm_data : dicom.dataset.Dataset

The DICOM dataset to convert into a NiftiWrapper.

meta_dict : dict

An optional dictionary of meta data extracted from dcm_data. See the extract module for generating this dict.

classmethod from_dicom_wrapper(klass, dcm_wrp, meta_dict=None)

Create a NiftiWrapper from a nibabel DicomWrapper.

Parameters :

dcm_wrap : nicom.dicomwrappers.DicomWrapper

The dataset to convert into a NiftiWrapper.

meta_dict : dict

An optional dictionary of meta data extracted from dcm_data. See the extract module for generating this dict.

classmethod from_filename(klass, path)

Create a NiftiWrapper from a file.

Parameters :

path : str

The path to the Nifti file to load.

classmethod from_sequence(klass, seq, dim=None)

Create a NiftiWrapper by joining a sequence of NiftiWrapper objects along the given dimension.

Parameters :

seq : sequence

The sequence of NiftiWrapper objects.

dim : int

The dimension to join the NiftiWrapper objects along. If None, 2D inputs will become 3D, 3D inputs will become 4D, and 4D inputs will become 5D.

Returns :

result : NiftiWrapper

The merged NiftiWrapper with updated meta data.

get_meta(key, index=None, default=None)

Return the meta data value for the provided key.

Parameters :

key : str

The meta data key.

index : tuple

The voxel index we are interested in.

default :

This will be returned if the meta data for key is not found.

Returns :

value :

The meta data value for the given key (and optionally index)

Notes

The per-sample and per-slice meta data will only be considered if the samples_valid and slices_valid methods return True (respectively), and an index is specified.

meta_valid(classification)

Return true if the meta data with the given classification appears to be valid for the wrapped Nifti image. Considers the shape and orientation of the image and the meta data extension.

remove_extension()

Remove the DcmMetaExtension from the header of nii_img. The attribute meta_ext will still point to the extension.

replace_extension(dcmmeta_ext)

Replace the DcmMetaExtension.

Parameters :

dcmmeta_ext : DcmMetaExtension

The new DcmMetaExtension.

split(dim=None)

Generate splits of the array and meta data along the specified dimension.

Parameters :

dim : int

The dimension to split the voxel array along. If None it will prefer the vector, then time, then slice dimensions.

Returns :

result :

Generator which yields a NiftiWrapper result for each index along dim.

to_filename(out_path)

Write out the wrapped Nifti to a file

Parameters :

out_path : str

The path to write out the file to

Notes

Will check that the DcmMetaExtension is valid before writing the file.

dcmstack.dcmmeta.is_constant(sequence, period=None)

Returns true if all elements in (each period of) the sequence are equal.

Parameters :

sequence : sequence

The sequence of elements to check.

period : int

If not None then each subsequence of that length is checked.

dcmstack.dcmmeta.is_repeating(sequence, period)

Returns true if the elements in the sequence repeat with the given period.

Parameters :

sequence : sequence

The sequence of elements to check.

period : int

The period over which the elements should repeat.

dcmstack.dcmmeta.patch_dcm_ds_is(dcm)

Convert all elements in dcm with VR of ‘DS’ or ‘IS’ to floats and ints. This is a hackish work around for the backwards incompatability of pydicom 0.9.7 and should not be needed once nibabel is updated.

extract Module

Extract meta data from a DICOM data set.

class dcmstack.extract.MetaExtractor(ignore_rules=None, translators=None, conversions=None, warn_on_trans_except=True)

Bases: object

Callable object for extracting meta data from a dicom dataset. Initialize with a set of ignore rules, translators, and type conversions.

Parameters :

ignore_rules : sequence

A sequence of callables, each of which should take a DICOM element and return True if it should be ignored. If None the module default is used.

translators : sequence

A sequence of Translator objects each of which can convert a DICOM element into a dictionary. Overrides any ignore rules. If None the module default is used.

conversions : dict

Mapping of DICOM value representation (VR) strings to callables that perform some conversion on the value

warn_on_trans_except : bool

Convert any exceptions from translators into warnings.

class dcmstack.extract.Translator

Bases: tuple

A namedtuple for storing the four elements of a translator: a name, the dicom.tag.Tag that can be translated, the private creator string (optional), and the function which takes the DICOM element and returns a dictionary.

Methods

count(...)
index((value, [start, ...) Raises ValueError if the value is not present.
name

Alias for field number 0

priv_creator

Alias for field number 2

tag

Alias for field number 1

trans_func

Alias for field number 3

dcmstack.extract.csa_image_trans = Translator(name='CsaImage', tag=(0029, 1010), priv_creator='SIEMENS CSA HEADER', trans_func=<function csa_image_trans_func at 0x390e050>)

Translator for the CSA image sub header.

dcmstack.extract.csa_image_trans_func(elem)

Function for translating the CSA image sub header.

dcmstack.extract.csa_series_trans = Translator(name='CsaSeries', tag=(0029, 1020), priv_creator='SIEMENS CSA HEADER', trans_func=<function csa_series_trans_func at 0x390e2a8>)

Translator for parsing the CSA series sub header.

dcmstack.extract.csa_series_trans_func(elem)

Function for parsing the CSA series sub header.

dcmstack.extract.default_extractor = <dcmstack.extract.MetaExtractor object at 0x390bc10>

The default MetaExtractor.

dcmstack.extract.default_ignore_rules = (<function ignore_private at 0x3912b90>, <function ignore_non_ascii_bytes at 0x3912c08>)

The default tuple of ignore rules for MetaExtractor.

dcmstack.extract.default_translators = (Translator(name='CsaImage', tag=(0029, 1010), priv_creator='SIEMENS CSA HEADER', trans_func=<function csa_image_trans_func at 0x390e050>), Translator(name='CsaSeries', tag=(0029, 1020), priv_creator='SIEMENS CSA HEADER', trans_func=<function csa_series_trans_func at 0x390e2a8>))

Default translators for MetaExtractor.

dcmstack.extract.ignore_non_ascii_bytes(elem)

Ignore rule for MetaExtractor to skip elements with VR of ‘OW’, ‘OB’, or ‘UN’ if the byte string contains non ASCII characters.

dcmstack.extract.ignore_private(elem)

Ignore rule for MetaExtractor to skip private DICOM elements (odd group number).

dcmstack.extract.parse_phoenix_prot(prot_key, prot_val)

Parse the MrPheonixProtocol string.

Parameters :

prot_str : str

The ‘MrPheonixProtocol’ string from the CSA Series sub header.

Returns :

prot_dict : OrderedDict

Meta data pulled from the ASCCONV section.

Raises :

PhoenixParseError : A line of the ASCCONV section could not be parsed.

dcmstack.extract.simplify_csa_dict(csa_dict)

Simplify the result of nibabel.nicom.csareader.

Parameters :

csa_dict : dict

The result from nibabel.nicom.csareader

Returns :

result : OrderedDict

Result where the keys come from the ‘tags’ sub dictionary of csa_dict. The values come from the ‘items’ within that tags sub sub dictionary. If items has only one element it will be unpacked from the list.

dcmstack.extract.tag_to_str(tag)

Convert a DICOM tag to a string representation using the group and element hex values seprated by an underscore.

dcmstack.extract.tm_to_seconds(time_str)

Convert a DICOM time value (value representation of ‘TM’) to the number of seconds past midnight.

Parameters :

time_str : str

The DICOM time value string

Returns :

A floating point representing the number of seconds past midnight :

dcmstack.extract.unpack_vr_map = {'SS': 'h', 'US': 'H', 'UL': 'I', 'FD': 'd', 'SL': 'i', 'US or SS': 'H', 'FL': 'f'}

Dictionary mapping value representations to corresponding format strings for the struct.unpack function.

Project Versions

Table Of Contents

Previous topic

API Documentation

This Page