dicomparser module

Class that parses and returns formatted DICOM RT data.

class dicompylercore.dicomparser.DicomParser(dataset, memmap_pixel_array=False)[source]

Bases: object

Class to parse DICOM / DICOM RT files.

Initialize DicomParser from a pydicom Dataset or DICOM file.

Parameters:
  • dataset (pydicom Dataset or filename) – pydicom dataset object or DICOM file location

  • memmap_pixel_array (bool, optional) – Enable pixel array access via memory mapping, by default False

Raises:
  • AttributeError – Raised if SOPClassUID is not present in the pydicom Dataset

  • AttributeError – Raised if the DICOM file or pydicom Dataset cannot be read

GetSOPClassUID()[source]

Determine the SOP Class UID of the current file.

GetSOPInstanceUID()[source]

Determine the SOP Class UID of the current file.

GetStudyInfo()[source]

Return the study information of the current file.

GetSeriesDateTime()[source]

Return the series date/time information.

GetSeriesInfo()[source]

Return the series information of the current file.

GetReferencedSeries()[source]

Return the SOP Class UID of the referenced series.

GetFrameOfReferenceUID()[source]

Determine the Frame of Reference UID of the current file.

GetReferencedStructureSet()[source]

Return the SOP Class UID of the referenced structure set.

GetReferencedRTPlan()[source]

Return the SOP Class UID of the referenced RT plan.

GetDemographics()[source]

Return the patient demographics from a DICOM file.

GetImageData()[source]

Return the image data from a DICOM file.

GetPixelArray()[source]

Generate a memory mapped numpy accessor to the pixel array.

property get_pixel_array

Generate a memory mapped numpy accessor to the pixel array.

GetImageLocation()[source]

Calculate the location of the current image slice.

GetImageOrientationType()[source]

Get the orientation of the current image slice.

GetNumberOfFrames()[source]

Return the number of frames in a DICOM image file.

GetRescaleInterceptSlope()[source]

Return the rescale intercept and slope if present.

GetImage(window=0, level=0, size=None, background=False, frames=0)[source]

Return the image from a DICOM image storage file.

Parameters:
  • window (int, optional) – Image window, by default 0

  • level (int, optional) – Image level or width, by default 0

  • size (tuple, optional) – Image size tuple in pixels, by default None

  • background (bool, optional) – Enable a black image background, by default False

  • frames (int, optional) – If multi-frame, use requested frame to generate image, by default 0

Returns:

A Pillow Image object

Return type:

Pillow Image

GetDefaultImageWindowLevel()[source]

Determine the default window/level for the DICOM image.

GetLUTValue(data, window, level)[source]

Apply the RGB Look-Up Table for the data and window/level value.

Parameters:
  • data (numpy array) – Pixel data array from pydicom dataset

  • window (float) – Image window value

  • level (float) – Image window level or width

Returns:

Modified numpy array with RGB LUT applied

Return type:

numpy array

GetPatientToPixelLUT()[source]

Get image transformation matrix from the DICOM standard.

Referenced matrix can be found in Part 3 Section C.7.6.2.1.1

GetStructureInfo()[source]

Return the patient demographics from a DICOM file.

GetStructures()[source]

Return a dictionary of structures (ROIs).

GetStructureCoordinates(roi_number)[source]

Get the list of coordinates for each plane of the structure.

Parameters:

roi_number (integer) – ROI number used to index structure from RT Struct

Returns:

Dict of structure coordinates sorted by slice position (z)

Return type:

dict

GetContourPoints(array)[source]

Unflatten a flattened list of xyz point triples.

Parameters:

array (list) – Flattened list of xyz point triples

Returns:

Unflattened list of xyz point triples

Return type:

list

CalculatePlaneThickness(planesDict)[source]

Calculate the plane thickness for each structure.

Parameters:

planesDict (dict) – Output from GetStructureCoordinates

Returns:

Thickness of the structure in mm

Return type:

float

CalculateStructureVolume(coords, thickness)[source]

Calculate the volume of the given structure.

Parameters:
  • coords (dict) – Coordinates of each plane of the structure

  • thickness (float) – Thickness of the structure in mm

Returns:

Volume of structure in cm3

Return type:

float

HasDVHs()[source]

Return whether dose-volume histograms (DVHs) exist.

GetDVHs()[source]

Return cumulative dose-volume histograms (DVHs).

GetDoseGrid(z=0, threshold=0.5)[source]

Return the 2d dose grid for the given slice position (mm).

Parameters:
  • z (int, optional) – Slice position in mm, by default 0

  • threshold (float, optional) – Threshold in mm to determine the max difference from z to the closest dose slice without using interpolation, by default 0.5

Returns:

An numpy 2d array of dose points

Return type:

np.array

InterpolateDosePlanes(uplane, lplane, fz)[source]

Interpolate a dose plane between two bounding planes.

Parameters:
  • uplane (float) – Upper dose plane boundary in mm

  • lplane (float) – Lower dose plane boundary in mm

  • fz (float) – Fractional distance from the bottom to the top, where the new plane is located. E.g. if fz = 1, the plane is at the upper plane, fz = 0, it is at the lower plane.

Returns:

An numpy 2d array of the interpolated dose plane

Return type:

numpy array

is_head_first_orientation()[source]

Return True if self.orientation is head-first.

Raises:

NotImplementedError – Raised if orientation is not one of head/feet-first and supine/prone/decubitus

Returns:

True if orientation is head-first, else False

Return type:

bool

x_lut_index()[source]

Return LUT index for real-world X direction.

Raises:

NotImplementedError – Raised if orientation is not one of head/feet-first and supine/prone/decubitus

Returns:

0 if real-world X across columns 1 if real-world X along rows

Return type:

X direction LUT index, matching ‘lut’ from GetDoseData

GetIsodosePoints(z=0, level=100, threshold=0.5)[source]

Return dose grid points from an isodose level & slice position.

Parameters:
  • z (int, optional) – Slice position in mm., by default 0

  • level (int, optional) – Isodose level in scaled form (multiplied by self.ds.DoseGridScaling), by default 100

  • threshold (float, optional) – Threshold in mm to determine the max difference from z to the closest dose slice without using interpolation, by default 0.5

Returns:

An list of tuples representing isodose points

Return type:

list

GetDoseData()[source]

Return the dose data from a DICOM RT Dose file.

GetReferencedBeamNumber()[source]

Return the referenced beam number (if it exists) from RT Dose.

GetPlan()[source]

Return the plan information.

GetReferencedBeamsInFraction(fx=0)[source]

Return the referenced beams from the specified fraction.

Parameters:

fx (int, optional) – FractionGroupSequence number, by default 0

Returns:

Dictionary of referenced beam data

Return type:

dict

dvh module

Class that stores dose volume histogram (DVH) data.

class dicompylercore.dvh.DVH(counts, bins, dvh_type='cumulative', dose_units='Gy', volume_units='cm3', rx_dose=None, name=None, color=None, notes=None)[source]

Bases: object

Class that stores dose volume histogram (DVH) data.

Initialization for a DVH from existing histogram counts and bins.

Parameters:
  • counts (iterable or numpy array) – An iterable of volume or percent count data

  • bins (iterable or numpy array) – An iterable of dose bins

  • dvh_type (str, optional) – Choice of ‘cumulative’ or ‘differential’ type of DVH

  • dose_units (str, optional) – Absolute dose units, i.e. ‘gy’ or relative units ‘%’

  • volume_units (str, optional) – Absolute volume units, i.e. ‘cm3’ or relative units ‘%’

  • rx_dose (number, optional) – Prescription dose value used to normalize dose bins (in Gy)

  • name (String, optional) – Name of the structure of the DVH

  • color (numpy array, optional) – RGB color triplet used for plotting the DVH

  • notes (String, optional) – Additional notes about the DVH instance

classmethod from_dicom_dvh(dataset, roi_num, rx_dose=None, name=None, color=None)[source]

Initialization for a DVH from a pydicom RT Dose DVH sequence.

classmethod from_data(data, binsize=1)[source]

Initialization for a DVH from raw data.

Parameters:
  • data (iterable or numpy array) – An iterable of dose data that is used to create the histogram

  • binsize (int, optional) – Bin width size (in cGy used to create the histogram)

property bincenters

Return a numpy array containing the bin centers.

property differential

Return a differential DVH from a cumulative DVH.

property cumulative

Return a cumulative DVH from a differential DVH.

absolute_dose(rx_dose=None, dose_units='Gy')[source]

Return an absolute dose DVH.

Parameters:
  • rx_dose (number, optional) – Prescription dose value used to normalize dose bins

  • dose_units (str, optional) – Units for the absolute dose

Raises:

AttributeError – Description

relative_dose(rx_dose=None)[source]

Return a relative dose DVH based on a prescription dose.

Parameters:

rx_dose (number, optional) – Prescription dose value used to normalize dose bins

Raises:

AttributeError – Raised if prescription dose was not present either during class initialization or passed via argument.

absolute_volume(volume, volume_units='cm3')[source]

Return an absolute volume DVH.

Parameters:
  • volume (number) – Absolute volume of the structure

  • volume_units (str, optional) – Units for the absolute volume

property relative_volume

Return a relative volume DVH.

property max

Return the maximum dose.

property min

Return the minimum dose.

property mean

Return the mean dose.

property volume

Return the volume of the structure.

describe()[source]

Describe a summary of DVH statistics in a text based format.

compare(dvh)[source]

Compare the DVH properties with another DVH.

Parameters:

dvh (DVH) – DVH instance to compare against

Raises:

AttributeError – If DVHs do not have equivalent dose & volume units

plot()[source]

Plot the DVH using Matplotlib if present.

volume_constraint(dose, dose_units=None)[source]

Calculate the volume that receives at least a specific dose.

i.e. V100, V150 or V20Gy

Parameters:

dose (number) – Dose value used to determine minimum volume that receives this dose. Can either be in relative or absolute dose units.

Returns:

Volume in self.volume_units units.

Return type:

number

dose_constraint(volume, volume_units=None)[source]

Calculate the maximum dose that a specific volume receives.

i.e. D90, D100 or D2cc

Parameters:

volume (number) – Volume used to determine the maximum dose that the volume receives. Can either be in relative or absolute volume units.

Returns:

Dose in self.dose_units units.

Return type:

number

statistic(name)[source]

Return a DVH dose or volume statistic.

Parameters:

name (str) – DVH statistic in the form of D90, D100, D2cc, V100 or V20Gy, etc.

Returns:

Value from the dose or volume statistic calculation.

Return type:

number

class dicompylercore.dvh.DVHValue(value, units='')[source]

Bases: object

Class that stores DVH values with the appropriate units.

Initialization for a DVH value that will also store units.

dvhcalc module

Calculate dose volume histogram (DVH) from DICOM RT Structure/Dose data.

dicompylercore.dvhcalc.get_dvh(structure, dose, roi, limit=None, calculate_full_volume=True, use_structure_extents=False, interpolation_resolution=None, interpolation_segments_between_planes=0, thickness=None, memmap_rtdose=False, callback=None)[source]

Calculate a cumulative DVH in Gy from a DICOM RT Structure Set & Dose.

Parameters:
  • structure (pydicom Dataset or filename) – DICOM RT Structure Set used to determine the structure data.

  • dose (pydicom Dataset or filename) – DICOM RT Dose used to determine the dose grid.

  • roi (int) – The ROI number used to uniquely identify the structure in the structure set.

  • limit (int, optional) – Dose limit in cGy as a maximum bin for the histogram.

  • calculate_full_volume (bool, optional) – Calculate the full structure volume including contours outside of the dose grid.

  • use_structure_extents (bool, optional) – Limit the DVH calculation to the in-plane structure boundaries.

  • interpolation_resolution (tuple or float, optional) – Resolution in mm (row, col) to interpolate structure and dose data to. If float is provided, original dose grid pixel spacing must be square.

  • interpolation_segments_between_planes (integer, optional) – Number of segments to interpolate between structure slices.

  • thickness (float, optional) – Structure thickness used to calculate volume of a voxel.

  • memmap_rtdose (bool, optional) – Use memory mapping to access the pixel array of the DICOM RT Dose. This reduces memory usage at the expense of increased calculation time.

  • callback (function, optional) – A function that will be called at every iteration of the calculation.

Returns:

An instance of dvh.DVH in cumulative dose. This can be converted to different formats using the attributes and properties of the DVH class.

Return type:

dvh.DVH

dicompylercore.dvhcalc.calculate_plane_histogram(plane, doseplane, dosegridpoints, maxdose, dd, id, structure, hist)[source]

Calculate the DVH for the given plane in the structure.

dicompylercore.dvhcalc.get_contour_mask(dd, id, dosegridpoints, contour)[source]

Get the mask for the contour with respect to the dose plane.

dicompylercore.dvhcalc.calculate_contour_dvh(mask, doseplane, maxdose, dd, id, structure)[source]

Calculate the differential DVH for the given contour and dose plane.

dicompylercore.dvhcalc.structure_extents(coords)[source]

Determine structure extents in patient coordinates.

Parameters:

coords (dict) – Structure coordinates from dicomparser.GetStructureCoordinates.

Returns:

Structure extents in patient coordintes: [xmin, ymin, xmax, ymax].

Return type:

list

dicompylercore.dvhcalc.dosegrid_extents_indices(extents, dd, padding=1)[source]

Determine dose grid extents from structure extents as array indices.

Parameters:
  • extents (list) – Structure extents in patient coordinates: [xmin, ymin, xmax, ymax]. If an empty list, no structure extents will be used in the calculation.

  • dd (dict) – Dose data from dicomparser.GetDoseData.

  • padding (int, optional) – Pixel padding around the structure extents.

Returns:

Dose grid extents in pixel coordinates as array indices: [col_min, row_min, col_max, row_max].

Return type:

list

dicompylercore.dvhcalc.dosegrid_extents_positions(extents, dd)[source]

Determine dose grid extents in patient coordinate indices.

Parameters:
  • extents (list) – Dose grid extents in pixel coordintes: [col_pos_min, row_pos_min, col_pos_max, row_pos_max].

  • dd (dict) – Dose data from dicomparser.GetDoseData.

Returns:

Dose grid extents in patient coordintes: [xmin, ymin, xmax, ymax].

Return type:

list

dicompylercore.dvhcalc.get_resampled_lut(index_extents, extents, new_pixel_spacing, min_pixel_spacing)[source]

Determine the patient to pixel LUT based on new pixel spacing.

Parameters:
  • index_extents (list) – Dose grid extents as array indices.

  • extents (list) – Dose grid extents in patient coordinates: [col_pos_min, row_pos_min, col_pos_max, row_pos_max].

  • new_pixel_spacing (tuple or float) – New pixel spacing in mm (row, column). If float is provided, original dose grid pixel spacing must be square.

  • min_pixel_spacing (tuple) – Min pixel spacing used to determine new pixel spacing (row, column).

Returns:

A tuple of lut lists (col lut, row lut) with the coordinates of the dose grid in patient coordinates

Return type:

tuple

Raises:

AttributeError – Raised if the new pixel_spacing is not a factor of the minimum pixel spacing.

Notes

The new pixel spacing must be a factor of the original (minimum) pixel spacing. For example if the original pixel spacing was 3 mm, the new pixel spacing should be: 3 / (2^n) mm, where n is an integer. This applies independently to both the row and column pixel spacing.

If a single float value is provided it will be applied to both row and column. Additionally, the original dose grid pixel spacing must be square.

Examples

Original pixel spacing: 3 mm, new pixel spacing: 0.375 mm Derived via: (3 / 2^16) == 0.375

dicompylercore.dvhcalc.get_interpolated_dose(dose, z, resolution, extents)[source]

Get interpolated dose for the given z, resolution & array extents.

Parameters:
  • dose (DicomParser) – A DicomParser instance of an RT Dose.

  • z (float) – Index in mm of z plane of dose grid.dose

  • resolution (tuple) – Interpolation resolution less than or equal to dose grid pixel spacing. Provided in (row, col) format.

  • extents (list) – Dose grid index extents.

Returns:

Interpolated dose grid with a shape larger than the input dose grid.

Return type:

ndarray

dicompylercore.dvhcalc.interpolate_between_planes(planes, n=2)[source]

Interpolate n additional structure planes (segments) in between planes.

Parameters:
  • planes (dict) – RT Structure plane data from dicomparser.GetStructureCoordinates.

  • n (int, optional) – Number of planes to interpolate in between the existing planes.

Returns:

Plane data with additional keys representing interpolated planes.

Return type:

dict

dose module

Routines to access and modify DICOM RT Dose.

class dicompylercore.dose.DoseGrid(rt_dose, order=1, mode='constant', cval=0.0)[source]

Bases: object

Class that stores DICOM-RT dose grids, performs addition/scaling.

Initialization of a DoseGrid from a DICOM-RT Dose file or dataset.

Parameters:
  • rt_dose (pydicom Dataset or filename) – DICOM RT Dose used to determine the structure dose grid data.

  • order (int, optional) – The order of the spline interpolation (if needed), default is 1. The order has to be in the range 0-5. 0: the nearest grid point, 1: trilinear, 2 to 5: spline See scipy.ndimage.map_coordinates documentation for more details

  • mode ('constant' or 'nearest', optional) –

    The mode parameter determines how the other dose grid is extended beyond its boundaries. Default is 'constant'. Behavior for these values is as follows:

    'constant' (k k k k | a b c d | k k k k)

    The other dose grid is extended by filling all values beyond the edge with the same constant value, defined by the cval parameter.

    'nearest' (a a a a | a b c d | d d d d)

    The input is extended by replicating the last pixel.

    Additional modes are available, see scipy.ndimage.map_coordinates documentation for more details.

  • cval (scalar, optional) – Value to fill past edges of input if mode is ‘constant’. Default is 0.0.

property shape

Get the x, y, z dimensions of the dose grid

property axes

Get the x, y, z axes of the dose grid (in mm)

property scale

Get the dose grid resolution (xyz)

property offset

Get the coordinates of the dose grid origin (mm)

property max_boundary_dose

Get the max boundary dose

property max_boundary_relative_dose
multiply(factor)[source]

Scale the dose grid.

Parameters:

factor (int, float) – Multiply the dose grid by this factor.

dose_grid_post_processing(other=None)[source]

Set the pixel data and store UIDs from other DoseGrid

is_coincident(other)[source]

Check dose grid spatial coincidence.

Parameters:

other (DoseGrid) – Another DoseGrid object.

set_pixel_data()[source]

Update the PixelData with the current dose_grid

save_dcm(file_path)[source]

Save the pydicom.FileDataset to file

get_ijk_points(other_axes)[source]

Convert axes from another DoseGrid into ijk of this DoseGrid.

Parameters:

other_axes (list) – The x, y, and z axis arrays.

Returns:

Array of other_axes in this ijk space.

Return type:

np.vstack

add(other, force=False)[source]

Add another dose grid to this dose grid, with interpolation if needed

Parameters:
  • other (DoseGrid) – Another DoseGrid object.

  • force (bool) – Set to True to ignore differences in DoseSummationType, DoseType, DoseUnits, ImageOrientationPatient

interp_entire_grid(other)[source]

Interpolate the other dose grid to this dose grid’s axes in one operation

Parameters:

other (DoseGrid) – Another DoseGrid object.

Returns:

The other dose grid interpolated to this dose grid’s axes

Return type:

np.array

update_dicom_tags()[source]

Update DICOM UIDs, Content Date/Time, and Dose Comment

show(z=None)[source]

Show the dose grid using Matplotlib if present.

Parameters:

z (float, optional) – slice position to display initially, by default None

dicompylercore.dose.set_dicom_tag_value(ds, tag, value)[source]

Set or update a DICOM tag value in the pydicom dataset.

Parameters:
  • ds (pydicom Dataset) – The pydicom dataset for the tag to be added/updated to.

  • tag (str, int or tuple) – DICOM tag or keyword to be added.

  • value (any) – New value for the tag’s element.

dicompylercore.dose.add_dicom_sequence(ds, seq_keyword, data_set_dict)[source]

Add a sequence to a data set.

Parameters:
  • ds (pydicom Dataset) – The pydicom dataset for the sequence to be added to.

  • seq_keyword (str) – The DICOM keyword for the sequence.

  • data_set_dict (dict) – Dictionary of tags and values for the sequence element.

dicompylercore.dose.validate_attr_equality(obj_1, obj_2, attr)[source]

Assess the equality of the provided attr between two objects. Send warning if unequal.

Parameters:
  • obj_1 (object) – Any object with an attr attribute that is comparable by !=

  • obj_2 (object) – Any object with an attr attribute that is comparable by !=

  • attr (str) – The attribute to be compared between obj_1 and obj_2

dicompylercore.dose.max_boundary_value(arr)[source]

Get the greatest value on the boundary of a 3D numpy array

Parameters:

arr (numpy.array) – Any 3-dimensional array-like object

Returns:

Maximum value along any side of the input array

Return type:

float