I/O Utilities#
NIfTI file loading/saving, bval/bvec handling, and filesystem helpers.
Input/Output utilities for the thesis framework.
- thesis.core.io.load_nifti(file_path, as_array=True)[source]#
- Overloads:
file_path (Union[str, Path]), as_array (Literal[True]) → np.ndarray
file_path (Union[str, Path]), as_array (Literal[False]) → SpatialImage
- Parameters:
- Return type:
ndarray | SpatialImage
Load a NIfTI image file.
- Parameters:
- Returns:
Numpy array or nibabel image object
- Raises:
FileNotFoundError – If file doesn’t exist
ImportError – If nibabel is not installed
- Return type:
ndarray | SpatialImage
Example
>>> data = load_nifti("T1.nii.gz") >>> print(data.shape) (256, 256, 256)
- thesis.core.io.save_nifti(data, file_path, affine=None, header=None)[source]#
Save data as a NIfTI image file.
- Parameters:
- Return type:
- Returns:
Path to saved file
- Raises:
ImportError – If nibabel is not installed
ValueError – If affine is missing for array data
Example
>>> data = np.random.rand(64, 64, 64) >>> affine = np.eye(4) >>> save_nifti(data, "output.nii.gz", affine=affine)
- thesis.core.io.load_bvals(file_path)[source]#
Load b-values from a text file.
- Parameters:
- Return type:
- Returns:
1D numpy array of b-values
Example
>>> bvals = load_bvals("data.bval") >>> print(bvals.shape) (32,)
- thesis.core.io.load_bvecs(file_path)[source]#
Load b-vectors from a text file.
- Parameters:
- Return type:
- Returns:
2D numpy array of shape (3, N) where N is number of directions
Example
>>> bvecs = load_bvecs("data.bvec") >>> print(bvecs.shape) (3, 32)
- thesis.core.io.check_file_exists(file_path, raise_error=True)[source]#
Check if a file exists.
- Parameters:
- Return type:
- Returns:
True if file exists, False otherwise (if raise_error=False)
- Raises:
FileNotFoundError – If file doesn’t exist and raise_error=True
- thesis.core.io.ensure_directory(dir_path, parents=True)[source]#
Ensure a directory exists, creating it if necessary.
- Parameters:
- Return type:
- Returns:
Path object
Example
>>> output_dir = ensure_directory("./results/patient_001")
- thesis.core.io.get_file_info(file_path)[source]#
Get information about a file.
- Parameters:
- Return type:
- Returns:
Dictionary with file information
Example
>>> info = get_file_info("data.nii.gz") >>> print(info["size_mb"])
- thesis.core.io.find_files(directory, pattern='*', recursive=False)[source]#
Find files matching a pattern in a directory.
- Parameters:
- Return type:
- Returns:
List of matching file paths
Example
>>> nii_files = find_files("./data", "*.nii.gz", recursive=True)
- thesis.core.io.copy_nifti_metadata(source_path, target_data, target_path)[source]#
Copy metadata from source NIfTI to save target data.
Useful when you process an image and want to keep the same affine matrix and header information.
- Parameters:
- Return type:
- Returns:
Path to saved file
Example
>>> processed = process_image(data) >>> copy_nifti_metadata("input.nii.gz", processed, "output.nii.gz")