Utils
batch_patients
- MEDimage.utils.batch_patients.batch_patients(n_patient: int, n_batch: int) ndarray [source]
Replaces volume intensities outside the ROI with NaN.
- Parameters:
n_patient (int) – Number of patient.
n_batch (int) – Number of batch, usually less or equal to the cores number on your machine.
- Returns:
List of indexes with size n_batch and max value n_patient.
- Return type:
ndarray
create_radiomics_table
- MEDimage.utils.create_radiomics_table.create_radiomics_table(radiomics_files_paths: List, image_space: str, log_file: str | Path) Dict [source]
Creates a dictionary with a csv and other information
- Parameters:
radiomics_files_paths (List) – List of paths to the radiomics JSON files.
image_space (str) – String of the image space that contains the extracted features
log_file (Union[str, Path]) – Path to logging file.
- Returns:
Dictionary containing the extracted radiomics and other info (patientID, feature names…)
- Return type:
Dict
data_frame_export
find_process_names
get_file_paths
- MEDimage.utils.get_file_paths.get_file_paths(path_to_parent_folder: str | Path, wildcard: str | None = None) List[Path] [source]
Finds all files in the given path that matches the pattern/wildcard.
Note
The search is done recursively in all subdirectories.
- Parameters:
path_to_parent_folder (Union[str, Path]) – Full path to where the files are located.
wildcard (str, optional) – String specifying which type of files
folder. (to locate in the parent) –
Ex : ‘.dcm’, to look for dicom files.
- Returns:
List of full paths to files with the specific wildcard located in the given path to parent folder.
- Return type:
List
get_institutions_from_ids
- MEDimage.utils.get_institutions_from_ids.get_institutions_from_ids(patient_ids)[source]
Extracts the institution strings from a cell of patient IDs.
- Parameters:
patient_ids (Any) – Patient ID (string, list of strings or pandas Series). Ex: ‘Cervix-CEM-010’.
- Returns:
Categorical vector, specifying the institution of each patient_id entry in “patient_ids”. Ex: ‘CEM’.
- Return type:
str
get_patient_id_from_scan_name
- MEDimage.utils.get_patient_id_from_scan_name.get_patient_id_from_scan_name(rad_name: str) str [source]
Finds the patient id from the given string
- Parameters:
rad_name (str) – Name of a scan or a radiomics structure
- Returns:
patient id
- Return type:
str
Example
>>> get_patient_id_from_scan_name('STS-McGill-001__T1(tumourAndEdema).MRscan') STS-McGill-001
get_patient_names
- MEDimage.utils.get_patient_names.get_patient_names(roi_names: ndarray) List[str] [source]
Generates all file names for scans using CSV data.
- Parameters:
roi_names (ndarray) – Array with CSV data organized as follows [[patient_id], [imaging_scan_name], [imagning_modality]]
- Returns:
List of scans files name.
- Return type:
list[str]
get_radiomic_names
- MEDimage.utils.get_radiomic_names.get_radiomic_names(roi_names: array, roi_type: str) Dict [source]
Generates radiomics names using
roi_names
androi_types
.- Parameters:
roi_names (np.array) – array of the ROI names.
roi_type (str) – string of the ROI.
- Returns:
dict with the radiomic names
- Return type:
dict
get_scan_name_from_rad_name
- MEDimage.utils.get_scan_name_from_rad_name.get_scan_name_from_rad_name(rad_name: str) str [source]
Finds the imaging scan name from thr radiomics structure name
- Parameters:
rad_name (str) – radiomics structure name.
- Returns:
String of the imaging scan name
- Return type:
str
Example
>>> get_scan_name_from_rad_name('STS-McGill-001__T1(tumourAndEdema).MRscan') 'T1'
image_reader_SITK
- MEDimage.utils.image_reader_SITK.image_reader_SITK(path: Path, option: str | None = None) Dict | None [source]
Return the image in a numpy array or a dictionary with the header of the image.
- Parameters:
path (path) – path of the file
option (str) – name of the option, either ‘image’ or ‘header’
- Returns:
dictionary with the header of the image
- Return type:
Union[Dict, None]
image_volume_obj
- class MEDimage.utils.image_volume_obj.image_volume_obj(data=None, spatial_ref=None)[source]
Bases:
object
Used to organize Imaging data and their corresponding imref3d object.
- Parameters:
data (ndarray, optional) – 3D array of imaging data.
spatialRef (imref3d, optional) – The corresponding imref3d object (same functionality of MATLAB imref3d class).
- data
3D array of imaging data.
- Type:
ndarray
imref
- class MEDimage.utils.imref.imref3d(imageSize=None, pixelExtentInWorldX=1.0, pixelExtentInWorldY=1.0, pixelExtentInWorldZ=1.0, xWorldLimits=None, yWorldLimits=None, zWorldLimits=None)[source]
Bases:
object
This class mirrors the functionality of the matlab imref3d class
An imref3d object stores the relationship between the intrinsic coordinates anchored to the columns, rows, and planes of a 3-D image and the spatial location of the same column, row, and plane locations in a world coordinate system.
The image is sampled regularly in the planar world-x, world-y, and world-z coordinates of the coordinate system such that intrinsic-x, -y and -z values align with world-x, -y and -z values, respectively. The resolution in each dimension can be different.
- Parameters:
ImageSize (ndarray, optional) – Number of elements in each spatial dimension, specified as a 3-element positive row vector.
PixelExtentInWorldX (float, optional) – Size of a single pixel in the x-dimension measured in the world coordinate system.
PixelExtentInWorldY (float, optional) – Size of a single pixel in the y-dimension measured in the world coordinate system.
PixelExtentInWorldZ (float, optional) – Size of a single pixel in the z-dimension measured in the world coordinate system.
xWorldLimits (ndarray, optional) – Limits of image in world x, specified as a 2-element row vector, [xMin xMax].
yWorldLimits (ndarray, optional) – Limits of image in world y, specified as a 2-element row vector, [yMin yMax].
zWorldLimits (ndarray, optional) – Limits of image in world z, specified as a 2-element row vector, [zMin zMax].
- ImageSize
Number of elements in each spatial dimension, specified as a 3-element positive row vector.
- Type:
ndarray
- PixelExtentInWorldX
Size of a single pixel in the x-dimension measured in the world coordinate system.
- Type:
float
- PixelExtentInWorldY
Size of a single pixel in the y-dimension measured in the world coordinate system.
- Type:
float
- PixelExtentInWorldZ
Size of a single pixel in the z-dimension measured in the world coordinate system.
- Type:
float
- XIntrinsicLimits
Limits of image in intrinsic units in the x-dimension, specified as a 2-element row vector [xMin xMax].
- Type:
ndarray
- YIntrinsicLimits
Limits of image in intrinsic units in the y-dimension, specified as a 2-element row vector [yMin yMax].
- Type:
ndarray
- ZIntrinsicLimits
Limits of image in intrinsic units in the z-dimension, specified as a 2-element row vector [zMin zMax].
- Type:
ndarray
- ImageExtentInWorldX
Span of image in the x-dimension in the world coordinate system.
- Type:
float
- ImageExtentInWorldY
Span of image in the y-dimension in the world coordinate system.
- Type:
float
- ImageExtentInWorldZ
Span of image in the z-dimension in the world coordinate system.
- Type:
float
- xWorldLimits
Limits of image in world x, specified as a 2-element row vector, [xMin xMax].
- Type:
ndarray
- yWorldLimits
Limits of image in world y, specified as a 2-element row vector, [yMin yMax].
- Type:
ndarray
- zWorldLimits
Limits of image in world z, specified as a 2-element row vector, [zMin zMax].
- Type:
ndarray
- ImageExtentInWorld(axis=None) float | None [source]
Returns the ImageExtentInWorld attribute value for the given
axis
.- Parameters:
axis (str, optional) – Specify the dimension, must be ‘X’, ‘Y’ or ‘Z’.
- Returns:
Span of image in the axis-dimension in the world coordinate system.
- Return type:
ndarray
- IntrinsicLimits(axis=None) ndarray | None [source]
Returns the IntrinsicLimits attribute value for the given
axis
.- Parameters:
axis (str, optional) – Specify the dimension, must be ‘X’, ‘Y’ or ‘Z’.
- Returns:
Limits of image in intrinsic units in the axis-dimension, specified as a 2-element row vector [xMin xMax].
- Return type:
ndarray
- PixelExtentInWorld(axis=None) float | None [source]
Returns the PixelExtentInWorld attribute value for the given
axis
.- Parameters:
axis (str, optional) – Specify the dimension, must be ‘X’, ‘Y’ or ‘Z’.
- Returns:
Size of a single pixel in the axis-dimension measured in the world coordinate system.
- Return type:
float
- WorldLimits(axis=None, newValue=None) ndarray | None [source]
Sets the WorldLimits to the new value for the given
axis
. If the newValue is None, the method returns the attribute value.- Parameters:
axis (str, optional) – Specify the dimension, must be ‘X’, ‘Y’ or ‘Z’.
newValue (iterable, optional) – New value for the WorldLimits attribute.
- Returns:
Limits of image in world along the axis-dimension.
- Return type:
ndarray
- _parse_to_ndarray(x: iterable, n=None) ndarray [source]
Internal function to cast input to a numpy array.
- Parameters:
x (iterable) – Object that supports __iter__.
n (int, optional) – expected length.
- Returns:
iterable input as a numpy array.
- Return type:
ndarray
- contains_point(xWorld: ndarray, yWorld: ndarray, zWorld: ndarray) ndarray [source]
Determines which points defined by
xWorld
,yWorld
andzWorld
.- Parameters:
xWorld (ndarray) – Coordinates along the x-dimension in the world coordinate system.
yWorld (ndarray) – Coordinates along the y-dimension in the world coordinate system.
zWorld (ndarray) – Coordinates along the z-dimension in the world coordinate system.
- Returns:
boolean array for coordinate sets that are within the bounds of the image.
- Return type:
ndarray
- intrinsicToWorld(xIntrinsic: ndarray, yIntrinsic: ndarray, zIntrinsic: ndarray) Tuple[ndarray, ndarray, ndarray] [source]
Convert from intrinsic to world coordinates.
- Parameters:
xIntrinsic (ndarray) – Coordinates along the x-dimension in the intrinsic coordinate system.
yIntrinsic (ndarray) – Coordinates along the y-dimension in the intrinsic coordinate system.
zIntrinsic (ndarray) – Coordinates along the z-dimension in the intrinsic coordinate system.
- Returns:
[xWorld, yWorld, zWorld] in world coordinate system.
- Return type:
Tuple[np.ndarray, np.ndarray, np.ndarray]
- worldToIntrinsic(xWorld: ndarray, yWorld: ndarray, zWorld: ndarray) ndarray [source]
Converts from world coordinates to intrinsic coordinates.
- Parameters:
xWorld (ndarray) – Coordinates along the x-dimension in the world coordinate system.
yWorld (ndarray) – Coordinates along the y-dimension in the world coordinate system.
zWorld (ndarray) – Coordinates along the z-dimension in the world coordinate system.
- Returns:
[xIntrinsic,yIntrinsic,zIntrinsic] in intrinsic coordinate system.
- Return type:
ndarray
- MEDimage.utils.imref.intrinsicToWorld(R, xIntrinsic: float, yIntrinsic: float, zIntrinsic: float) Tuple[float, float, float] [source]
Convert from intrinsic to world coordinates.
- Parameters:
R (imref3d) – imref3d object (same functionality of MATLAB imref3d class)
xIntrinsic (float) – Coordinates along the x-dimension in the intrinsic coordinate system
yIntrinsic (float) – Coordinates along the y-dimension in the intrinsic coordinate system
zIntrinsic (float) – Coordinates along the z-dimension in the intrinsic coordinate system
- Returns:
world coordinates
- Return type:
float
- MEDimage.utils.imref.sizes_match(R, A)[source]
Compares whether the two imref3d objects have the same size.
- MEDimage.utils.imref.worldToIntrinsic(R, xWorld: float, yWorld: float, zWorld: float) Tuple[float, float, float] [source]
Convert from world coordinates to intrinsic.
- Parameters:
R (imref3d) – imref3d object (same functionality of MATLAB imref3d class)
xWorld (float) – Coordinates along the x-dimension in the intrinsic coordinate system
yWorld (float) – Coordinates along the y-dimension in the intrinsic coordinate system
zWorld (float) – Coordinates along the z-dimension in the intrinsic coordinate system
- Returns:
intrinsic coordinates
- Return type:
_type_
initialize_features_names
- MEDimage.utils.initialize_features_names.initialize_features_names(image_space_struct: Dict) Tuple[List, List] [source]
Finds all the features names from image_space_struct
- Parameters:
image_space_struct (Dict) – Dictionary of the extracted features (Texture & Non-texture)
- Returns:
Two lists of the texture and non-texture features names found in the image_space_struct.
- Return type:
Tuple[List, List]
inpolygon
- MEDimage.utils.inpolygon.inpolygon(x_q: ndarray, y_q: ndarray, x_v: ndarray, y_v: ndarray) ndarray [source]
Implements similar functionality MATLAB inpolygon. Finds points located inside or on edge of polygonal region.
Note
Unlike matlab inpolygon, this function does not determine the status of single points \((x_q, y_q)\). Instead, it determines the status for an entire grid by ray-casting.
- Parameters:
x_q (ndarray) – x-coordinates of query points, in intrinsic reference system.
y_q (ndarray) – y-coordinates of query points, in intrinsic reference system.
x_q – x-coordinates of polygon vertices, in intrinsic reference system.
y_q – y-coordinates of polygon vertices, in intrinsic reference system.
- Returns:
boolean array indicating if the query points are on the edge of the polygon area.
- Return type:
ndarray
interp3
- MEDimage.utils.interp3.interp3(v, x_q, y_q, z_q, method) ndarray [source]
Interpolation for 3-D gridded data in meshgrid format, implements similar functionality MATLAB interp3.
- Parameters:
X (ndarray) – Query points, should be intrinsic coordinates.
Y (ndarray) – Query points, should be intrinsic coordinates.
Z (ndarray) – Query points, should be intrinsic coordinates.
method (str) – {nearest, linear, spline, cubic}, Interpolation
method
.
- Returns:
Array of interpolated values.
- Return type:
ndarray
- Raises:
ValueError – If
method
is not ‘nearest’, ‘linear’, ‘spline’ or ‘cubic’.
json_utils
- MEDimage.utils.json_utils._is_jsonable(data: any, cls: object) bool [source]
Checks if the given
data
is JSON serializable.- Parameters:
data (Any) –
Data
that will be checked.cls (object, optional) – Costum JSONDecoder subclass. If not specified JSONDecoder is used.
- Returns:
True if the given
data
is serializable, False if not.- Return type:
bool
- MEDimage.utils.json_utils.load_json(file_path: Path) Dict [source]
Wrapper to json.load function.
- Parameters:
file_path (Path) – Path of the json file to load.
- Returns:
The loaded json file.
- Return type:
Dict
- MEDimage.utils.json_utils.posix_to_string(dictionnary: Dict) Dict [source]
Converts all Pathlib.Path to str [Pathlib is not serializable].
- Parameters:
dictionnary (Dict) – dict with Pathlib.Path values to convert.
- Returns:
dictionnary
with all Pathlib.Path converted to str.- Return type:
Dict
- MEDimage.utils.json_utils.save_json(file_path: Path, data: any, cls=None) None [source]
Wrapper to json.dump function.
- Parameters:
file_path (Path) – Path to write the json file to.
data (Any) – Data to write to the given path. Must be serializable by JSON.
cls (object, optional) – Costum JSONDecoder subclass. If not specified JSONDecoder is used.
- Returns:
saves the
data
in JSON file to thefile_path
.- Return type:
None
- Raises:
TypeError – If
data
is not JSON serializable.
mode
- MEDimage.utils.mode.mode(x: ndarray, return_counts=False) Tuple[ndarray, ndarray] | ndarray [source]
Implementation of mode that also returns counts, unlike the standard statistics.mode.
- Parameters:
x (ndarray) – n-dimensional array of which to find mode.
return_counts (bool) – If True, also return the number of times each unique item appears in
x
.
- Returns:
2-element tuple containing
ndarray: Array of the modal (most common) value in the given array.
ndarray: Array of the counts if
return_counts
is True.
parse_contour_string
- MEDimage.utils.parse_contour_string.parse_contour_string(contour_string) Tuple[float, List[str]] | Tuple[int, List[str]] | Tuple[List[int], List[str]] [source]
Finds the delimeters (\('+'\) and \('-'\)) and the contour indexe(s) from the given string.
- Parameters:
contour_string (str, float or int) – Index or string of indexes with
example (delimeters. For) – \('3'\) or \('1-3+2'\).
- Returns:
If
contour_string
is a an int or float we returncontour_string
. List[str]: List of the delimeters. List[int]: List of the contour indexes.- Return type:
float, int
Example
>>> ``contour_string`` = '1-3+2' >>> :function: parse_contour_string(contour_string) [1, 2, 3], ['+', '-'] >>> ``contour_string`` = 1 >>> :function: parse_contour_string(contour_string) 1, []
save_MEDscan
strfind
- MEDimage.utils.strfind.strfind(pattern: str, string: str) List[int] [source]
Finds indices of
pattern
instring
. Based on regex.Note
Be careful with + and - symbols. Use \(\+\) and \(\-\) instead.
- Parameters:
pattern (str) – Substring to be searched in the
string
.string (str) – String used to find matches.
- Returns:
List of indexes of every occurence of
pattern
in the passedstring
.- Return type:
List[int]
- Raises:
ValueError – If the
pattern
does not use backslash with special regex symbols
textureTools
- MEDimage.utils.textureTools.coord2index(x: ndarray, y: ndarray, z: ndarray, dims: List | ndarray) ndarray | List [source]
Translate requested coordinates to row indices in image intensity tables.
Note
Code was adapted from the in-house radiomics software created at OncoRay, Dresden, Germany.
- Parameters:
x (ndarray) – set of discrete x-coordinates.
y (ndarray) – set of discrete y-coordinates.
z (ndarray) – set of discrete z-coordinates.
dims (ndarray or List) – dimensions of the image.
- Returns:
Array or List of indexes corresponding the requested coordinates
- Return type:
ndarray or List
- MEDimage.utils.textureTools.get_neighbour_direction(d=1.8, distance='euclidian', centre=False, complete=False, dim3=True) ndarray [source]
Defines transitions to neighbour voxels.
Note
This code was adapted from the in-house radiomics software created at OncoRay, Dresden, Germany.
- Parameters:
d (float, optional) – Max
distance
between voxels.distance (str, optional) – Distance norm used to compute distances. must be “manhattan”, “l1”, “l_1”, “euclidian”, “l2”, “l_2”, “chebyshev”, “linf” or “l_inf”.
centre (bool, optional) – Flags whether the [0,0,0] direction should be included
complete (bool, optional) – Flags whether all directions should be computed (True) or just the primary ones (False). For example, including [0,0,1] and [0,0,-1] directions may lead to redundant texture matrices.
dim3 (bool, optional) – flags whether full 3D (True) or only in-slice (2D; False) directions should be considered.
- Returns:
set of k neighbour direction vectors.
- Return type:
ndarray
- MEDimage.utils.textureTools.get_value(x: ndarray, index: int, replace_invalid=True) ndarray [source]
Retrieves intensity values from an image intensity table used for computing texture features.
Note
Code was adapted from the in-house radiomics software created at OncoRay, Dresden, Germany.
- Parameters:
x (ndarray) – set of intensity values.
index (int) – Index to the provided set of intensity values.
replace_invalid (bool, optional) – If True, invalid indices will be replaced by a placeholder “NaN” value.
- Returns:
Array of the intensity values found at the requested indices.
- Return type:
ndarray
- MEDimage.utils.textureTools.is_list_all_none(x: List) bool [source]
Determines if all list elements are None.
- Parameters:
x (List) – List of elements to check.
- Returns:
True if all elemets in x are None.
- Return type:
bool
- MEDimage.utils.textureTools.rep(x: ndarray, each=1, times=1) ndarray [source]
Replicates the values in
x
. Replicates the"rep"()
function found in R for tiling and repeating vectors.Note
Code was adapted from the in-house radiomics software created at OncoRay, Dresden, Germany.
- Parameters:
x (ndarray) – Array to replicate.
each (int) – Integer (non-negative) giving the number of times to repeat each element of the passed array.
times (int) – Integer (non-negative). Each element of
x
is repeated each times.
- Returns:
Array with same values but replicated.
- Return type:
ndarray
write_radiomics_csv
- MEDimage.utils.write_radiomics_csv.write_radiomics_csv(path_radiomics_table: Path | str) None [source]
Loads a radiomics structure (dict with radiomics features) to convert it to a CSV file and save it.
- Parameters:
path_radiomics_table (Union[Path, str]) – path to the radiomics dict.
- Returns:
None.