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 double (*.mhd+*.raw) or single files (only *.mhd),

  • 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.

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

See also

SimpleITK.ReadImage

SimpleITK routine for reading files.

fredtools.writeMHD(img: Image, filePath: PathLike | str, singleFile: bool = True, 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 the MetaImage file. The function extends the functionality of SimpleITK.WriteImage() to write a single file MetaImage instead of standard two-files MHD+RAW. It is recommended to use .mhd extension when saving MetaImage. Note that metadata keys with empty values are erased from the input image object (in-place side effect) before writing.

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

  • filePath (path) – Path to file to be saved.

  • singleFile (bool, optional) – Determine if the MHD is a single file or two files MHD+RAW. (def. True)

  • overwrite (bool, optional) – Overwrite the file if it exists, otherwise, raise an error. (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 MHD files, the useful range is 0-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 file exists and overwrite is False, or if the ‘ElementDataFile’ tag cannot be found in the written MHD file when converting to a single file.

  • IOError – If the raw data file cannot be read or attached to the MHD file when converting to a single file.

See also

SimpleITK.WriteImage

SimpleITK routine for writing files.

fredtools.convertMHDtoSingleFile(fileName: PathLike | str, displayInfo: bool = False) None

Convert two-file MetaImage to a single file.

The function reads a MetaImage file (two- or single-file) and saves it as a single file MetaImage (MHD) with the same file name.

Parameters:
  • fileName (path) – Path to file to be converted.

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

See also

readMHD

reading MetaImage file.

writeMHD

writing MetaImage file.

fredtools.convertMHDtoDoubleFiles(fileName: PathLike | str, displayInfo: bool = False) None

Convert single file MetaImage to double-file.

The function reads a MetaImage file (two- or single-file) and saves it as a two-file MetaImage (mhd/raw) with the same file name.

Parameters:
  • fileName (path) – Path to file to be converted.

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

See also

readMHD

reading MetaImage file.

writeMHD

writing MetaImage file.

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

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 centre 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, 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)

  • 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, removePrivateTags: bool = False, displayInfo: bool = False) None

Anonymize dicom files.

The function anonymizes dicom files given as an iterable of file paths. The function overwrites the original files.

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

  • 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)

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[cupy.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[tuple[Any, ...], dtype[_ScalarT]]

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.