Series Class
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. Most ndarray methods are inheritied, and are available with the Series class.
See: https://numpy.org/doc/stable/ for documentation on NumPy.
- class imagedata.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]
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
- property DicomHeaderDict
DICOM header dictionary
DicomHeaderDict[slice].tuple(tagvalue, filename, dicomheader)
- Raises
ValueError – when DICOM header is not set.
Examples
Get values for slice=0:
>>> si = Series(np.eye(128)) >>> tagvalue, filename, dicomheader = si.DicomHeaderDict()[0]
- Type
dict
- property SOPClassUID
DICOM SOP Class UID
- Raises
ValueError – when SOP Class UID 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.
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
- Raises
ValueError – When FrameOfReference or TransformationMatrix is missing for either series.
- 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
- 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 columns
Number of columns.
- Raises
ValueError – when number of columns is not defined.
- Type
int
- find_axis(name)[source]
Find axis with given name.
- Parameters
name – Axis name to search for.
- Returns
axis object with given name.
- Return type
- 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, colormap='Greys_r', lut=None, norm='linear', clip='window', probs=(0.01, 0.999))[source]
Color fusion of mask
Create an RGB image of self, enhancing the mask area in red.
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
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
- Raises
IndexError – When the mask does not match the image
- getDicomAttribute(keyword, slice=0, tag=0)[source]
Get named DICOM attribute.
- Parameters
keyword (str) – name or dicom tag
slice (int) – optional slice to get attribute from (default: 0)
tag (int) – optional tag to get attribute from (default: 0)
- 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, colormap='Greys_r', norm='linear', colorbar=None, window=None, level=None, link=False, single=False)[source]
Let user draw ROI on image.
Examples
>>> img = Series(...) >>> mask = img.get_roi()
>>> mask, vertices = img.get_roi(vertices=True)
- Parameters
roi – Predefined vertices (optional). Dict of slices, index as [tag,slice] or [slice], each is list of (x,y) pairs.
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) –
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.
- 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. 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. 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_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
- property modality
Imaging modality.
- Raises
ValueError – when modality is not set.
ValueError – when modality cannot be converted to str.
- Type
str
- 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, 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
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_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
- 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