src.imagedata package

Subpackages

Submodules

src.imagedata.axis module

Axis defines a dimension of an images Series.

class src.imagedata.axis.Axis(name)[source]

Bases: object

class src.imagedata.axis.UniformAxis(name, start, stop, step=1)[source]

Bases: Axis

Define axis by giving start, stop and step (optional). Start, stop and step are given in actual values

Examples

>>> ax = UniformAxis('row', 0, 128)
property slice
class src.imagedata.axis.UniformLengthAxis(name, start, n, step=1)[source]

Bases: UniformAxis

Define axis by giving start, length and step (optional). Start and step are given in actual values.

Examples

>>> ax = UniformLengthAxis('row', 0, 128)
class src.imagedata.axis.VariableAxis(name, values)[source]

Bases: Axis

Define axis by giving an array of values. values are actual values.

Examples

>>> ax = VariableAxis('time', [0, 1, 4, 9, 11, 13])

src.imagedata.cmdline module

Add standard command line options.

class src.imagedata.cmdline.CommaSepAction(option_strings, dest, nargs=None, **kwargs)[source]

Bases: Action

class src.imagedata.cmdline.DictAction(option_strings, dest, nargs=None, **kwargs)[source]

Bases: Action

class src.imagedata.cmdline.DtypeAction(option_strings, dest, nargs=None, **kwargs)[source]

Bases: Action

class src.imagedata.cmdline.InputOrderAction(option_strings, dest, nargs=None, **kwargs)[source]

Bases: Action

class src.imagedata.cmdline.OutputFormatAction(option_strings, dest, nargs=None, **kwargs)[source]

Bases: Action

class src.imagedata.cmdline.SortOnAction(option_strings, dest, nargs=None, **kwargs)[source]

Bases: Action

src.imagedata.cmdline.add_argparse_options(parser)[source]

src.imagedata.collections module

Image cohort

The Cohort class is a collection of Patient objects.

Typical example usage:

cohort = Cohort(‘input’)

class src.imagedata.collections.ClinicalTrialSubject(obj)[source]

Bases: object

class src.imagedata.collections.Cohort(data, opts=None)[source]

Bases: SortedDict

Cohort – Read and sort images into a collection of Patient objects.

Cohort(data, opts=None)

Examples

>>> from imagedata import Cohort
>>> cohort = Cohort('directory/')
>>> for id in cohort:
>>>     patient = cohort[id]
Parameters:
  • data – URL to input data, or list of Patient instances

  • opts – Dict of input options, mostly for format specific plugins (argparse.Namespace or dict) * ‘strict_values’: Whether attributes should match in each study (bool)

Returns:

Cohort instance

authors = 'Erling Andersen'
description = 'Image cohort'
name = 'Cohort'
url = 'www.helse-bergen.no'
version = '1.0.0'
write(url, opts=None, formats=None)[source]

Write image data, calling appropriate format plugins

Parameters:
  • self – Cohort instance

  • url – output destination url

  • opts – Output options (argparse.Namespace or dict)

  • formats – list of output formats, overriding opts.output_format (list or str)

Raises:
class src.imagedata.collections.GeneralEquipment(obj)[source]

Bases: object

class src.imagedata.collections.Patient(data, opts=None)[source]

Bases: SortedDict

Patient – Read and sort images into a collection of Study objects.

Patient(data, opts=None)

Examples

>>> from imagedata import Patient
>>> patient = Patient('directory/')
>>> for uid in patient:
>>>     study = patient[uid]
Parameters:
  • data – URL to input data, or list of Study instances

  • opts – Dict of input options, mostly for format specific plugins (argparse.Namespace or dict) * ‘strict_values’: Whether attributes should match in each study (bool)

Returns:

Patient instance

authors = 'Erling Andersen'
description = 'Image patient'
name = 'Patient'
url = 'www.helse-bergen.no'
version = '1.0.0'
write(url, opts=None, formats=None)[source]

Write image data, calling appropriate format plugins

Parameters:
  • self – Patient instance

  • url – output destination url

  • opts – Output options (argparse.Namespace or dict)

  • formats – list of output formats, overriding opts.output_format (list or str)

Raises:
class src.imagedata.collections.Study(data, opts=None)[source]

Bases: SortedDict

Study – Read and sort images into a collection of Series objects.

Study(data, opts=None)

Examples

>>> from imagedata import Study
>>> study = Study('directory/')
>>> for uid in study:
>>>     series = study[uid]
Parameters:
  • data – URL to input data, or list of Series instances

  • opts – Dict of input options, mostly for format specific plugins (argparse.Namespace or dict) * ‘strict_values’: Whether study attributes should match in each series (bool)

Returns:

Study instance

authors = 'Erling Andersen'
description = 'Image study'
name = 'Study'
url = 'www.helse-bergen.no'
version = '1.0.0'
write(url, opts=None, formats=None)[source]

Write image data, calling appropriate format plugins

Parameters:
  • self – Study instance

  • url – output destination url

  • opts – Output options (argparse.Namespace or dict)

  • formats – list of output formats, overriding opts.output_format (list or str)

Raises:
exception src.imagedata.collections.UnknownOptionType[source]

Bases: Exception

src.imagedata.header module

Image series header

class src.imagedata.header.Header[source]

Bases: object

Image header object.

Variables:
  • input_order

  • sort_on

  • input_format

  • dicomTemplate

  • seriesNumber

  • seriesDescription

  • imageType

  • frameOfReferenceUID

  • studyInstanceUID

  • studyID

  • seriesInstanceUID

  • SOPClassUID

  • accessionNumber

  • patientName

  • patientID

  • patientBirthDate

  • input_sort

  • sliceLocations (#)

  • tags

  • spacing

  • imagePositions

  • orientation

  • transformationMatrix

  • photometricInterpretation

  • axes

  • __uid_generator

add_geometry(geometry)[source]

Add geometry data to obj header.

Parameters:
  • self – header or dict

  • geometry – geometry template header or dict. Can be None.

add_template(template) None[source]

Add template data to this header. Does not add geometry data.

Parameters:

template – template header. Can be None.

empty_ds() Dataset[source]
find_axis(name)[source]

Find axis with given name

Parameters:

name – Axis name to search for

Returns:

axis object with given name

Raises:

ValueError – when no axis object has given name

Usage:
>>> from imagedata.series import Series
>>> si = Series(np.array([3, 3, 3]))
>>> axis = si.find_axis('slice')
new_uid() str[source]

Return the next available UID from the UID generator.

set_default_values(axes) None[source]

Set default values.

src.imagedata.image_data module

Read/write image data to file(s). Handles DICOM, Nifti, VTI and mhd.

src.imagedata.image_data.calculator()[source]
src.imagedata.image_data.conversion()[source]
src.imagedata.image_data.dump()[source]
src.imagedata.image_data.image_list()[source]
src.imagedata.image_data.print_statistics(si, mask=None, bash=False)[source]
src.imagedata.image_data.show()[source]
src.imagedata.image_data.statistics(cmdline=None)[source]
src.imagedata.image_data.timeline()[source]

src.imagedata.list_plugins module

src.imagedata.readdata module

Read/Write image files, calling appropriate transport, archive and format plugins

exception src.imagedata.readdata.NoArchiveError[source]

Bases: Exception

exception src.imagedata.readdata.NoTransportError[source]

Bases: Exception

exception src.imagedata.readdata.UnknownOptionType[source]

Bases: Exception

src.imagedata.readdata.read(urls, order=None, opts=None)[source]

Read image data, calling appropriate transport, archive and format plugins

Parameters:
  • urls – list of urls or url to read (list of str, or str)

  • order – determine how to sort the images (default: auto-detect)

  • opts – input options (argparse.Namespace or dict)

Returns:

tuple of
  • hdr: header instance

  • si[tag,slice,rows,columns]: numpy array

Raises:
  • ValueError – When no sources are given.

  • UnknownOptionType – When opts cannot be made into a dict.

  • FileNotFoundError – When specified URL cannot be opened.

  • UnknownInputError – When the input format could not be determined.

  • CannotSort – When input data cannot be sorted.

src.imagedata.readdata.sorted_plugins_dicom_first(plugins)[source]

Sort plugins such that any Nifti plugin is used early.

src.imagedata.readdata.str_to_dtype(s)[source]

Convert dtype string to numpy dtype.

src.imagedata.readdata.write(si, url, opts=None, formats=None)[source]

Write image data, calling appropriate format plugins

Parameters:
  • si[tag – Series array

  • slice – Series array

  • rows – Series array

  • columns] – Series array

  • url – output destination url

  • opts – Output options (argparse.Namespace or dict)

  • formats – list of output formats, overriding opts.output_format (list or str)

Raises:
  • UnknownOptionType – When opts cannot be made into a dict.

  • TypeError – List of output format is not list().

  • ValueError – Wrong number of destinations given, or no way to write multidimensional image.

  • imagedata.formats.WriteNotImplemented – Cannot write this image format.

src.imagedata.series module

Image series

The Series class is a subclassed Numpy.ndarray enhancing the array with relevant medical image methods and attributes.

Typical example usage:

si = Series(‘input’)

exception src.imagedata.series.DoNotSetSlicesError[source]

Bases: Exception

class src.imagedata.series.Series(data, input_order='auto', opts=None, shape=(0, ), dtype=<class 'float'>, buffer=None, offset=0, strides=None, order=None, template=None, geometry=None, axes=None)[source]

Bases: ndarray

Series – a multidimensional array of medical imaging pixels.

The Series class is a subclassed numpy.ndarray enhancing the ndarray with relevant medical image methods and attributes.

Examples

Read the contents of an input directory

>>> image = Series('directory/')

Make a Series instance from a Numpy.ndarray

>>> a = np.eye(128)
>>> image = Series(a)
Parameters:
  • data (array_like or URL) – Input data, either explicit as np.ndarray, np.uint16, np.float32, or by URL to input data.

  • input_order (str) –

    How to sort the input data. Typical values are:

    • ’auto’ : auto-detect sort criteria (default).

    • ’none’ : 3D volume or 2D slice.

    • ’time’ : Time-resolved data.

    • ’b’ : Diffusion data with variable b values.

    • ’te’ : Varying echo times.

    • ’fa’ : Varying flip angles.

  • opts (argparse.Namespace or dict) – Dict of input options, mostly for format specific plugins.

  • shape (tuple of ints) – Specifying shape of input data.

  • dtype (numpy.dtype) – Numpy data type. Default: float.

  • template (Series, array_like or URL) – Input data to use as template for DICOM header.

  • geometry (Series, array_like or URL) – Input data to use as template for geometry.

  • axes (list of Axis) – Set axes for new instance.

  • order – Row-major (C-style) or column-major (Fortran-style) order, {‘C’, ‘F’}, optional

Returns:

Series instance

Return type:

Series

property SOPClassUID

DICOM SOP Class UID

Raises:

ValueError – when SOP Class UID is not set

Type:

str

property SOPInstanceUIDs

DICOM SOP Instance UIDs

Raises:

ValueError – when SOP Instance UIDs is not set

Type:

str

property accessionNumber

DICOM accession number

Raises:
  • ValueError – when accession number is not set

  • TypeError – When accno is not printable

Type:

str

align(reference, interpolation='linear', force=False)[source]

Align moving series (self) to reference. The moving series is resampled on the grid of the reference series. In effect the moving series is reformatted to the slices of the reference series. The aligned image is rounded to nearest integer when the moving image is integer.

Examples

Align vibe series (moving) with reference dce series

>>> moving = Series('vibe')
>>> reference = Series('dce', 'time')
>>> img = moving.align(reference)
Parameters:
  • moving (Series) – The moving series which will be aligned to the reference series.

  • reference (Series) – Reference series.

  • interpolation (str) – Method of interpolation. See scipy.interpolate.RegularGridInterpolator for possible value. Default: ‘linear’.

  • force (bool) – Override check on FrameOfReferenceUID when True. Default: False.

Returns:

Aligned series.

Return type:

Series

Raises:

ValueError – When FrameOfReference or TransformationMatrix is missing for either series.

authors = 'Erling Andersen'
property axes

axes objects, sorted like shape indices.

Raises:

ValueError – when the axes are not set.

Type:

list of Axis

property bodyPartExamined

Body Part Examined.

Raises:
  • ValueError – when Body Part Examined is not set.

  • ValueError – when Body Part Examined cannot be converted to str.

Type:

str

property bvalues

b-values in s/mm2, as numpy array of floats.

Length of array is number of tags.

Raises:

ValueError – tags for dataset is not b tags

Type:

numpy.array

calculate_clip_range(probs: Tuple, bins: int = None)[source]
property color

Color interpretation.

Whether the array stores a color image, and the last index represents the color components

Raises:
  • ValueError – when color interpretation is not set

  • TypeError – When color is not bool

Type:

bool

property colormap
property colormap_label

Colormap label

Raises:
  • ValueError – when colormap label is not set

  • TypeError – When colormap label is not printable

Type:

str

property colormap_norm
property columns

Number of columns.

Raises:

ValueError – when number of columns is not defined.

Type:

int

description = 'Image series'
property dicomTemplate

DICOM data set

Raises: ValueError: when modality is not set. ValueError: when modality cannot be converted to str.

Type:

pydicom.dataset.Dataset

find_axis(name)[source]

Find axis with given name.

Parameters:

name – Axis name to search for.

Returns:

axis object with given name.

Return type:

Axis

Raises:

ValueError – when no axis object has given name

Usage:
>>> si = Series(np.array([3, 3, 3]))
>>> axis = si.find_axis('slice')
property frameOfReferenceUID

DICOM frame of reference UID

Raises:
  • ValueError – when frame of reference UID is not set

  • TypeError – When uid is not printable

Type:

str

fuse_mask(mask, alpha=0.7, blend=False, colormap='Greys_r', lut=None, norm='linear', clip='window', probs=(0.01, 0.999), maskmap='magma', maskrange=None)[source]

Color fusion of mask

Create an RGB image of self, overlaying/enhancing the mask area.

When the mask is binary, it is gaussian filtered to disperse edges.

With ideas from Hauke Bartsch and Sathiesh Kaliyugarasan (2023).

Examples

>>> img = Series(...)
>>> mask = Series(...)
>>> overlayed_img = img.fuse_mask(mask, clip='hist')
>>> overlayed_img.show()
Parameters:
  • mask (Series or np.ndarray) – Mask image

  • alpha (float) – Alpha blending for each channel. Default: 0.7

  • blend (bool) – Whether the self image will be blended using alpha. Default: False

  • colormap (str) – Matplotlib colormap name for image. Defaults: ‘Greys_r’.

  • maskmap (str) – Matplotlib colormap name for mask. Defaults: ‘magma’.

  • lut (int) – Number of rgb quantization levels. Default: None, lut is calculated from the voxel values.

  • norm (str or matplotlib.colors.Normalize) – Normalization method. Either linear/log, or the .Normalize instance used to scale scalar data to the [0, 1] range before mapping to colors using colormap.

  • clip (str) – How to clip the data values. Default: ‘window’, clip data to window center and width. ‘hist’: clip data at histogram probabilities.

  • probs (tuple) – Minimum and maximum probabilities when clipping using histogram method.

  • maskrange (tuple) – Range of mask colormap. Defaults: None: Use full mask range.

Returns:

RGB Series object

Return type:

Series

Raises:

IndexError – When the mask does not match the image

getDicomAttribute(keyword)[source]

Get named DICOM attribute.

Parameters:

keyword (str) – name or dicom tag

Returns:

DICOM attribute

getPositionForVoxel(r, transformation=None)[source]

Get patient position for center of given voxel r.

Use Patient Position and Image Orientation to calculate world coordinates for given voxel

Parameters:
  • r (numpy.array) – (s,r,c) of voxel in voxel coordinates

  • transformation (numpy.array, optional) – transformation matrix when different from self.transformationMatrix

Returns:

position of voxel in world coordinates (mm)

Return type:

numpy.array((z,y,x))

getVoxelForPosition(p, transformation=None)[source]

Get voxel for given patient position p

Use Patient Position and Image Orientation to calculate world coordinates for given voxel

Parameters:
  • p (numpy.array) – (z,y,x) of voxel in world coordinates (mm)

  • transformation (numpy.array, optional) – transformation matrix when different from self.transformationMatrix

Returns:

of voxel in voxel coordinates

Return type:

numpy.array((s,r,c))

get_roi(roi=None, color='r', follow=False, vertices=False, im2=None, fig=None, ax=None, colormap='Greys_r', norm='linear', colorbar=None, window=None, level=None, link=False, single=False, onselect=None)[source]

Let user draw ROI on image.

Examples

>>> img = Series(...)
>>> mask = img.get_roi()
>>> mask, vertices = img.get_roi(vertices=True)
Parameters:
  • roi – Either predefined vertices (optional). Dict of slices, index as [tag,slice] or [slice], each is list of (x,y) pairs. Or a binary Series grid.

  • color (str) – Color of polygon ROI. Default: ‘r’.

  • follow – (bool) Copy ROI to next tag. Default: False.

  • vertices (bool) – Return both grid mask and dictionary of vertices. Default: False.

  • im2 (Series or list of Series) – Series or list of Series which will be displayed in addition to self.

  • fig (matplotlib.plt.Figure, optional)

  • ax (matplotlib.plt.Figure, optional)

  • colormap (str) – colour map for display. Default: ‘Greys_r’

  • norm (str or matplotlib.colors.Normalize) – Normalization method. Either linear/log, or the .Normalize instance used to scale scalar data to the [0, 1] range before mapping to colors using colormap.

  • colorbar (bool) – Display colorbar with image. Default: None: determine colorbar based on colormap and norm.

  • window (number) – window width of signal intensities. Default is DICOM Window Width.

  • level (number) – window level of signal intensities. Default is DICOM Window Center.

  • link (bool) – whether scrolling is linked between displayed objects. Default: False.

  • single (bool) – draw ROI in single slice per tag. Default: False.

  • onselect (function) – call function when roi change. Default: None. When a polygon is completed or modified after completion, the onselect function is called and passed a list of the vertices as (xdata, ydata) tuples.

Returns:

tuple of grid mask and vertices_dict. Otherwise, grid mask only.
  • grid mask: Series object with voxel=1 inside ROI. Series object with shape (nz,ny,nx) (3D or more) or (ny, nx) (2D) from original image, dtype ubyte. Voxel inside ROI is 1, 0 outside.

  • vertices_dict: if vertices: Dictionary of vertices.

If running from a notebook (nbagg driver), no ROI is returned. Call get_roi_mask() afterwards to get the mask.

Return type:

If vertices

Raises:
  • ValueError – when image is not a subclass of Series, or too many viewports are requested.

  • IndexError – when there is a mismatch with images and viewports.

get_roi_mask()[source]

Get mask drawn by user in get_roi().

Examples

When used in Jupyter Notebook:

>>> img = Series(...)
>>> img.get_roi()
>>> mask = img.get_roi_mask()
Returns:

tuple of grid mask and vertices_dict. Otherwise, grid mask only.
  • grid mask: Series object with voxel=1 inside ROI. Series object with shape (nz,ny,nx) from original image, dtype ubyte. If original image is 2D, the mask will be shape (ny,nx) from original image. Voxel inside ROI is 1, 0 outside.

  • vertices_dict: if vertices: Dictionary of vertices.

Return type:

If vertices

Raises:

ValueError – when get_roi() has not produced a mask up front.

get_slice_axis()[source]

Get the slice axis instance.

get_tag_axis()[source]

Get the tax axis instance.

get_transformation_components_xyz()[source]

Get origin and direction from transformation matrix in xyz convention.

Returns:

Tuple of
  • Origin (np.array size 3): Origin.

  • Orientation (np.array size 6): (row, then column directional cosines) (DICOM convention).

  • Normal vector (np.array size 3): Slice direction.

Return type:

tuple

property imagePositions

The [z,y,x] coordinates of the upper left hand corner (first pixel) of each slice.

dict(imagePositions[s]) of [z,y,x] in mm, as numpy array

When setting, the position list is added to existing imagePositions. Overlapping dict keys will replace exisiting imagePosition for given slice s.

Examples

>>> from imagedata import Series
>>> import numpy as np
>>> si = Series(np.eye(128))
>>> z,y,x = si.imagePositions[0]

Examples

>>> from imagedata import Series
>>> import numpy as np
>>> si = Series(np.zeros((16, 128, 128)))
>>> for s in range(si.slices):
...     si.imagePositions = { s: si.getPositionForVoxel(np.array([s, 0, 0])) }
Raises:
  • ValueError – when imagePositions are not set.

  • AssertionError – when positions have wrong shape or datatype.

Type:

dict of numpy.array([z,y,x])

property imageType

DICOM image type(s).

Raises:
  • ValueError – when image type is not set.

  • TypeError – When imagetype is not printable.

Type:

list of str

property input_format

Input format

Possible input formats depend on the available formats plugins, and include ‘dicom’, ‘itk’ and ‘nifti’.

Type:

str

property input_order

Input order

How to sort input files:
  • INPUT_ORDER_NONE (‘none’): No sorting.

  • INPUT_ORDER_TIME (‘time’): Sort on image time (acquisition time or trigger time).

  • INPUT_ORDER_B (‘b’): Sort on b value.

  • INPUT_ORDER_FA (‘fa’): Sort on flip angle.

  • INPUT_ORDER_TE (‘te’): Sort on echo time.

  • INPUT_ORDER_FAULTY (‘faulty’): Correct erroneous attributes.

Raises:

ValueError – when order is illegal.

Type:

str

property input_sort

Input order

How to sort output files:
  • SORT_ON_SLICE: Run over slices first

  • SORT_ON_TAG : Run over input order first, then slices

Raises:

ValueError – when input order is not defined.

Type:

int

property laterality

Imaging laterality.

Raises:
  • ValueError – when laterality is not set.

  • ValueError – when laterality cannot be converted to str.

Type:

str

latest_roi_parameters = None
property modality

Imaging modality.

Raises:
  • ValueError – when modality is not set.

  • ValueError – when modality cannot be converted to str.

Type:

str

name = 'Series'
property orientation

The direction cosines of the first row and the first column with respect to the patient.

These attributes shall be provided as a pair. Row value (column index) for the z,y,x axes respectively, followed by the column value (row index) for the z,y,x axes respectively.

Raises:
  • ValueError – when orientation is not set.

  • AssertionError – when len(orient) != 6

Type:

numpy.array

property patientBirthDate

Patient birth date

Raises:
  • ValueError – when patient birth date is not set.

  • TypeError – When patient birth date is not printable.

Type:

str

property patientID

Patient ID

Raises:
  • ValueError – when patient ID is not set

  • TypeError – When patID is not printable

Type:

str

property patientName

Patient name

Raises:
  • ValueError – when patient name is not set

  • TypeError – When patnam is not printable

Type:

str

property patientPosition

Patient Position.

Raises:
  • ValueError – when Patient Position is not set.

  • ValueError – when Patient Position cannot be converted to str.

Type:

str

property photometricInterpretation

Photometric Interpretation.

Raises:
  • ValueError – when photometric interpretation is not set

  • TypeError – When photometric interpretation is not printable

Type:

str

property protocolName

Imaging Protocol Name.

Raises:
  • ValueError – when protocolName is not set.

  • ValueError – when protocolName cannot be converted to str.

Type:

str

property rows

Number of rows.

Raises:

ValueError – when number of rows is not defined.

Type:

int

property seriesDate

Imaging Series Date.

Raises:
  • ValueError – when seriesDate is not set.

  • ValueError – when seriesDate cannot be converted to str.

Type:

str

property seriesDescription

DICOM series description.

Raises:
  • ValueError – When series description is not set.

  • AssertionError – when series description is not str

Type:

str

property seriesInstanceUID

DICOM series instance UID

Raises:
  • ValueError – when series instance UID is not set

  • TypeError – When uid is not printable

Type:

str

property seriesNumber

DICOM series number.

Raises:
  • ValueError – when series number is not set.

  • ValueError – when series number cannot be converted to int.

Type:

int

property seriesTime

Imaging Series Time.

Raises:
  • ValueError – when seriesTime is not set.

  • ValueError – when seriesTime cannot be converted to str.

Type:

str

setDicomAttribute(keyword, value, slice=None, tag=None)[source]

Set named DICOM attribute.

Parameters:
  • keyword (str) – name or dicom tag.

  • value – new value for DICOM attribute.

  • slice (int) – optional slice to set attribute for. Default: all.

  • tag (int) – optional tag to set attribute for. Default: all.

Raises:

ValueError – When no DICOM tag is set.

property shape

Matrix shape.

Raises:

IndexError – always when set (do not set shape). Should set axes instead.

Type:

tuple of ints

show(im2=None, fig=None, ax=None, colormap='Greys_r', norm='linear', colorbar=None, window=None, level=None, link=False)[source]

Interactive display of series on screen.

Allows interactive scrolling and adjustment of window center and level.

With ideas borrowed from Erlend Hodneland (2021).

Examples

>>> img = Series(...)
>>> img.show()
Parameters:
  • im2 (Series or list of Series) – Series or list of Series which will be displayed in addition to self.

  • fig (matplotlib.plt.Figure, optional) – if already exist

  • ax (matplotlib.plt.Axes, optional) – if already exist

  • colormap (str) – color map for display. Default: ‘Greys_r’

  • norm (str or matplotlib.colors.Normalize) – Normalization method. Either linear/log, or the .Normalize instance used to scale scalar data to the [0, 1] range before mapping to colors using colormap.

  • colorbar (bool) – Display colorbar with image. Default: None: determine colorbar based on colormap and norm.

  • window (number) – window width of signal intensities. Default is DICOM Window Width.

  • level (number) – window level of signal intensities. Default is DICOM Window Center.

  • link (bool) – whether scrolling is linked between displayed images. Default: False

Raises:
  • ValueError – when image is not a subclass of Series, or too many viewports are requested.

  • IndexError – when there is a mismatch with images and viewports.

property sliceLocations

Slice locations.

Sorted numpy array of slice locations, in mm.

Raises:

ValueError – When no slice locations are defined.

Type:

numpy.ndarray

property slices

Number of slices.

Raises:
  • ValueError – when number of slices is not defined.

  • DoNotSetSlicesError – Always (do not set slices)

Type:

int

property sort_on

Output order

How to sort output files:
  • SORT_ON_SLICE: Run over slices first

  • SORT_ON_TAG : Run over input order first, then slices

Raises:

ValueError – when output order is not defined.

Type:

int

property spacing

spacing in mm.

Given as ds,dr,dc in mm. 2D image will return ds=1.

Raises:
  • ValueError – when spacing is not set.

  • ValueError – when spacing is not a tuple of 3 coordinates

Usage:
>>> si = Series(np.eye(128))
>>> ds, dr, dc = si.spacing
>>> si.spacing = ds, dr, dc
Type:

numpy.array([ds,dr,dc])

property studyID

DICOM study ID

Raises:
  • ValueError – when study ID is not set.

  • TypeError – When id is not printable

Type:

str

property studyInstanceUID

DICOM Study instance UID

Raises:
  • ValueError – when study instance UID is not set.

  • TypeError – When uid is not printable.

Type:

str

property tags

Image tags for each slice

Image tags can be an array of:
  • time points

  • diffusion weightings (b values)

  • flip angles

Setting the tags will adjust the tags in DicomHeaderDict too.

tags is a dict with (slice keys, tag array)

dict[slice] is np.ndarray(tags)

Examples

>>>self.tags[slice][tag]

Raises:

ValueError – when tags are not set.

Type:

dict[slice] of numpy.ndarray(tags)

property timeline

Timeline in seconds, as numpy array of floats.

Delta time is given as seconds. First image is t=0. Length of array is number of tags.

Raises:

ValueError – tags for dataset is not time tags

Type:

numpy.array

to_channels(channels, labels)[source]

Create a Series object with channeled data.

Examples

>>> from imagedata import Series
>>> channel0 = Series(...)
>>> channel1 = Series(...)
>>> channel2 = Series(...)
>>> T2 = Series(...)
>>> T2_channels = T2.to_channels([channel0, channel1, channel2], ['0', '1', '2'])
Parameters:
  • channels (list) – List of data for each channel.

  • labels (list) – List of labels for each channel.

Returns:

Channeled Series object

Return type:

Series

to_rgb(colormap='Greys_r', lut=None, norm='linear', clip='window', probs=(0.01, 0.999))[source]

Create an RGB color image of self.

Examples

>>> T2 = Series(...)
>>> T2_rgb = T2.to_rgb()
Parameters:
  • colormap (str) – Matplotlib colormap name. Defaults: ‘Greys_r’.

  • lut (int) – Number of rgb quantization levels. Default: None, lut is calculated from the voxel values.

  • norm (str or matplotlib.colors.Normalize) – Normalization method. Either linear/log, or the .Normalize instance used to scale scalar data to the [0, 1] range before mapping to colors using colormap.

  • clip (str) – How to clip the data values. Default: ‘window’, clip data to window center and width. ‘hist’: clip data at histogram probabilities.

  • probs (tuple) – Minimum and maximum probabilities when clipping using histogram method.

Returns:

RGB Series object

Return type:

Series

property transformationMatrix

Transformation matrix.

If the transformation matrix is not set, an attempt will be made to calculate it from spacing, imagePositions and orientation.

When setting the transformation matrix, spacing and slices must be set in advance. A new transformation matrix will also impact orientation and imagePositions.

Raises:

ValueError – Transformation matrix cannot be constructed.

Type:

numpy.array

url = 'www.helse-bergen.no'
version = '1.2.0'
vertices_from_grid(grid, align: bool = True) dict[source]

Convert roi grid to roi vertices Assume there is a single, connected roi in the grid https://docs.opencv.org/4.x/d4/d73/tutorial_py_contours_begin.html

Parameters:
  • grid

  • align

Returns:

dict

viewer = None
property windowCenter

Window Center

Raises:
  • ValueError – when window center is not set

  • TypeError – When window center is not a number

Type:

number

property windowWidth

Window Width

Raises:
  • ValueError – when window width is not set

  • TypeError – When window width is not a number

Type:

number

write(url, opts=None, formats=None)[source]

Write Series image

Parameters:
  • url (str) – Output URL.

  • opts (argparse.Namespace or dict) – Output options.

  • formats (list or str) – list of output formats, overriding opts.output_format.

DICOMPlugin accept these opts:
  • “keep_uid”: whether we will keep existing SOP Instance UID (bool).

  • “window”: “original” will keep window center/level DICOM attributes, not recalculate from present data (str).

  • “output_sort”: Which tag will sort the output images (int). Values: SORT_ON_SLICE, SORT_ON_TAG. Default: SORT_ON_SLICE.

  • “output_dir”: Store all images in a single or multiple directories (str). Values: “single”, “multi”. Default: “single”

  • input_order: DICOM tag for given input_order (str).

src.imagedata.viewer module

class src.imagedata.viewer.MyPolygonSelector(ax, onselect, useblit=False, lineprops=None, markerprops=None, vertex_select_radius=10, vertices=None, tag=None, copy=None, paste=None)[source]

Bases: PolygonSelector

Select a polygon region of an axes.

Place vertices with each mouse click, and make the selection by completing the polygon (clicking on the first vertex). Hold the ctrl key and click and drag a vertex to reposition it (the ctrl key is not necessary if the polygon has already been completed). Hold the shift key and click and drag anywhere in the axes to move all vertices. Press the esc key to start a new polygon.

For the selector to remain responsive you must keep a reference to it.

Class MyPolygonSelector subclasses matplotlib.widgets.PolygonSelector. Allows to set an initial polygon.

class src.imagedata.viewer.Viewer(images, fig=None, ax=None, follow=False, colormap='Greys_r', norm='linear', colorbar=None, window=None, level=None, link=False, onselect=None)[source]

Bases: object

Viewer – a graphical tool to display and interact with Series objects.

Parameters:
  • images (imagedata.Series or list) – Series object or list of Series objects to view.

  • fig (Figure) – matplotlib.plt.figure if already exist (optional).

  • ax (Axes) – matplotlib axis if already exist (optional).

  • follow (bool) – Copy ROI to next tag. Default: False.

  • colormap (str) – Colour map for display. Default: Greys_r.

  • norm (str or matplotlib.colors.Normalize) – Normalization method. Either linear/log, or the .Normalize instance used to scale scalar data to the [0, 1] range before mapping to colors using colormap.

  • colorbar (bool) – Display colorbar with image. Default: None: determine colorbar based on colormap and norm. range before mapping to colors using colormap.

  • window (number) – Window width of signal intensities. Default: DICOM Window Width.

  • level (number) – Window level of signal intensities. Default: DICOM Window Center.

  • link (bool) – Whether scrolling is linked between displayed objects. Default: False.

  • onselect (function) – call function when roi changes. Default: None. When a polygon is completed or modified after completion, the onselect function is called and passed idx, tag and a list of the vertices as (xdata, ydata) tuples.

advance_data(inaxes, increment)[source]

Advance display to next/previous tag value

connect()[source]
connect_draw(roi=None, color='w', callback_quit=None)[source]
disconnect()[source]
disconnect_draw()[source]
end_window_level(event)[source]
find_image_from_event(inaxes)[source]
find_viewport_from_event(inaxes)[source]
get_roi()[source]

Return drawn ROI.

Returns:

Dict of slices, index as [tag,slice] or [slice], each is list of (x,y) pairs.

key_press(event)[source]
modify_window_level(event)[source]
normalize_window(inaxes)[source]
on_copy(polygon)[source]
on_motion(event)[source]
on_paste()[source]
on_press(event)[source]
on_release(event)[source]
onselect(vertices)[source]
pretty_datetime(my_date, my_time)[source]
scroll(event)[source]
scroll_all_data(im, idx)[source]
scroll_data(inaxes, increment)[source]
set_default_viewport(axes)[source]

View as many Series as there are axes

show(ax, im)[source]
start_window_level(event)[source]
toggle_button(button)[source]
toggle_hide(inaxes)[source]

Toggle the display of text on images

update()[source]
update_tag(value)[source]
upper_left_text(im)[source]

Update upper left text

upper_right_text(im)[source]

Update upper right text

viewport_advance(increment)[source]

Advance viewport by given increment

viewport_set(position)[source]

Set viewport to image position

src.imagedata.viewer.build_info(im, colormap, norm, colorbar, window, level)[source]
src.imagedata.viewer.default_layout(fig, n)[source]

Setup a default layout for given number of axes.

Parameters:
  • fig – matplotlib figure

  • n – Number of axes required

Returns:

List of Axes

Raises:

ValueError – When no ax axes or > 9*9 are required. When no figure is given.

src.imagedata.viewer.get_level(si, level)[source]
src.imagedata.viewer.get_window_level(si, norm, window, level)[source]
src.imagedata.viewer.grid_from_roi(im: Series, vertices: dict, single: bool = False) bool | Series[source]

Return drawn ROI as grid.

Parameters:
  • im (imagedata.Series) – Series object as template

  • vertices – The polygon vertices, as a dictionary of tags of (x,y)

  • single (bool) – Draw ROI in single slice per tag

Returns:

Series with shape (nz,ny,nx) from original image, dtype ubyte. Voxels inside ROI is 1, 0 outside.

src.imagedata.viewer.pretty_tag_value(im)[source]
src.imagedata.viewer.pretty_window_level(im)[source]

Module contents

imagedata