spydcmtk package
Submodules
spydcmtk.dcmTK module
Classes for working with Dicom studies
- class spydcmtk.dcmTK.BIDSConst[source]
Bases:
object
- anat = 'anat'
- code = 'code'
- configf = 'dcm2bids_config.json'
- dwi = 'dwi'
- fmap = 'fmap'
- func = 'func'
- class spydcmtk.dcmTK.BIDS_Directory(rootDirectroy)[source]
Bases:
object
Class to work with BIDS directory
- class spydcmtk.dcmTK.BIDS_Subject(subjID, BIDSDirObj)[source]
Bases:
object
Class to work with a single BIDS subject
- class spydcmtk.dcmTK.DicomSeries(dsList=None, OVERVIEW=False, HIDE_PROGRESSBAR=False, FORCE_READ=False, SAFE_NAME_MODE=False)[source]
Bases:
list
Extends a list of ds (pydicom dataset) objects.
- anonymise(anonName, anonPatientID, anon_birthdate=True, remove_private_tags=True)[source]
Anonymise series inplace
- Parameters:
anonName (str) – New anonymise name (can be empty str)
anonPatientID (str) – New anon patient ID, if None then no action taken.
anon_birthdate (bool, optional) – To remove birthdate from tags. Defaults to True.
remove_private_tags (bool, optional) – To remove private tags from dataset. Defaults to True. In some cases this will need to be set False to keep tags necessary for post processing (e.g. some DTI tags). It is up to the user to confirm complete anonymisation in these cases.
- checkIfShouldUse_SAFE_NAMING(se_instance_set=None)[source]
Checks is should name dicoms based on UIDs or if a SE-number, Instace-number naming convention is possible. Basically checks if there would be any overlaps.
- Parameters:
se_instance_set (set, optional) – A set of instance file names (without extension). Defaults to None.
- getPixelDataAsNumpy()[source]
- Get pixel data as numpy array organised by slice and time(if present).
Also return a PatientMatrix object containing meta NOTE: Some data is repeated to serve VTK and DICOM conventions
- Returns:
numpy array - shape [nRow, nCol, nSlice, nTime], dictionary - keys: Spacing, Origin, ImageOrientationPatient, PatientPosition, Dimensions, Times
- Return type:
tuple
- getSeriesOverview(tagList=['SeriesNumber', 'SeriesDescription', 'PulseSequenceName', 'SeriesInstanceUID'])[source]
- getStudyOutputDir(rootDir='', studyPrefix='')[source]
Generate a study output directory name based on config setting STUDY_NAMINF_TAG_LIST
- Parameters:
rootDir (str, optional) – The root directory to build study directory in. Defaults to ‘’.
studyPrefix (str, optional) – Optional prefix to add to naming. Defaults to ‘’.
- Returns:
Path to directory at Study level where dicoms will be written
- Return type:
str
- getTagValuesList(tagList, RETURN_STR)[source]
Build table with file name and value from each tag in list. Return list of lists
- resetUIDs(studyUID)[source]
Reset SOPInstanceUID, SeriesInstanceUID and StudyInstaceUID (must pass last)
- Parameters:
studyUID (str) – UID - can use str(generate_uid())
- classmethod setFromDirectory(dirName, OVERVIEW=False, HIDE_PROGRESSBAR=False, FORCE_READ=False, ONE_FILE_PER_DIR=False)[source]
Initialise object from directory of dicom files.
- Parameters:
dirName (str) – Path to directory of dicom files
OVERVIEW (bool, optional) – Set attribute OVERVIEW. Defaults to False.
HIDE_PROGRESSBAR (bool, optional) – Set attribute HIDE_PROGRESSBAR. Defaults to False.
FORCE_READ (bool, optional) – Set attribute FORCE_READ. Defaults to False.
ONE_FILE_PER_DIR (bool, optional) – Read only one file per directory for fast applications with meta interest only. Defaults to False.
- Raises:
ValueError – If dicom files belonging to more than one study are found.
ValueError – If dicom files belonging to more than one series are found.
- Returns:
An instance of DicomSeries class.
- Return type:
- classmethod setFromFileList(fileList, OVERVIEW=False, HIDE_PROGRESSBAR=False, FORCE_READ=False)[source]
Initialise object from list of files
- Parameters:
fileList (list) – List of full file names
OVERVIEW (bool, optional) – Set attribute OVERVIEW. Defaults to False.
HIDE_PROGRESSBAR (bool, optional) – Set attribute HIDE_PROGRESSBAR. Defaults to False.
FORCE_READ (bool, optional) – Set attribute FORCE_READ. Defaults to False.
- Raises:
ValueError – If dicom files belonging to more than one study are found.
ValueError – If dicom files belonging to more than one series are found.
- Returns:
An instance of DicomSeries class.
- Return type:
- property sliceLocations
- writeToNII(outputPath, outputNamingTags=('PatientName', 'SeriesNumber', 'SeriesDescription'))[source]
Will write DicomSeries as nii.gz file (uses dcm2niix found on local system)
- Parameters:
outputPath (str) – Directory where to save output (if full pathname, with extn, is given then this is used)
outputNamingTags (tuple, optional) – Tags to use to name output. If outputPath contains extension then not used. Defaults to (‘PatientName’, ‘SeriesNumber’, ‘SeriesDescription’).
- Returns:
Name of files saved
- Return type:
str
- writeToOrganisedFileStructure(studyOutputDir, SAFE_NAMING_CHECK=True, seriesOutDirName=None)[source]
Recurse down directory tree - grab dicoms and move to new hierarchical folder structure rooted at ‘studyOutputDir’
- writeToVTI(outputPath, outputNamingTags=('PatientName', 'SeriesNumber', 'SeriesDescription'), TRUE_ORIENTATION=False)[source]
Write DicomSeries as VTK ImageData (*.vti)
- Parameters:
outputPath (str) – Directory to save in or full filename to save
outputNamingTags (tuple, optional) – Tags to use for naming, only used if full outputpath not given. Defaults to (‘PatientName’, ‘SeriesNumber’, ‘SeriesDescription’).
TRUE_ORIENTATION (bool, optional) – To apply matrix to VTI data. Defaults to False.
- Returns:
Name of file saved
- Return type:
str
- writeToVTS(outputPath, outputNamingTags=('PatientName', 'SeriesNumber', 'SeriesDescription'))[source]
Write DicomSeries as VTK StructuredImageData (*.vts)
- Parameters:
outputPath (str) – Directory to save in or full filename to save.
outputNamingTags (tuple, optional) – Tags to use for naming, only used if full outputpath not given. Defaults to (‘PatientName’, ‘SeriesNumber’, ‘SeriesDescription’).
- Returns:
Name of file saved
- Return type:
str
- class spydcmtk.dcmTK.DicomStudy(dSeriesList, OVERVIEW=False, HIDE_PROGRESSBAR=False)[source]
Bases:
list
Extends list of DicomSeries objects (creating list of list of pydicom.dataset)
- getPatientOverview(tagList=['PatientName', 'PatientID', 'PatientBirthDate', 'PatientSex', 'PatientAge', 'PatientWeight'])[source]
- getSeriesMatchingDescription(matchingStrList, RETURN_SERIES_OBJ=False, REDUCE_MULTIPLE=False)[source]
- getStudyOverview(tagList=['StudyID', 'ScannerStudyID', 'StudyDescription', 'StudyTime', 'StudyDate', 'AccessionNumber', 'ProtocolName', 'InstitutionName', 'StudyInstanceUID', 'MagneticFieldStrength'])[source]
- classmethod setFromDictionary(dicomDict, OVERVIEW=False, HIDE_PROGRESSBAR=False, FORCE_READ=False)[source]
- classmethod setFromDirectory(dirName, OVERVIEW=False, HIDE_PROGRESSBAR=False, FORCE_READ=False, ONE_FILE_PER_DIR=False)[source]
- writeFDQ(seriesNumber_list, outputFileName, phase_factors=[1, 1, 1], VERBOSE=True)[source]
Writes a 4D-flow output as VTS format.
- Parameters:
seriesNumber_list (list) – A list of series numbers identifying mag and 3 phase series. Mag, X, Y, Z phases
outputFileName (str) – The name of the pvd file to write to.
- Returns:
the pvd file written
- Return type:
str
- class spydcmtk.dcmTK.ListOfDicomStudies(dStudiesList, OVERVIEW=False, HIDE_PROGRESSBAR=False)[source]
Bases:
list
Extends list of DicomStudies objects (creating list of list of list of pydicom.dataset)
- buildMSTable(DICOM_TAGS=['SeriesNumber', 'SeriesDescription', 'PulseSequenceName', 'SeriesInstanceUID'])[source]
- classmethod setFromDcmDict(dicomDict, OVERVIEW=False, HIDE_PROGRESSBAR=False, FORCE_READ=False)[source]
- classmethod setFromDirectory(dirName, OVERVIEW=False, HIDE_PROGRESSBAR=False, FORCE_READ=False, ONE_FILE_PER_DIR=False, extn_filter=None)[source]
- classmethod setFromInput(input, OVERVIEW=False, HIDE_PROGRESSBAR=False, FORCE_READ=False, ONE_FILE_PER_DIR=False)[source]
- classmethod setFromTar(tarFileName, HIDE_PROGRESSBAR=False, FORCE_READ=False, FIRST_ONLY=False, matchTagPair=None)[source]
- spydcmtk.dcmTK.organiseDicoms(dcmDirectory, outputDirectory, anonName=None, anonID='', FORCE_READ=False, HIDE_PROGRESSBAR=False, REMOVE_PRIVATE_TAGS=False)[source]
Recurse down directory tree - grab dicoms and move to new hierarchical folder structure
- spydcmtk.dcmTK.studySummary(pathToDicoms)[source]
- Parameters:
pathToDicoms – path to dicoms - anywhere in the tree above - will search down tree till find a dicom
- Returns:
a formatted string
- spydcmtk.dcmTK.writeImageStackToDicom(images_sortedList, patientMeta, dcmTemplateFile_or_ds, outputDir, tagUpdateDict=None)[source]
spydcmtk.dcmTools module
Basic helper tools here
- class spydcmtk.dcmTools.DicomTags[source]
Bases:
object
- AccessionNumber = (8, 80)
- AcquisitionMatrix = (24, 4880)
- BodyPartExamined = (24, 21)
- CardiacNumberOfImages = (24, 4240)
- EchoTime = (24, 129)
- FlipAngle = (24, 4884)
- HeartRate = (24, 4232)
- ImageOrientationPatient = (32, 55)
- ImagePositionPatient = (32, 50)
- InstanceNumber = (32, 19)
- InversionTime = (24, 130)
- MagneticFieldStrength = (24, 135)
- Manufacturer = (8, 112)
- ManufacturerModelName = (8, 4240)
- Modality = (8, 96)
- NominalInterval = (24, 4194)
- NumberOfAverages = (24, 131)
- PatientDateOfBirth = (16, 48)
- PatientID = (16, 32)
- PatientName = (16, 16)
- PatientOrientation = (32, 32)
- PatientPosition = (24, 20736)
- PatientSex = (16, 64)
- PixelSpacing = (40, 48)
- ReceiveCoilName = (24, 4688)
- RepetitionTime = (24, 128)
- SeriesDescription = (8, 4158)
- SeriesInstanceUID = (32, 14)
- SeriesNumber = (32, 17)
- SliceThickness = (24, 80)
- SoftwareVersions = (24, 4128)
- SpacingBetweenSlices = (24, 136)
- StudyDate = (8, 32)
- StudyDescription = (8, 4144)
- StudyID = (32, 16)
- StudyInstanceUID = (32, 13)
- TriggerTime = (24, 4192)
- TriggerWindow = (24, 4244)
- class spydcmtk.dcmTools.NumpyEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]
Bases:
JSONEncoder
Special json encoder for numpy types
- default(obj)[source]
Implement this method in a subclass such that it returns a serializable object for
o
, or calls the base implementation (to raise aTypeError
).For example, to support arbitrary iterators, you could implement default like this:
def default(self, o): try: iterable = iter(o) except TypeError: pass else: return list(iterable) # Let the base class default method raise the TypeError return JSONEncoder.default(self, o)
- spydcmtk.dcmTools.anonymiseDicomDS(dataset, UIDupdateDict={}, anon_birthdate=True, remove_private_tags=False, anonName=None, anonID='')[source]
- spydcmtk.dcmTools.getDicomDictFromTar(tarFileToRead, QUIET=True, FORCE_READ=False, FIRST_ONLY=False, OVERVIEW_ONLY=False, matchingTagValuePair=None)[source]
- spydcmtk.dcmTools.getDicomDictFromZip(zipFileToRead, QUIET=True, FORCE_READ=False, FIRST_ONLY=False, OVERVIEW_ONLY=False, matchingTagValuePair=None)[source]
Read a zip archive, extract dicoms to structures dictionary
- spydcmtk.dcmTools.getRootDirWithSEdirs(startDir)[source]
- Search from startDir until find rootDir with format of subdirs:
SE123_ etc
param1: start directory of search return: rootdirectory with subfolders of SE{int}_ format (startDir if not found)
- spydcmtk.dcmTools.organiseDicomHeirarchyByUIDs(rootDir, HIDE_PROGRESSBAR=False, FORCE_READ=False, ONE_FILE_PER_DIR=False, OVERVIEW=False, extn_filter=None, DEBUG=False)[source]
Find all dicoms under “rootDir” and organise based upon UIDs
- Parameters:
rootDir (str) – Directory path under which to search
HIDE_PROGRESSBAR (bool, optional) – To hide tqdm progress bar. Defaults to False.
FORCE_READ (bool, optional) – Will tell pydicom to force read files that do not conform to dicom standard. Defaults to False.
ONE_FILE_PER_DIR (bool, optional) – For a fast summary, will read only first file found per subdirectory (if one knows that dicoms are already organised in such a format). Defaults to False.
OVERVIEW (bool, optional) – Will not read pixel data. Defaults to False.
extn_filter (str, optional) – For faster reading of large multi data directory trees pass an extension to filter upon (e.g. dcm) then will only read files ending in this extension. Defaults to None.
DEBUG (bool, optional) – Set true for debugging actions. Defaults to False.
- Returns:
A larger dictionary structure of {studyUID: {seriesUID: [list of pydicom datasets]}}
- Return type:
dict
- spydcmtk.dcmTools.readDicomFile_intoDict(dcmFile, dsDict, FORCE_READ=False, OVERVIEW=False)[source]
- spydcmtk.dcmTools.sliceLoc_InstanceNumberSortKey(val)[source]
Sort by slice location 1st (group all slices together), then instance number
- spydcmtk.dcmTools.streamDicoms(inputDir, outputDir, FORCE_READ=False, HIDE_PROGRESSBAR=False, SAFE_NAMING=False, anonName=None, anonID='')[source]
- spydcmtk.dcmTools.writeDirectoryToNII(dcmDir, outputPath, fileName)[source]
- Write directory of dicom files to nifti file.
Requires dcm2nii which must be in path or provided via config. Also writes json sidecar. s
- Parameters:
dcmDir (str) – Directory under which to find DICOMS
outputPath (str) – Directory where to save output
fileName (str) – Filename for output
- Raises:
OSError – If dcm2nii path is not found
- Returns:
full filename of new nifti file
- Return type:
str
spydcmtk.dcmVTKTK module
Created on MArch 2023 (rewrite from old module - remove reliance on VTKDICOM)
@author: fraser
Dicom to VTK conversion toolkit
- class spydcmtk.dcmVTKTK.PatientMeta[source]
Bases:
object
A class that manages spatial / geometric information for DICOM and VTK conversion
_meta keys: ‘ImagePositionPatient’, ‘PixelSpacing’, ‘ImageOrientationPatient’, ‘SliceVector’, ‘SliceThickness’, ‘SliceLocation0’, ‘SpacingBetweenSlices’, ‘Dimensions’
- property Dimensions
- property ImageOrientationPatient
- property ImagePositionPatient
- property Origin
- property PatientPosition
- property PixelSpacing
- property SliceLocation0
- property SliceThickness
- property SliceVector
- property Spacing
- property SpacingBetweenSlices
- property Times
- spydcmtk.dcmVTKTK.arrToVTI(arr: ndarray, patientMeta: PatientMeta, ds: Dataset | None = None, TRUE_ORIENTATION: bool = False, outputPath: str | None = None) Dict[float, vtkImageData] [source]
Convert array (+meta) to VTI dict (keys=times, values=VTI volumes).
- Parameters:
arr (np.array) – Array of pixel data, shape: nR,nC,nSlice,nTime
patientMeta (PatientMatrix) – PatientMatrix object containing meta to be added as Field data
ds (pydicom dataset [optional]) – pydicom dataset to use to add dicom tags as field data
TRUE_ORIENTATION (bool [False]) – Boolean to force accurate spatial location of image data. NOTE: this uses resampling from VTS data so output VTI will have different dimensions.
outputPath (str [None]) – Save as go, then rename at end - RAM friendly
- Returns:
vtiDict
- Raises:
ValueError – If VTK import not available
- spydcmtk.dcmVTKTK.arrToVTS(arr: ndarray, patientMeta: PatientMeta, ds: Dataset | None = None, outputPath: str | None = None) Dict[float, vtkStructuredGrid] [source]
- spydcmtk.dcmVTKTK.array_to_DcmSeg(arr, source_dicom_ds_list, dcmSegFileOut=None, algorithm_identification=None)[source]
- spydcmtk.dcmVTKTK.filterResampleToImage(vtsObj: vtkStructuredGrid, target_spacing: List[float]) vtkStructuredGrid [source]
- spydcmtk.dcmVTKTK.mergePhaseSeries4D(magPVD, phasePVD_list, outputPVDName, phase_factors, phase_offsets, DEL_ORIGINAL=True)[source]
- spydcmtk.dcmVTKTK.readImageStackToVTI(imageFileNames: List[str], patientMeta: PatientMeta | None = None, arrayName: str = 'PixelData', CONVERT_TO_GREYSCALE: bool = False) vtkImageData [source]
- spydcmtk.dcmVTKTK.writeArrToVTI(arr: ndarray, patientMeta: PatientMeta, filePrefix: str, outputPath: str, ds: Dataset | None = None, TRUE_ORIENTATION: bool = False) str [source]
Will write a VTI file(s) from arr (if np.ndim(arr)=4 write vti files + pvd file)
- Parameters:
arr (np.array) – Array of pixel data, shape: nR,nC,nSlice,nTime
patientMeta (PatientMatrix) – PatientMatrix object containing meta to be added as Field data
filePrefix (str) – File name prefix (if nTime>1 then named ‘{fileprefix}_{timeID:05d}.vti)
outputPath (str) – Output path (if nTime > 1 then ‘{fileprefix}.pvd written to outputPath and sub-directory holds *.vti files)
ds (pydicom dataset [optional]) – pydicom dataset to use to add dicom tags as field data
- Raises:
ValueError – If VTK import not available
spydcmtk.spydcm module
Module that exposes the routines and utilities making up SPYDCMTK
- class spydcmtk.spydcm.MyParser(prog=None, usage=None, description=None, epilog=None, parents=[], formatter_class=<class 'argparse.HelpFormatter'>, prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='error', add_help=True, allow_abbrev=True, exit_on_error=True)[source]
Bases:
ArgumentParser
- spydcmtk.spydcm.buildTableOfDicomParamsForManuscript(topLevelDirectoryList, outputCSVPath, seriesDescriptionIdentifier=None, ONE_FILE_PER_DIR=True)[source]
- Build a simple table of dicom parameters that would be suitable for input into a scientific manuscript.
Output is comma delimited multiline string of Tr, Te (etc) stats.
- Parameters:
topLevelDirectoryList (list) – list of str that are paths to directories containing dicom files
outputCSVPath (str) – path to outputCSV
seriesDescriptionIdentifier (str, optional) – A substring of SeriesDescription tag used to select certian series only. Defaults to None.
ONE_FILE_PER_DIR (bool, optional) – Set false to read all dicoms, can set True for faster reading if dicoms organised. Default: True
- spydcmtk.spydcm.convertInputsToHTML(listOfFilePaths, outputFile=None, glanceHtml=None, QUIET=False, DEBUG=False)[source]
Convert inputs to HTML viewable via ParaViewGlance (3D volumes and/or surface polymeshes)
Keyword arguments: listOfFilePaths – May be nii, vtk or dicoms outputFile (optional) – Full path to outputfile, if not given then use first input path. Defaults to None. glanceHtml (optional) – Full path to glanceHtml template file, if not given then use default. Defaults to None. QUIET (optional) – Set True to suppress output. Defaults to False. DEBUG (optional) – Set True to prevent cleanup of intermediary files. Defaults to False. Return: path to html file written
- spydcmtk.spydcm.directoryToVTI(dcmDirectory, outputFolder, outputNamingTags=['PatientName', 'SeriesNumber', 'SeriesDescription'], QUITE=True, FORCE=False, TRUE_ORIENTATION=False)[source]
- Convert directory of dicoms to VTI files (one vti per series)
Naming built from dicom tags:
- Parameters:
dcmDirectory (str) – Directory containing dicom files
outputFolder (str) – Directory where vti output files to be written
outputNamingTags (tuple, optional) – Dicom tags used to generate vti file name. Defaults to (‘PatientName’, ‘SeriesNumber’, ‘SeriesDescription’)
QUITE (bool, optional) – Suppress output information. Defaults to True.
FORCE (bool, optional) – Set True to overwrite already present files. Defaults to False.
- Returns:
List of output file names written
- Return type:
list
- spydcmtk.spydcm.directoryToVTS(dcmDirectory, outputFolder, outputNamingTags=['PatientName', 'SeriesNumber', 'SeriesDescription'], QUITE=True, FORCE=False)[source]
- Convert directory of dicoms to VTS files (Good for cine etc)
Naming built from dicom tags:
- Parameters:
dcmDirectory (str) – Directory containing dicom files
outputFolder (str) – Directory where vti output files to be written
outputNamingTags (tuple, optional) – Dicom tags used to generate vti file name. Defaults to (‘PatientName’, ‘SeriesNumber’, ‘SeriesDescription’)
QUITE (bool, optional) – Suppress output information. Defaults to True.
FORCE (bool, optional) – Set True to overwrite already present files. Defaults to False.
- Returns:
List of output file names written
- Return type:
list
- spydcmtk.spydcm.getTag(pathToDicoms, tagName)[source]
Convienience function to find first dicom and then get tag value
- Parameters:
pathToDicoms (str) – path to dicoms
tagName (str) – dicom tag name
- spydcmtk.spydcm.returnFirstDicomFound(rootDir, FILE_NAME_ONLY=False, MatchingTag_dict=None)[source]
Search recursively for first dicom file under root and return. If have dicoms in nice folder structure then this can be a fast way to find, e.g. all series with protocol X
- Parameters:
rootDir – directory on filesystem
FILE_NAME_ONLY – If true will return the file name [Default False]
MatchingTag_dict – If given then will only consider dicoms where tag(key) matches value given [Default None]
- Returns:
pydicom dataset<without pixel data> or fileName<str>
- spydcmtk.spydcm.writeDirectoryToNII(dcmDir, outputPath, fileName)[source]
- Write a directory of dicom files to a Nifti (*.nii.gz) file.
Uses dcm2nii so MUST have dcm2nii installed and within path.
- Parameters:
dcmDir (str) – Path to directory containing dicom files
outputPath (str) – Path to output directory where to save nifti
fileName (str) – Name of output nii.gz file (will rename nii.gz output from dcm2nii)