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.Series(data, input_order='none', opts=None, shape=(0, ), dtype=<class 'float'>, buffer=None, offset=0, strides=None, order=None, template=None, geometry=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.
Series(data, input_order=’none’, opts=None, shape=(0,), dtype=float, order=None, template=None, geometry=None)
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: * ‘none’ : 3D volume or 2D slice (default). * ‘time’ : Time-resolved data. * ‘b’ : Diffusion data with variable b values. * ‘te’ : Varying echo times. * ‘fa’ : Varying flip angles.
opts – Dict of input options, mostly for format specific plugins (argparse.Namespace or dict)
shape – Tuple of ints, specifying shape of input data.
dtype – Numpy data type. Default: float
template – Input data to use as template for DICOM header (Series, array_like or URL)
geometry – Input data to use as template for geometry (Series, array_like or URL)
order – Row-major (C-style) or column-major (Fortran-style) order, {‘C’, ‘F’}, optional
- Returns
Series instance
- 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:
>>> tagvalue, filename, dicomheader = image.DicomHeaderDict()[0]
- Type
dict
- property SOPClassUID¶
DICOM SOP Class UID
- Raises
ValueError – when SOP Class UID is not set
- property accessionNumber¶
Accession number
DICOM accession number
- Raises
ValueError – when accession number is not set
TypeError – When accno is not printable
- Type
str
- property axes¶
axes objects
- Raises
ValueError – when the axes are not set.
- Type
list of Axis
- 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
- Raises
ValueError – when no axis object has given name
- Usage:
>>> axis = si.find_axis('slice')
- property frameOfReferenceUID¶
Frame of reference UID
DICOM frame of reference UID
- Raises
ValueError – when frame of reference UID is not set
TypeError – When uid is not printable
- Type
str
- 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, cmap='gray', window=None, level=None, link=False)[source]¶
Let user draw ROI on image
- 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) –
cmap (str) – colour map for display. Default: ‘gray’
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.
- Returns
- If vertices, 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.
- 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_transformation_components_xyz()[source]¶
Get origin and direction from transformation matrix in xyz convention.
- Returns
- Tuple of
Origin np.array size 3.
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¶
imagePositions
The [z,y,x] coordinates of the upper left hand corner (first pixel) of each slice.
dict(imagePositions[slice]) 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.
Examples
>>> z,y,x = si.imagePositions[slice]
Examples
>>> for slice in range(slices): >>> si.imagePositions = { >>> slice: si.getPositionForVoxel(np.array([slice,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¶
Image type
DICOM image type
- 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.
- Returns
Current input order.
- 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
- Returns
The input order.
- Raises
ValueError – when input order is not defined.
- Type
int
- property orientation¶
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
DICOM 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
DICOM patient ID
- Raises
ValueError – when patient ID is not set
TypeError – When patID is not printable
- Type
str
- property patientName¶
Patient name
DICOM patient name
- Raises
ValueError – when patient name is not set
TypeError – When patnam is not printable
- Type
str
- property photometricInterpretation¶
Photometric Interpretation
DICOM Photometric Interpretation
- Raises
ValueError – when photometric interpretation is not set
TypeError – When photometric interpretation is not printable
- Type
str
- property rows¶
Number of rows
- Raises
ValueError – when number of rows is not defined.
- Type
int
- property seriesDescription¶
Series description
DICOM series description.
- Raises
ValueError – When series description is not set.
AssertionError – when series description is not str
- Type
str
- property seriesInstanceUID¶
Series instance UID
DICOM series instance UID
- Raises
ValueError – when series instance UID is not set
TypeError – When uid is not printable
- Type
str
- property seriesNumber¶
Series number
DICOM series number.
- Raises
ValueError – when series number is not set.
ValueError – when series number cannot be converted to int.
- Type
int
- 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
- show(im2=None, fig=None, cmap='gray', window=None, level=None, link=False)[source]¶
Show image
With ideas borrowed from Erlend Hodneland (2021).
- 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
cmap (str) – color map for display. Default: ‘gray’
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.array
- 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
- Returns
Current output order.
- Raises
ValueError – when output order is not defined.
- Type
int
- property spacing¶
spacing
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:
>>> ds, dr, dc = si.spacing >>> si.spacing = ds, dr, dc
- Type
numpy.array([ds,dr,dc])
- property studyID¶
Study ID
DICOM study ID
- Raises
ValueError – when study ID is not set.
TypeError – When id is not printable
- Type
str
- property studyInstanceUID¶
Study instance UID
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.array(tags)
Examples
>>>self.tags[slice][tag]
- Raises
ValueError – when tags are not set.
- Type
dict[slice] of numpy.array(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
- 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
- write(url, opts=None, formats=None)[source]¶
Write Series image
- Parameters
self – Series array
directory_name – directory name
filename_template – template including %d for image number
opts – Output options (argparse.Namespace or dict)
formats – list of output formats, overriding opts.output_format (list or str)