src.imagedata package
Subpackages
- src.imagedata.apps package
- src.imagedata.archives package
- Submodules
- src.imagedata.archives.abstractarchive module
AbstractArchive
AbstractArchive.add_localfile()
AbstractArchive.authors
AbstractArchive.base
AbstractArchive.basename()
AbstractArchive.close()
AbstractArchive.construct_filename()
AbstractArchive.description
AbstractArchive.exists()
AbstractArchive.getmembers()
AbstractArchive.getnames()
AbstractArchive.is_file()
AbstractArchive.mimetypes
AbstractArchive.name
AbstractArchive.new_local_file()
AbstractArchive.open()
AbstractArchive.path
AbstractArchive.plugin_type
AbstractArchive.root
AbstractArchive.set_member_naming_scheme()
AbstractArchive.to_localfile()
AbstractArchive.transport
AbstractArchive.url
AbstractArchive.use_query()
AbstractArchive.version
AbstractArchive.writedata()
Member
NoOtherInstance
WriteMultipleArchives
- src.imagedata.archives.filesystemarchive module
FilesystemArchive
FilesystemArchive.add_localfile()
FilesystemArchive.authors
FilesystemArchive.base
FilesystemArchive.basename()
FilesystemArchive.close()
FilesystemArchive.construct_filename()
FilesystemArchive.description
FilesystemArchive.exists()
FilesystemArchive.extensions
FilesystemArchive.getmembers()
FilesystemArchive.getnames()
FilesystemArchive.is_file()
FilesystemArchive.level
FilesystemArchive.mimetypes
FilesystemArchive.name
FilesystemArchive.new_local_file()
FilesystemArchive.open()
FilesystemArchive.path
FilesystemArchive.root
FilesystemArchive.to_localfile()
FilesystemArchive.url
FilesystemArchive.use_query()
FilesystemArchive.version
FilesystemArchive.writedata()
NoSuchFile
ReadOnlyError
WriteOnFile
- src.imagedata.archives.zipfilearchive module
WriteFileIO
ZipfileArchive
ZipfileArchive.add_localfile()
ZipfileArchive.authors
ZipfileArchive.base
ZipfileArchive.basename()
ZipfileArchive.close()
ZipfileArchive.construct_filename()
ZipfileArchive.description
ZipfileArchive.exists()
ZipfileArchive.getmembers()
ZipfileArchive.getnames()
ZipfileArchive.is_file()
ZipfileArchive.mimetypes
ZipfileArchive.name
ZipfileArchive.new_local_file()
ZipfileArchive.open()
ZipfileArchive.path
ZipfileArchive.root
ZipfileArchive.to_localfile()
ZipfileArchive.url
ZipfileArchive.use_query()
ZipfileArchive.version
ZipfileArchive.writedata()
list_files()
- Module contents
- src.imagedata.formats package
- Subpackages
- Submodules
- src.imagedata.formats.abstractplugin module
AbstractPlugin
AbstractPlugin.authors
AbstractPlugin.description
AbstractPlugin.getPositionForVoxel()
AbstractPlugin.getTimeline()
AbstractPlugin.getVoxelForPosition()
AbstractPlugin.name
AbstractPlugin.plugin_type
AbstractPlugin.read()
AbstractPlugin.replace_geometry_attributes()
AbstractPlugin.url
AbstractPlugin.version
AbstractPlugin.write_3d_numpy()
AbstractPlugin.write_4d_numpy()
NoOtherInstance
- src.imagedata.formats.dicomplugin module
DICOMPlugin
DICOMPlugin.authors
DICOMPlugin.auto_sort()
DICOMPlugin.construct_basic_dicom()
DICOMPlugin.construct_dicom()
DICOMPlugin.construct_pixel_array()
DICOMPlugin.correct_acqtimes_for_dynamic_series()
DICOMPlugin.create_affine()
DICOMPlugin.description
DICOMPlugin.extensions
DICOMPlugin.extractDicomAttributes()
DICOMPlugin.getDicomAttribute()
DICOMPlugin.getOriginForSlice()
DICOMPlugin.get_dicom_files()
DICOMPlugin.keep_uid
DICOMPlugin.name
DICOMPlugin.process_member()
DICOMPlugin.read()
DICOMPlugin.read_files()
DICOMPlugin.removePrivateTags()
DICOMPlugin.root
DICOMPlugin.setDicomAttribute()
DICOMPlugin.simulateAffine()
DICOMPlugin.smallint
DICOMPlugin.sort_images()
DICOMPlugin.url
DICOMPlugin.version
DICOMPlugin.write_3d_numpy()
DICOMPlugin.write_4d_numpy()
DICOMPlugin.write_enhanced()
DICOMPlugin.write_slice()
FilesGivenForMultipleURLs
NoDICOMAttributes
UnevenSlicesError
UnknownTag
ValueErrorWrapperPrecisionError
- src.imagedata.formats.itkplugin module
DependencyError
ITKPlugin
ITKPlugin.authors
ITKPlugin.description
ITKPlugin.extensions
ITKPlugin.get_image_from_numpy()
ITKPlugin.name
ITKPlugin.set_direction_from_dicom_header()
ITKPlugin.set_direction_from_transformation_matrix()
ITKPlugin.url
ITKPlugin.version
ITKPlugin.write_3d_numpy()
ITKPlugin.write_4d_numpy()
ITKPlugin.write_numpy_itk()
ImageTypeError
- src.imagedata.formats.matplugin module
- src.imagedata.formats.niftiplugin module
- Module contents
CannotSort
EmptyImageError
FormatPluginNotFound
NotImageError
NotTimeOrder
SOPInstanceUIDNotFound
UnknownInputError
UnknownTag
WriteNotImplemented
find_plugin()
get_plugins_list()
get_size()
input_order_to_dirname_str()
input_order_to_str()
shape_to_str()
sort_on_to_str()
str_to_dtype()
str_to_input_order()
str_to_sort_on()
- src.imagedata.transports package
- Submodules
- src.imagedata.transports.abstracttransport module
AbstractTransport
AbstractTransport.authors
AbstractTransport.close()
AbstractTransport.description
AbstractTransport.exists()
AbstractTransport.info()
AbstractTransport.isfile()
AbstractTransport.mimetype
AbstractTransport.name
AbstractTransport.open()
AbstractTransport.plugin_type
AbstractTransport.schemes
AbstractTransport.url
AbstractTransport.version
AbstractTransport.walk()
NoOtherInstance
- src.imagedata.transports.dicomtransport module
- src.imagedata.transports.filetransport module
FileTransport
FileTransport.authors
FileTransport.close()
FileTransport.description
FileTransport.exists()
FileTransport.info()
FileTransport.isfile()
FileTransport.name
FileTransport.netloc
FileTransport.open()
FileTransport.opts
FileTransport.path
FileTransport.schemes
FileTransport.url
FileTransport.version
FileTransport.walk()
- src.imagedata.transports.xnattransport module
XnatTransport
XnatTransport.authors
XnatTransport.close()
XnatTransport.description
XnatTransport.exists()
XnatTransport.info()
XnatTransport.isfile()
XnatTransport.mimetype
XnatTransport.name
XnatTransport.netloc
XnatTransport.open()
XnatTransport.opts
XnatTransport.read_directory_only
XnatTransport.schemes
XnatTransport.url
XnatTransport.version
XnatTransport.walk()
- Module contents
Submodules
src.imagedata.axis module
Axis defines a dimension of an images Series.
- 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)
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
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.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:
imagedata.collections.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.
- 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:
imagedata.collections.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.
- 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:
imagedata.collections.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.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.
- 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')
src.imagedata.image_data module
Read/write image data to file(s). Handles DICOM, Nifti, VTI and mhd.
src.imagedata.list_plugins module
src.imagedata.readdata module
Read/Write image files, calling appropriate transport, archive and format plugins
- 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.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’)
- 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:
- 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:
- 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
- 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:
- 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:
- 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_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:
- 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
- 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.
- 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.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.
Module contents
imagedata