Image Reading and Writing

A collection of useful functions for reading and writing images, implemented in the fredtools.ImgIO subpackage. The supported image types are:

  • MetaImage format in single files (*.mha) or in a header with a separate data file (*.mhd+*.raw),

  • NRRD format in single files (*.nrrd) or in a header with a separate data file (*.nhdr+*.raw),

  • TIFF format (reading only), e.g. scans of radiochromic films,

  • Dicom format (reading only) for 3D/2D images (e.g. dose distribution), Structures (i.e. RS*.dcm), Proton treatment plans (i.e. RN*.dcm or RP*.dcm) and CT images,

  • Influence matrices produced by the FRED Monte Carlo,

  • OmniPro measurement files.

MetaImage files (*.mhd, *.mha)

fredtools.readMHD(fileNames: Iterable[PathLike | str] | PathLike | str, displayInfo: bool = False) → Image | tuple[Image, ...]

Read MetaImage image to SimpleITK image object.

The function reads a single MetaImage file or an iterable of MetaImage files and creates an instance or tuple of instances of a SimpleITK object. Both layouts of the format are read, regardless of the extension: a single file with the header and the data (usually with the .mha extension) and a header with a separate data file (usually with the .mhd extension).

Parameters:
  • fileNames (string or array_like) – A path or an iterable (list, tuple, etc.) of paths to MetaImage file.

  • displayInfo (bool, optional) – Displays a summary of the function results. (def. False)

Returns:

Object or tuple of objects of a SimpleITK image.

Return type:

SimpleITK Image or tuple

Raises:
  • FileNotFoundError – If a file does not exist.

  • TypeError – If a file is not a MetaImage file.

  • RuntimeError – If a file cannot be read by SimpleITK, for instance when the data file of a header is missing.

See also

writeMHD

writing MetaImage file.

SimpleITK.ReadImage

SimpleITK routine for reading files.

Notes

The layout of a file is recognised by its header and not by its extension. Therefore, the single files with the .mhd extension, which were written by the earlier versions of FREDtools, are read as well.

fredtools.writeMHD(img: Image, filePath: PathLike | str, overwrite: bool = True, useCompression: bool = False, compressionLevel: int = 5, displayInfo: bool = False) → None

Write image to MetaImage format.

The function writes a SimpleITK image object to a MetaImage file. The layout of the file is chosen by the extension of filePath, following the convention of ITK. For the .mha extension, a single file with the header and the data is written. For the .mhd extension, the header is written to the .mhd file and the data to a separate file with the same name and the .raw extension (or .zraw, when the compression is used). The metadata of the image are saved in the header and the image is not changed.

Parameters:
  • img (SimpleITK Image) – Object of a SimpleITK image.

  • filePath (path) – Path to file to be saved, with the .mha extension for a single file or the .mhd extension for a header with a separate data file.

  • overwrite (bool, optional) – Overwrite the file if it exists, otherwise, raise an error. For the .mhd extension, this applies also to the data file. (def. True)

  • useCompression (bool, optional) – Determine if a compression will be used when saving the file. (def. False)

  • compressionLevel (unsigned int, optional) – Determine the compression level. For MetaImage files, the useful range is 1-9 (zlib compression levels); higher values do not increase the compression. (def. 5)

  • displayInfo (bool, optional) – Displays a summary of the function results. (def. False)

Raises:
  • TypeError – If img is not an instance of a SimpleITK image object.

  • ValueError – If the extension of filePath is not .mha or .mhd, if the file exists and overwrite is False, or if a metadata entry of the image cannot be saved in a MetaImage file.

  • RuntimeError – If the file cannot be written by SimpleITK.

See also

readMHD

reading MetaImage file.

SimpleITK.WriteImage

SimpleITK routine for writing files.

Notes

The earlier versions of FREDtools wrote a single file with the .mhd extension by default. Now the .mhd extension always means a header with a separate data file, and a warning is logged when such a file is written, to remind of this change. The single files with the .mhd extension are still read by readMHD, and they can be renamed to .mha.

The metadata are saved as lines of text in the header, which means that:

  • a metadata entry with an empty value cannot be saved and is skipped,

  • a metadata entry with a line break in its value, or with the key ElementDataFile, would damage the file, therefore an error is raised and nothing is written.

The warnings of ITK, which are raised for each skipped metadata entry, are switched off for the time of writing the file.

NRRD files (*.nrrd, *.nhdr)

fredtools.readNRRD(fileNames: Iterable[PathLike | str] | PathLike | str, displayInfo: bool = False) → Image | tuple[Image, ...]

Read NRRD image to SimpleITK image object.

The function reads a single NRRD (Nearly Raw Raster Data) file or an iterable of NRRD files and creates an instance or tuple of instances of a SimpleITK object. Both layouts of the format are read: a single file with the header and the data (usually with the .nrrd extension) and a header with a separate data file (usually with the .nhdr extension).

Parameters:
  • fileNames (string or array_like) – A path or an iterable (list, tuple, etc.) of paths to NRRD file.

  • displayInfo (bool, optional) – Displays a summary of the function results. (def. False)

Returns:

Object or tuple of objects of a SimpleITK image.

Return type:

SimpleITK Image or tuple

Raises:
  • FileNotFoundError – If a file does not exist.

  • TypeError – If a file is not a NRRD file.

  • RuntimeError – If a file cannot be read by SimpleITK, for instance when the data file of a header is missing.

See also

writeNRRD

writing NRRD file.

SimpleITK.ReadImage

SimpleITK routine for reading files.

Notes

The files are read with the NRRD reader of SimpleITK, which means that:

  • the positions are given in the LPS (left-posterior-superior) convention used by ITK and DICOM. For a file defined in another anatomical space (e.g. right-anterior-superior), the origin and the direction of the image are converted, and the voxels are not reordered,

  • an axis which is not a spatial one (e.g. of the list, vector or RGB-color kind) becomes the components of a vector image,

  • the fields of the header are available in the metadata of the image under the keys starting with NRRD_, and the key/value pairs under their keys.

fredtools.writeNRRD(img: Image, filePath: PathLike | str, overwrite: bool = True, useCompression: bool = False, compressionLevel: int = 5, displayInfo: bool = False) → None

Write image to NRRD format.

The function writes a SimpleITK image object to a NRRD (Nearly Raw Raster Data) file. The layout of the file is chosen by the extension of filePath. For the .nrrd extension, a single file with the header and the data is written. For the .nhdr extension, the header is written to the .nhdr file and the data to a separate file with the same name and the .raw extension (or .raw.gz, when the compression is used). The metadata of the image are saved in the header.

Parameters:
  • img (SimpleITK Image) – Object of a SimpleITK image.

  • filePath (path) – Path to file to be saved, with the .nrrd extension for a single file or the .nhdr extension for a header with a separate data file.

  • overwrite (bool, optional) – Overwrite the file if it exists, otherwise, raise an error. For the .nhdr extension, this applies also to the data file. (def. True)

  • useCompression (bool, optional) – Determine if a compression will be used when saving the file. (def. False)

  • compressionLevel (unsigned int, optional) – Determine the compression level. For NRRD files, the useful range is 1-9 (gzip compression levels); higher values do not increase the compression. (def. 5)

  • displayInfo (bool, optional) – Displays a summary of the function results. (def. False)

Raises:
  • TypeError – If img is not an instance of a SimpleITK image object.

  • ValueError – If the extension of filePath is not .nrrd or .nhdr, or if the file exists and overwrite is False.

  • RuntimeError – If the file cannot be written by SimpleITK.

See also

readNRRD

reading NRRD file.

SimpleITK.WriteImage

SimpleITK routine for writing files.

TIFF files (*.tif, *.tiff)

fredtools.readTIFF(fileNames: Iterable[PathLike | str] | PathLike | str, displayInfo: bool = False) → Image | tuple[Image, ...]

Read TIFF image to SimpleITK image object.

The function reads a single TIFF file or an iterable of TIFF files, for instance scans of radiochromic films, and creates an instance or tuple of instances of a SimpleITK object describing a 2D image. The pixel size is calculated from the resolution (DPI) saved in the file, the image is centered at (0, 0) unless the file defines its position, and the image is not rotated.

Parameters:
  • fileNames (string or array_like) – A path or an iterable (list, tuple, etc.) of paths to TIFF file.

  • displayInfo (bool, optional) – Displays a summary of the function results. (def. False)

Returns:

Object or tuple of objects of a SimpleITK 2D image.

Return type:

SimpleITK Image or tuple

Raises:
  • FileNotFoundError – If a file does not exist.

  • TypeError – If a file is not a TIFF file, or if its structure or pixel type is not supported.

  • NotImplementedError – If a file has more than one page.

  • RuntimeError – If a file cannot be read by SimpleITK.

See also

SimpleITK.ReadImage

SimpleITK routine for reading files.

expandDimsImg

expand the dimension of an image, e.g. from a 2D image to a 3D slice.

Notes

The pixel values are read with the TIFF reader of SimpleITK and the geometry of the image is taken from the tags of the file:

  • the pixel size in mm is calculated from the XResolution, YResolution and ResolutionUnit tags, i.e. from the number of pixels per inch (DPI) or per centimeter. The unit is inch when the ResolutionUnit tag is missing. If the file does not define the resolution or its unit, the pixel size is set to 1 mm and a warning is logged,

  • the image is centered, i.e. fredtools.getImageCenter is (0, 0), unless the file has the XPosition and YPosition tags (and defines the pixel size). These tags describe the position of the left and top edges of the image, therefore fredtools.getExtent starts at this position. The way the position was determined is logged at the debug level,

  • the direction of the image is identity. The rows are in the order of the file, therefore the first row of the image is the top of the scan and has the lowest Y coordinate,

  • a color file (e.g. RGB) is read to a vector image with one component per channel, and the pixel values are not converted or scaled,

  • the text tags of the file (e.g. ImageDescription, Software or Artist) are available in the metadata of the image.

Multi-page TIFF files are not supported, and neither are the files for which SimpleITK cannot return the pixel values as they are stored (e.g. tiled, 1-bit, planar or indexed-color files).

The tags are read with the Pillow library, which refuses to open images above about 179 megapixels and warns above about 89 megapixels. The limit can be lifted with PIL.Image.MAX_IMAGE_PIXELS = None before calling the function.

DICOM files (*.dcm, *.dicom)

fredtools.getDicomTypeName(dicomVar: PathLike | str | Dataset | FileDataset) → str

Check the type of the dicom given as a path or tags.

The function returns the name of the SOP Class UID tag of a dicom file given as a file name or dicom tags. The description of the SOP Class UID names can be found in [1].

Parameters:

dicomVar (path or tags) – A string of path to a dicom file or a dicom tag structure read by pydicom.dcmread.

Returns:

A string of the SOP Class UID name.

Return type:

string

Raises:
  • TypeError – If dicomVar is not an instance of dicom.dataset.FileDataset.

  • ValueError – If the ‘SOPClassUID’ tag cannot be found in the dicom tags.

See also

sortDicoms

sort dicom files in a folder by type.

fredtools.sortDicoms(searchFolder: PathLike | str, recursive: bool = False, displayInfo: bool = False) → DottedDict

Sort dicom file names found in the search folder for CT, RS, RN, RD, PET and Unknown.

The function sorts file names found in the searchFolder (and subfolders if requested) for:

  • CT - dicom files of CT Image Storage (“CT Image Storage”, “Enhanced CT Image Storage” or “Legacy Converted Enhanced CT Image Storage”)

  • RS - dicom files of RT Structure Set Storage

  • RN - dicom files of RT Plan Storage (“RT Plan Storage” or “RT Ion Plan Storage”)

  • RD - dicom files of 1D/2D/3D RT Dose Storage (for instance dose distribution)

  • PET - dicom files of PET Image Storage (“Positron Emission Tomography Image Storage”)

  • Unknown - files with *.dcm extension that were not recognised.

Parameters:
  • searchFolder (path) – The path to be searched.

  • recursive (bool, optional) – Search for files recursively. (def. False)

  • displayInfo (bool, optional) – Displays a summary of the function results. (def. False)

Returns:

Dictionary (dotted_dict.DottedDict) with the sorted file names. If only a single file name is found for a given dicom type, then the one-element list is collapsed to a single file name string.

Return type:

DottedDict

See also

getDicomsInfo

read the identity and the references of all the dicoms in a folder in a single pass.

sortDicomsFromInfo

group the dicoms information by the dicom type.

Notes

The function is a thin wrapper over getDicomsInfo and sortDicomsFromInfo, which read the type of every dicom only once. The dicom file names are returned in the order they were found in the search folder and are not sorted.

fredtools.getRNMachineName(fileName: PathLike | str, displayInfo: bool = False) → str

Get the machine name defined in the RN plan.

The function retrieves the machine name defined in the RN dicom file. The name is read from the ‘TreatmentMachineName’ tag of each TREATMENT beam and it is validated that it is the same for all of them.

Parameters:
  • fileName (path) – Path to RN dicom file.

  • displayInfo (bool, optional) – Displays a summary of the function results. (def. False)

Returns:

Treatment machine name.

Return type:

string

Raises:
  • TypeError – If the dicom is not of RN type, or if the beam sequence cannot be recognised as ‘RT Plan Storage’ or ‘RT Ion Plan Storage’.

  • ValueError – If the beam sequence cannot be found in the dicom, or if the ‘TreatmentMachineName’ tags are not the same for all TREATMENT beams.

See also

getRNFields

get a summary of parameters for each field defined in the RN plan.

getRNSpots

get a summary of parameters for each spot defined in the RN plan.

getRNInfo

get some basic information from the RN plan.

fredtools.getRNIsocenter(fileName: PathLike | str, displayInfo: bool = False) → tuple

Get the isocenter position defined in the RN plan.

The function retrieves the isocenter position defined in the RN dicom file. The isocenter is defined for each field separately but usually, it is the same for all fields. If it is not the same then a warning is raised and a geometrical center is returned.

Parameters:
  • fileName (path) – Path to RN dicom file.

  • displayInfo (bool, optional) – Displays a summary of the function results. (def. False)

Returns:

3-element tuple of XYZ isocenter coordinates in [mm].

Return type:

tuple

Raises:
  • TypeError – If the dicom is not of RN type, or if the beam sequence cannot be recognised as ‘RT Plan Storage’ or ‘RT Ion Plan Storage’.

  • ValueError – If the beam sequence cannot be found in the dicom, or if no isocenter position can be found for any TREATMENT field.

See also

getRNFields

get a summary of parameters for each field defined in the RN plan.

getRNSpots

get a summary of parameters for each spot defined in the RN plan.

getRNInfo

get some basic information from the RN plan.

fredtools.getRNInfo(fileName: PathLike | str, displayInfo: bool = False) → DottedDict

Get some information from the RN plan.

The function retrieves some useful information from a RN dicom of a treatment plan. Following information are saved to a dictionary:

  • RNFileName : absolute path to the RN file.

  • dosePrescribed : dose prescribed to the target (see notes below).

  • fractionNo : number of the fractions planned.

  • targetStructName : name of the structure which the plan was prepared for (does not work for all RN dicoms).

  • planLabel : name of the treatment plan (can be empty for anonymized DICOM).

  • planDate : date of the plan creation (can be empty for anonymized DICOM).

  • planTime : time of the plan creation (can be empty for anonymized DICOM).

  • patientName : name of the patient (can be empty for anonymized DICOM).

  • patientBirthDate : birth date of the patient (can be empty for anonymized DICOM).

  • patientID : ID of the patient (can be empty for anonymized DICOM).

  • manufacturer : manufacturer of the treatment planning system.

  • softwareVersions : version of the treatment planning system.

  • stationName : name of the station on which the plan was prepared.

  • machineName : name of the treatment machine.

  • totalFieldsNumber : total number of fields defined in the plan.

  • treatmentFieldsNumber : number of fields with TREATMENT delivery type.

  • setupFieldsNumber : number of fields with SETUP delivery type.

  • otherFieldsNumber : number of fields with other delivery types.

Parameters:
  • fileName (path) – Path to RN dicom file.

  • displayInfo (bool, optional) – Displays a summary of the function results. (def. False)

Returns:

Dictionary with the RN treatment plan parameters.

Return type:

dict

Raises:
  • TypeError – If the dicom is not of RN type, or if the beam sequence cannot be recognised as ‘RT Plan Storage’ or ‘RT Ion Plan Storage’.

  • ValueError – If the beam sequence cannot be found in the dicom, or if the ‘TreatmentMachineName’ tags are not the same for all TREATMENT beams.

See also

getRNFields

get a summary of parameters for each field defined in the RN plan.

getRNSpots

get a summary of parameters for each spot defined in the RN plan.

Notes

The prescribed dose, dosePrescribed, is read from TargetPrescriptionDose in DoseReferenceSequence, but if this is not available it is calculated as the sum of BeamDose in FractionGroupSequence[0].ReferencedBeamSequence multiplied by the number of fractions.

fredtools.getRNFields(fileName: PathLike | str, raiseWarning=True, displayInfo: bool = False) → DataFrame

Get the parameters of each field defined in the RN file.

The function retrieves information for each field defined in the RN dicom file. Only the fields with TREATMENT delivery type are included, and the spots with zero (or negative) meterset weight are excluded from the field statistics. A consistency check is performed to check the correctness of the parameters written in the RN dicom file.

Parameters:
  • fileName (path) – Path to RN dicom file.

  • raiseWarning (bool, optional) – Raise warnings if the consistency check fails. (def. True)

  • displayInfo (bool, optional) – Displays a summary of the function results. (def. False)

Returns:

DataFrame indexed by FDeliveryNo (field delivery number) with one row per TREATMENT field and the following columns (columns with no values in the plan are dropped; a column value is the literal string ‘var’ when the parameter varies between the spots of the field):

  • FNo : field (beam) number.

  • FName : field (beam) name.

  • FGantryAngle : gantry angle in [deg].

  • FCouchAngle : couch (patient support) angle in [deg].

  • FCouchPitchAngle : couch pitch angle in [deg].

  • FCouchRollAngle : couch roll angle in [deg].

  • FIsoPos : isocenter position (3-element XYZ) in [mm].

  • FRSID : range shifter ID.

  • FSnoutPos : snout position in [mm].

  • FEnergyNo : number of energy layers.

  • FEnergyMin, FEnergyMax : minimum and maximum nominal energy in [MeV].

  • FSpotNo : number of spots with positive meterset weight.

  • FDose : field dose in [Gy].

  • FDosePos : field dose specification point (3-element XYZ) in [mm].

  • FMU : field meterset in [MU].

  • FCumMsW : final cumulative meterset weight.

  • FnomRange : nominal range (private tag (0x300B, 0x1004)).

  • FnomSOBPWidth : nominal SOBP width (private tag (0x300B, 0x100E)).

  • FsupportID : patient support ID.

  • FMagDist : virtual source-axis distances in [mm].

Return type:

pandas DataFrame

Raises:

TypeError – If the dicom is not of RN type or not of ‘RT Ion Plan Storage’ type.

See also

getRNSpots

get a summary of parameters for each spot defined in the RN plan.

getRNInfo

get some basic information from the RN plan.

fredtools.getRNSpots(fileName: PathLike | str, displayInfo: bool = False) → DataFrame

Get the parameters of each spot defined in the RN file.

The function retrieves information for each spot defined in the RN dicom file. Only the fields with TREATMENT delivery type are included. All spots of those fields are listed in the results, including the spots with zero meterset weights.

Parameters:
  • fileName (path) – Path to RN dicom file.

  • displayInfo (bool, optional) – Displays a summary of the function results. (def. False)

Returns:

DataFrame with one row per spot and the following columns (columns with no values in the plan are dropped):

  • FDeliveryNo : field delivery number (order in IonBeamSequence).

  • FNo : field (beam) number.

  • FName : field (beam) name.

  • FGantryAngle : gantry angle in [deg].

  • FCouchAngle : couch (patient support) angle in [deg].

  • FCouchPitchAngle : couch pitch angle in [deg].

  • FCouchRollAngle : couch roll angle in [deg].

  • FIsoPos : isocenter position (3-element XYZ) in [mm].

  • FMagDist : virtual source-axis distances in [mm].

  • FEnergyNo : energy layer number within the field.

  • FSpotNo : spot number within the field.

  • PBRSID : range shifter ID.

  • PBRSSetting : range shifter setting.

  • PBSnoutPos : snout position in [mm].

  • PBnomEnergy : nominal beam energy in [MeV].

  • PBMsW : spot meterset weight.

  • PBMU : spot meterset in [MU].

  • PBPosX, PBPosY : spot positions in [mm].

  • PBTuneID : scan spot tune ID.

  • PBPainting : number of paintings.

Return type:

pandas DataFrame

Raises:

TypeError – If the dicom is not of RN type or not of ‘RT Ion Plan Storage’ type.

See also

getRNFields

get a summary of parameters for each field defined in the RN plan.

getRNInfo

get some basic information from the RN plan.

fredtools.getRSInfo(fileName: PathLike | str, displayInfo: bool = False) → DataFrame

Get some information from the RS structures from the RS dicom file.

The function retrieves some basic information about structures from an RS dicom file.

Parameters:
  • fileName (path) – Path to RS dicom file.

  • displayInfo (bool, optional) – Displays a summary of the function results. (def. False)

Returns:

Pandas DataFrame with structures and properties.

Return type:

DataFrame

Raises:
  • TypeError – If the dicom is not of RS type.

  • ImportError – If the ‘StructureSetROISequence’, ‘ROIContourSequence’ or ‘RTROIObservationsSequence’ cannot be found in the dicom.

fredtools.checkDicomsUID(RNfileName: PathLike | str, RSfileName: PathLike | str, CTfileNames: PathLike | str | Iterable[PathLike | str], RDfileNames: PathLike | str | Iterable[PathLike | str] | None = None, dicomsInfo: DataFrame | None = None, displayInfo: bool = False) → DottedDict

Check the UID matching of all the dicoms describing a single patient plan.

The function performs all the UID consistency checks for the dicoms describing a single patient treatment plan, i.e. a single plan (RN) dicom, a single structure set (RS) dicom, the CT image dicoms and, optionally, the dose (RD) dicoms. The following checks are performed:

  • UIDRNtoRS: the RN dicom references the RS dicom (checkUID_RNtoRS).

  • UIDRStoCT: the RS dicom references exactly the given CT dicoms (checkUID_RStoCT).

  • UIDRNtoRD: every RD dicom references the RN dicom (checkUID_RNtoRD). None if no RD dicoms were provided.

  • UIDFoR: all the dicoms share the same FrameOfReferenceUID (getFrameOfReferenceUID).

  • RDbeamNumbers: the beam number referenced in every RD dicom is defined in the RN dicom. None if no RD dicoms were provided.

The checks are implemented in the fredtools.Miscellaneous.dicom_uid module. Any error raised by the checks (e.g. a wrong dicom type or a missing tag) is propagated to the calling code.

Parameters:
  • RNfileName (path) – Path to a dicom file with an RT plan (RN file).

  • RSfileName (path) – Path to a dicom file with a structure set (RS file).

  • CTfileNames (path or iterable of paths) – A path or an iterable of paths to CT image dicom files.

  • RDfileNames (path or iterable of paths, optional) – A path or an iterable of paths to dose (RD) dicom files. If None or empty, the RD checks are skipped. (def. None)

  • dicomsInfo (DataFrame, optional) – The dicoms information produced by getDicomsInfo, holding at least all the given dicom files. If it is given, then all the checks are answered from the index and no dicom file is read, which is substantially faster when the checks are performed for many plans of the same patient. The information must have been built with the FrameOfReferenceUID read for the ‘UIDFoR’ check to be performed, otherwise it is set to None. (def. None)

  • displayInfo (bool, optional) – Displays a summary of the function results. (def. False)

Returns:

Dictionary with the check results, with keys ‘UIDRNtoRS’, ‘UIDRStoCT’, ‘UIDRNtoRD’, ‘UIDFoR’ and ‘RDbeamNumbers’, each holding True/False, or None for the checks skipped due to no RD dicoms provided.

Return type:

dict

Raises:
  • TypeError – If any of the given files is not a dicom of the expected type.

  • ValueError – If no single RN or RS file name is provided, if no CT file names are provided, or if a required tag cannot be found in a dicom file.

  • FileNotFoundError – If any of the given files does not exist.

See also

sortDicoms

sort dicom files in a folder by type.

getRNInfo

get some information from the RN plan from RN dicom file.

getRSInfo

get some information from the RS structures from RS dicom file.

fredtools.getExternalName(fileName: PathLike | str, displayInfo: bool = False) → str

Get the name of the EXTERNAL structure from RS dicom file.

The function retrieves the name of the structure of type EXTERNAL from an RS dicom file. If more than one structure of type EXTERNAL exists in the RS dicom file, then the first one is returned.

Parameters:
  • fileName (path) – Path to RS dicom file.

  • displayInfo (bool, optional) – Displays a summary of the function results. (def. False)

Returns:

String with the name of the structure of type EXTERNAL.

Return type:

string

Raises:
  • TypeError – If the dicom is not of RS type.

  • ValueError – If no structure of type EXTERNAL is defined in the RS dicom file.

See also

getRSInfo

getting information about all structures on the RS dicom file.

fredtools.getCT(fileNames: Iterable[PathLike | str], displayInfo: bool = False) → Image

Get a CT image from dicom series.

The function reads a series of dicom files containing a CT scan and creates an instance of a SimpleITK object. The dicom files should come from the same Series and have the same frame of reference.

Parameters:
  • fileNames (array_like) – An iterable (list, tuple, etc.) of paths to dicoms.

  • displayInfo (bool, optional) – Displays a summary of the function results. (def. False)

Returns:

An object of a SimpleITK image of sitk.sitkInt16 (int16) type.

Return type:

SimpleITK Image

Raises:
  • TypeError – If fileNames is not an iterable of paths, if any dicom is missing the ‘FrameOfReferenceUID’ or ‘SeriesInstanceUID’ tag, or if those tags are not the same for all dicoms.

  • ValueError – If any file is not a CT dicom, or if the slice location spacing is not constant.

See also

sortDicoms

get names of dicoms in a folder sorted by the dicom type.

fredtools.getPET(fileNames: Iterable[PathLike | str], SUV: bool = True, displayInfo: bool = False) → Image

Get a PET image from dicom series.

The function reads a series of dicom files containing a PET scan and creates an instance of a SimpleITK object. The dicom files should come from the same Series and have the same frame of reference.

Parameters:
  • fileNames (array_like) – An iterable (list, tuple, etc.) of paths to dicoms.

  • SUV (bool, optional) – Determine if the image should be recalculated with the Standardized Uptake Value (SUV). (def. True)

  • displayInfo (bool, optional) – Displays a summary of the function results. (def. False)

Returns:

An object of a SimpleITK image of sitk.sitkFloat32 (32-bit float) type.

Return type:

SimpleITK Image

Raises:
  • TypeError – If fileNames is not an iterable of paths, if any dicom is missing the ‘FrameOfReferenceUID’ or ‘SeriesInstanceUID’ tag, or if those tags are not the same for all dicoms.

  • ValueError – If any file is not a PET dicom, or if the slice location spacing is not constant.

See also

sortDicoms

get names of dicoms in a folder sorted by the dicom type.

fredtools.getRD(fileNames: Iterable[PathLike | str] | PathLike | str, displayInfo: bool = False) → Image | tuple[Image]

Get an image from dicom.

The function reads a single dicom file or an iterable of dicom files and creates an instance or tuple of instances of a SimpleITK object.

Parameters:
  • fileNames (string or array_like) – A path or an iterable (list, tuple, etc.) of paths to dicoms.

  • displayInfo (bool, optional) – Displays a summary of the function results. (def. False)

Returns:

An Object or tuple of objects of a SimpleITK image.

Return type:

SimpleITK Image or tuple

See also

sortDicoms

get names of dicoms in a folder sorted by the dicom type.

fredtools.getRDFileNameForFieldNumber(fileNames: Iterable[PathLike | str], fieldNumber: int, displayInfo: bool = False) → PathLike | str | None

Get the file name of the RD dose dicom for the given field number.

The function searches for the RD dose dicom file for a given field number (beam number) and returns its file name.

Parameters:
  • fileNames (array_like) – An iterable (list, tuple, etc.) of paths to RD dicoms.

  • fieldNumber (scalar, int) – Field number to find the dicom for.

  • displayInfo (bool, optional) – Displays a summary of the function results. (def. False)

Returns:

Path to the RD dose file for the given beam number, or None if not found.

Return type:

path or None

fredtools.anonymizeDicoms(fileNames: Iterable[PathLike | str] | PathLike | str, *, destination: PathLike | str | Iterable[PathLike | str] | None = None, patientName: str | None = None, patientID: str | None = None, tags: dict | None = None, removePrivateTags: bool = False, displayInfo: bool = False) → List[str]

Anonymize dicom files.

The function anonymizes dicom files given as an iterable of file paths, by blanking the tags holding the patient and the personnel identity: ‘PatientName’, ‘PatientBirthDate’, ‘PatientBirthTime’, ‘PatientSex’, ‘ReferringPhysicianName’, ‘ReviewerName’, ‘ReviewDate’, ‘ReviewTime’, ‘OperatorsName’ and ‘PhysiciansOfRecord’. The original files are overwritten, unless a destination is given, in which case each dicom is read once and written anonymized to the destination, leaving the original files untouched.

The tags of the anonymized dicoms can be additionally set with patientName, patientID and tags, which is useful for instance to replace the patient identity with an anonymous identifier instead of blanking it. Note that the SOPInstanceUID and all the other UIDs are not modified, therefore the dicoms can still be matched to each other after the anonymization.

Parameters:
  • fileNames (string or array_like) – A path or an iterable (list, tuple, etc.) of paths to DICOM files.

  • destination (path or array_like, optional) – A path to a folder where the anonymized dicoms should be written, keeping their original file names, or an iterable of the destination paths, one for each of fileNames. If None, then the original files are overwritten in place. (def. None)

  • patientName (string, optional) – The value to be set as the ‘PatientName’ tag, instead of blanking it. (def. None)

  • patientID (string, optional) – The value to be set as the ‘PatientID’ tag. The tag is not modified by the anonymization itself. (def. None)

  • tags (dict, optional) – A dictionary of additional {tagKeyword: value} to be set in the anonymized dicoms, applied after the anonymization, for instance to remove the institution identity. (def. None)

  • removePrivateTags (bool, optional) – Determine if the private tags should be removed. (def. False)

  • displayInfo (bool, optional) – Displays a summary of the function results. (def. False)

Returns:

The paths of the written dicom files.

Return type:

list of strings

Raises:

ValueError – If the destination is an iterable of a different length than fileNames.

Examples

Anonymize the dicoms in place, as in the previous versions of the function.

>>> ft.anonymizeDicoms(fileNames)

Copy and anonymize the dicoms in a single read/write pass, setting an anonymous patient identity.

>>> ft.anonymizeDicoms(fileNames, destination=destinationFileNames, patientName='12345', patientID='12345')

FRED influence matrices

Functions for reading influence matrices produced by the FRED Monte Carlo. The influence matrix is usually a 3D image describing the influence (dose, LET or other quantity) for each pencil beam, therefore it can be treated as a 4D image with geometrical X, Y, Z and pencil beam dimensions.

Note

The binary influence matrix file format has changed across FRED versions. The functions support influence matrix files in format versions 2.x and 3.x and raise an error for unsupported versions.

fredtools.getInmFREDInfo(fileName: PathLike | str, displayInfo: bool = False) → DataFrame

Read basic information from FRED influence matrix.

The function reads an influence matrix file produced by the FRED Monte Carlo and gets the basic information about the pencil beams and fields saved.

Parameters:
  • fileName (path) – Path to FRED influence matrix file to read.

  • displayInfo (bool, optional) – Displays a summary of the function results. (def. False)

Returns:

Pandas DataFrame with pencil beams and field numbers.

Return type:

DataFrame

Raises:
  • TypeError – If the file is not a proper FRED influence matrix file.

  • FileNotFoundError – If the file cannot be found.

  • NotImplementedError – If the version of the influence matrix file is not supported.

See also

getInmFREDBaseImg

get base image defined in FRED influence matrix.

getInmFREDSparse

get sparse matrices of point values from an influence matrix produced by FRED Monte Carlo.

fredtools.getInmFREDBaseImg(fileName: PathLike | str, dtype: DTypeLike = <class 'float'>, displayInfo: bool = False) → Image

Get base image defined in FRED influence matrix.

The function reads the header of an influence matrix file produced by the FRED Monte Carlo and builds the basic image of a given type, defined as an instance of a SimpleITK image object, with the frame of reference defined in the influence matrix.

Parameters:
  • fileName (path) – Path to FRED influence matrix file to read.

  • dtype (data-type, optional) – The desired data-type for the output image, e.g., numpy.uint32 or float32. (def. numpy.float64)

  • displayInfo (bool, optional) – Displays a summary of the function results. (def. False)

Returns:

An object of a SimpleITK image.

Return type:

SimpleITK Image

Raises:
  • TypeError – If the file is not a proper FRED influence matrix file.

  • FileNotFoundError – If the file cannot be found.

  • NotImplementedError – If the version of the influence matrix file is not supported.

See also

getInmFREDInfo

get information from an influence matrix produced by FRED Monte Carlo.

getInmFREDSparse

get sparse matrices of point values from an influence matrix produced by FRED Monte Carlo.

fredtools.getInmFREDSparse(fileName: PathLike | str, points: Iterable[Iterable[int | float | number]], interpreter: str = 'numpy', displayInfo: bool = False) → Sequence[csr_matrix]

Get sparse matrices of point values from an influence matrix produced by FRED Monte Carlo.

The function reads an influence matrix file produced by the FRED Monte Carlo and returns a list of sparse matrices of point values for each component at the requested points.

Parameters:
  • fileName (path) – Path to FRED influence matrix file to read.

  • points (array_like) – An N-element iterable of 3 elements iterables with physical points.

  • interpreter ({'numpy', 'cupy'}, optional) – The interpreter to be used for calculations. Use ‘numpy’ for CPU or ‘cupy’ for GPU implementation. (def. ‘numpy’)

  • displayInfo (bool, optional) – Displays a summary of the function results. (def. False)

Returns:

List of sparse matrices of point values for each component.

Return type:

list[scipy.sparse.csr_matrix] or list[cupyx.scipy.sparse.csr_matrix]

Raises:
  • TypeError – If the file is not a proper FRED influence matrix file, or if points is not an N-element iterable of 3-element iterables.

  • FileNotFoundError – If the file cannot be found.

  • ValueError – If the interpreter is not supported.

  • NotImplementedError – If the version of the influence matrix file is not supported.

See also

getInmFREDInfo

get information from an influence matrix produced by FRED Monte Carlo.

getInmFREDBaseImg

get base image defined in FRED influence matrix.

OmniPro files (*.opg, *.opd)

fredtools.readOPG(fileName: PathLike | str, depth: float = 0, displayInfo: bool = False) → Image

Read OPG files from OmniPro software.

The function reads a single OPG file exported from OmniPro software (IBA) and creates an instance of a SimpleITK object.

Parameters:
  • fileName (string) – A path to OPG file.

  • depth (scalar, optional) – A scalar defining the depth of a 3D image. Usually, it is the depth of the measurement. (def. 0)

  • displayInfo (bool, optional) – Displays a summary of the function results. (def. False)

Returns:

An object of a SimpleITK image. The pixel values are converted to dose in [Gy] and the coordinates to [mm], regardless of the data and length units defined in the file.

Return type:

SimpleITK Image

Raises:

ImportError – If any of the required header lines (‘Data Factor’, ‘Data Unit’, ‘Length Unit’), the asciibody section, or the X/Y coordinate lines cannot be found in the file, or if the data or length unit cannot be recognised.

fredtools.readOPD(fileName: PathLike | str, depth: int | float | number = 0, returnImg=['Integral', 'Sum'], raiseWarning: bool = True, displayInfo: bool = False) → List[Image]

Read OPD files from OmniPro software.

The function reads a single OPD file saved by OmniPro software (IBA) and creates a list of SimpleITK image objects. All the “Snap”, “Integral” and “Sum” records found in the file are parsed and the images whose type matches returnImg are returned, in the order they appear in the file.

Parameters:
  • fileName (path) – A path to OPD file.

  • depth (scalar, optional) – A scalar defining the depth of a 3D image in [mm] (it becomes the z origin). Usually, it is the depth of the measurement. (def. 0)

  • returnImg (string or iterable of strings, optional) – A string or an iterable of strings determining the type of image to be returned. Usually it might take “Snap”, “Integral” and/or “Sum”. (def. [“Integral”, “Sum”])

  • raiseWarning (bool, optional) – Raise warnings. (def. True)

  • displayInfo (bool, optional) – Displays a summary of the function results. (def. False)

Returns:

A list of SimpleITK image objects matching returnImg.

Return type:

list of SimpleITK Images

Notes

The implementation in python has been done based on the MATLAB implementation prepared by Dawid Krzempek.

Format conversion

fredtools.SITK2ITK(imgSITK: Image) → <itkTemplate itk::Image>

Convert image from SimpleITK.Image object to ITK.Image object.

The function converts a SimpleITK image object to an ITK image object, preserving the origin, spacing and direction. The pixel buffer is copied (via GetArrayFromImage/GetImageFromArray). Vector images (multi-component pixels) are handled.

Parameters:

imgSITK (SimpleITK Image) – Object of a SimpleITK image.

Returns:

Object of an ITK image.

Return type:

ITK Image

Raises:

TypeError – If imgSITK is not an instance of a SimpleITK image object.

See also

ITK2SITK

convert an ITK image to a SimpleITK image.

fredtools.ITK2SITK(imgITK: <itkTemplate itk::Image>) → Image

Convert image from ITK.Image object to SimpleITK.Image object.

The function converts an ITK image object to a SimpleITK image object, preserving the origin, spacing and direction. The pixel buffer is copied (via GetArrayFromImage/GetImageFromArray). Vector images (multi-component pixels) are handled.

Parameters:

imgITK (ITK Image) – Object of an ITK image.

Returns:

Object of a SimpleITK image.

Return type:

SimpleITK Image

Raises:

TypeError – If imgITK is not an instance of an ITK image object.

See also

SITK2ITK

convert a SimpleITK image to an ITK image.

fredtools.img2vec(img: Image) → NDArray

Convert an image to a vector of voxel values.

The function flattens a SimpleITK image to a 1D numpy array. The voxel array is first transposed from the numpy zyx order to the xyz order (swapaxes(0, -1)) and then flattened in the Fortran order (flatten(order=’F’)), so the element order matches the voxel indexing convention of numpy.ravel_multi_index(…, order=’F’) used by getInmFREDSparse.

Parameters:

img (SimpleITK Image) – Object of a SimpleITK image.

Returns:

1D numpy array of the voxel values.

Return type:

numpy ndarray

Raises:

TypeError – If img is not an instance of a SimpleITK image object.

See also

getInmFREDSparse

get sparse matrices of point values from an influence matrix produced by FRED Monte Carlo.