Utils Module
Image Manipulation API
The utils.image_manipulation module focuses on the preprocessing, orientation handling, and quality assessment of medical imaging data, particularly for Arterial Spin Labeling (ASL) MRI and similar volumetric neuroimaging datasets. It provides a set of utility functions designed to ensure that image volumes are properly aligned, normalized, and suitable for subsequent analysis or registration.
The code integrates well-established Python libraries for medical imaging, such as SimpleITK, ANTsPy, and NumPy, alongside project-specific utilities from asltk. Its main objectives are:
- Volume Management – Extracting and organizing 3D volumes from multi-dimensional ASL datasets.
- Orientation Analysis and Correction – Checking whether two images are properly aligned in orientation, automatically detecting mismatches, and applying corrective transformations (flips, transpositions, resampling).
- Image Quality Assessment – Computing key statistical measures such as mean intensity and signal-to-noise ratio (SNR) to assist in selecting representative or reference volumes for analysis.
- Reporting and Logging – Generating structured orientation analysis reports, with detailed information on image properties and recommended corrections.
In practice, these tools are expected to be used as an early step in the ASL processing pipeline. By ensuring that image volumes are consistent in orientation and quality, the subsequent stages of image registration, quantification, and biomarker extraction can be performed more reliably.
collect_data_volumes(data)
Collect the data volumes from a higher dimension array.
This method is used to collect the data volumes from a higher dimension array. The method assumes that the data is a 4D array, where the first dimension is the number of volumes. The method will collect the volumes and return a list of 3D arrays.
The method is used to separate the 3D volumes from the higher dimension array. This is useful when the user wants to apply a filter to each volume separately.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
ndarray
|
The data to be separated. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
list |
List[ImageIO]
|
A list of ImageIO, each one representing a volume. |
tuple |
Tuple[int, ...]
|
The original shape of the data. |
Source code in asltk/utils/image_manipulation.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | |
Image Statistics API
The utils.image_statistics module provides core utility functions for the quantitative analysis of medical images, focusing on extracting essential statistical and structural properties from volumetric data. The implemented functions are designed to support preprocessing, quality assessment, and orientation verification of medical imaging.
The main goals of this code is to provide quantitative analysis such as SNR, mean image intensity, correlations, and many others image properties.
By combining these functions, the module supports early steps in medical image analysis pipelines, where image quality and structural consistency must be verified before applying more advanced techniques like registration, segmentation, or quantitative biomarker extraction.
analyze_image_properties(image)
Analyze basic properties of a medical image for orientation assessment.
Parameters
image : np.ndarray The image to analyze.
Returns
dict Dictionary containing image properties: - 'shape': tuple, image dimensions - 'center_of_mass': tuple, center of mass coordinates - 'intensity_stats': dict, intensity statistics - 'symmetry_axes': dict, symmetry analysis for each axis
Source code in asltk/utils/image_statistics.py
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 | |
calculate_mean_intensity(image, roi=None)
Calculate the mean intensity of a medical image.
Parameters
image : np.ndarray The image to analyze.
np.ndarray, optional
Region of interest (ROI) mask. If provided, only the ROI will be considered.
Returns
float The mean intensity value of the image or ROI.
Source code in asltk/utils/image_statistics.py
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | |
calculate_snr(image, roi=None)
Calculate the Signal-to-Noise Ratio (SNR) of a medical image.
It is assumed the absolute value for SNR, i.e., SNR = |mean_signal| / |std_noise|.
Parameters
image : np.ndarray The image to analyze.
Returns
float The SNR value of the image.
Source code in asltk/utils/image_statistics.py
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | |
IO
The utils.io module provides utility functions for loading, saving, and managing medical imaging data, with a focus on Arterial Spin Labeling (ASL) MRI and BIDS-compliant datasets. It builds on libraries such as SimpleITK, NumPy, and dill, allowing users to handle both raw image files and serialized data objects in a reproducible way.
The main features include:
- Loading Images: Supports a wide range of formats (e.g., .nii, .nii.gz, .nrrd, .mha, .tif) and can automatically detect and load files from a BIDS directory structure.
- Saving Images: Exports images in multiple formats, either to a direct path or within a valid BIDS folder hierarchy.
- Managing ASL Data: Provides serialization (save_asl_data) and deserialization (load_asl_data) of ASL datasets using dill for robust object storage.
- BIDS Integration: Ensures compatibility with the BIDS specification, helping organize imaging data systematically across subjects and sessions.
These tools are intended to serve as a foundation for preprocessing and organizing ASL datasets, ensuring that images and related data are stored, retrieved, and shared in a standardized and efficient way before further analysis.
ImageIO
ImageIO is the base class in asltk for loading, manipulating,
and saving ASL images.
The basic functionality includes
- Loading images from a file path or a numpy array.
- Converting images to different representations (SimpleITK, ANTsPy, numpy).
- Saving images to a file path in various formats.
Source code in asltk/utils/io.py
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 | |
__init__(image_path=None, image_array=None, **kwargs)
The constructor initializes the ImageIO object with an image path or a numpy array.
It is needed to provide either an image path or a numpy array to load the image. If both are provided, an error will be raised because it is ambiguous which one to use.
Note
- If
image_pathis provided, the image will be loaded from the file. - If
image_arrayis provided, the image will be loaded as a numpy array. - If both are provided, an error will be raised.
- If neither is provided, an error will be raised.
Important
The image path should be a valid file path to an image file or a directory containing BIDS-compliant images. It is also recommended to provide the image path for complex image processing, as it allows to preserve the image metadata and properties, as seen for the SimpleITK and ANTsPy representations.
Only the SimpleITK and Numpy representations are availble to manipulate higher dimensional images (4D, 5D, etc.). The ANTsPy representation is limited up to 3D images, mainly due to the specificity to image normalization applications.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image_path
|
str
|
The file path to the image. Defaults to None. |
None
|
image_array
|
ndarray
|
The image as a numpy array. Defaults to None. |
None
|
average_m0
|
bool
|
If True, averages the M0 image if it is provided. Defaults to False. |
required |
verbose
|
bool
|
If True, prints additional information during loading. Defaults to False |
required |
Source code in asltk/utils/io.py
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | |
__str__()
Returns a string representation of the ImageIO object.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
A summary of the image parameters, BIDS information, and loading parameters. |
Source code in asltk/utils/io.py
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 | |
get_as_ants()
Get the image as an ANTsPy image object.
Important
The methods returns a copy of the ANTsPy image object. This is to ensure that the original image is not modified unintentionally.
Returns:
| Type | Description |
|---|---|
|
ants.image: The image as an ANTsPy image object. |
Source code in asltk/utils/io.py
169 170 171 172 173 174 175 176 177 178 179 180 181 | |
get_as_numpy()
Get the image as a NumPy array.
Important
The methods returns a copy of the NumPy array. This is to ensure that the original image is not modified unintentionally. Also, the image representation as numpy array does not preserve the image metadata, such as spacing, origin, and direction. For a complete image representation, use the SimpleITK or ANTsPy representations.
Returns:
| Type | Description |
|---|---|
|
numpy.ndarray: The image as a NumPy array. |
Source code in asltk/utils/io.py
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 | |
get_as_sitk()
Get the image as a SimpleITK image object.
Important
The methods returns a copy of the SimpleITK image object. This is to ensure that the original image is not modified unintentionally.
Returns:
| Type | Description |
|---|---|
|
SimpleITK.Image: The image as a SimpleITK image object. |
Source code in asltk/utils/io.py
155 156 157 158 159 160 161 162 163 164 165 166 167 | |
get_image_path()
Get the image path for loading.
Returns:
| Name | Type | Description |
|---|---|---|
str |
Path to the image file. |
Source code in asltk/utils/io.py
147 148 149 150 151 152 153 | |
load_image()
Load an image file from a BIDS directory or file using the SimpleITK and ANTsPy representation (if applicable).
a
SimpleITK image, a numpy array and (if applicable) a ANTsPy image.
Note
- The general image loading is done using SimpleITK, which supports a wide range of image formats.
- The image is loaded as a SimpleITK image, and then converted to a numpy array.
- If the image is 3D or lower, it is also converted to an ANTsPy image.
Supported image formats include: .nii, .nii.gz, .nrrd, .mha, .tif, and other formats supported by SimpleITK.
Note
- The default values for
modalityandsuffixare None. If not provided, the function will search for the first matching ASL image in the directory. - If
full_pathis a file, it is loaded directly. If it is a directory, the function searches for a BIDS-compliant image using the provided parameters. - If both a file and a BIDS directory are provided, the file takes precedence.
Tip
To validate your BIDS structure, use the bids-validator tool: https://bids-standard.github.io/bids-validator/
For more details about ASL BIDS structure, see: https://bids-specification.readthedocs.io/en/latest
Note
The image file is assumed to be an ASL subtract image (control-label). If not, use helper functions in asltk.utils to create one.
The information passed to the ImageIO constructor is used to load the image.
Examples:
Load a single image file directly:
>>> data = ImageIO("./tests/files/pcasl_mte.nii.gz").get_as_numpy()
>>> type(data)
<class 'numpy.ndarray'>
>>> data.shape # Example: 5D ASL data
(8, 7, 5, 35, 35)
Load M0 reference image:
>>> m0_data = ImageIO("./tests/files/m0.nii.gz").get_as_numpy()
>>> m0_data.shape # Example: 3D reference image
(5, 35, 35)
Load from BIDS directory (automatic detection):
>>> data = ImageIO("./tests/files/bids-example/asl001").get_as_numpy()
>>> type(data)
<class 'numpy.ndarray'>
Load specific BIDS data with detailed parameters:
>>> data = ImageIO("./tests/files/bids-example/asl001", subject='Sub103', suffix='asl').get_as_numpy()
>>> type(data)
<class 'numpy.ndarray'>
Load NRRD format
>>> nrrd_data = ImageIO("./tests/files/t1-mri.nrrd").get_as_numpy()
>>> type(nrrd_data)
<class 'numpy.ndarray'>
Returns:
| Name | Type | Description |
|---|---|---|
ImageIO |
The loaded image as a ImageIO object. |
Source code in asltk/utils/io.py
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 | |
save_image(full_path=None, *, bids_root=None, subject=None, session=None, **kwargs)
Save the current image to a file path using SimpleITK.
All available image formats provided in the SimpleITK API can be used here. Supported formats include: .nii, .nii.gz, .nrrd, .mha, .tif, and others.
Note
If the file extension is not recognized by SimpleITK, an error will be raised. The image array should be 2D, 3D, or 4D. For 4D arrays, only the first volume may be saved unless handled explicitly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
full_path
|
str
|
Full absolute path with image file name provided. |
None
|
bids_root
|
str
|
Optional BIDS root directory to save in BIDS structure. |
None
|
subject
|
str
|
Subject ID for BIDS saving. |
None
|
session
|
str
|
Optional session ID for BIDS saving. |
None
|
Examples:
Save an image using a direct file path:
>>> import tempfile
>>> from asltk.utils.io import ImageIO
>>> import numpy as np
>>> img = np.random.rand(10, 10, 10)
>>> io = ImageIO(image_array=img)
>>> with tempfile.NamedTemporaryFile(suffix='.nii.gz', delete=False) as f:
... io.save_image(f.name)
Save an image using BIDS structure:
>>> import tempfile
>>> from asltk.utils.io import ImageIO
>>> import numpy as np
>>> img = np.random.rand(10, 10, 10)
>>> io = ImageIO(image_array=img)
>>> with tempfile.TemporaryDirectory() as temp_dir:
... io.save_image(bids_root=temp_dir, subject='001', session='01')
Save processed ASL results:
>>> from asltk.asldata import ASLData
>>> from asltk.utils.io import ImageIO
>>> asl_data = ASLData(pcasl='./tests/files/pcasl_mte.nii.gz', m0='./tests/files/m0.nii.gz')
>>> processed_img = asl_data('pcasl').get_as_numpy()[0] # Get first volume
>>> io = ImageIO(image_array=processed_img)
>>> import tempfile
>>> with tempfile.NamedTemporaryFile(suffix='.nii.gz', delete=False) as f:
... io.save_image(f.name)
Raises:
| Type | Description |
|---|---|
ValueError
|
If neither full_path nor (bids_root + subject) are provided. |
RuntimeError
|
If the file extension is not recognized by SimpleITK. |
Source code in asltk/utils/io.py
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 | |
set_image_path(image_path)
Set the image path for loading.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image_path
|
str
|
Path to the image file. |
required |
Source code in asltk/utils/io.py
138 139 140 141 142 143 144 145 | |
update_image_data(new_array, enforce_new_dimension=False)
Update the image data with a new numpy array, preserving the original image metadata.
This is particularly useful for updating the image data after processing or when new data is available. Hence, it allows to change the image data without losing the original metadata such as spacing, origin, and direction.
Another application for this method is to create a new image using a processed numpy array and then copy the metadata from the original image that was loaded using a file path, which contains the original metadata.
Examples:
>>> import numpy as np
>>> array = np.random.rand(5, 35, 35)
>>> image1 = ImageIO(image_array=array)# Example 3D image from a numpy array (without metadata)
>>> image2 = ImageIO(image_path="./tests/files/m0.nii.gz") # Example 3D image with metadata
>>> full_image = ImageIO(image_path="./tests/files/m0.nii.gz") # Example 3D image with metadata
Both images has the same shape, so we can update the image data:
>>> image1.get_as_numpy().shape == image2.get_as_numpy().shape
True
>>> image2.update_image_data(image1.get_as_numpy())
Now the image2 has the same data as image1, but retains its original metadata.
Important
- The new array must match the shape of the original image unless
enforce_new_dimensionis set to True. - If
enforce_new_dimensionis True, the new array can have a different shape than the original image, but it will be assumed the first dimensions to get averaged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
new_array
|
ndarray
|
The new image data array. Must match the shape of the original image. |
required |
enforce_new_dimension
|
bool
|
If True, allows the new array to have a different shape than the original image. |
False
|
Source code in asltk/utils/io.py
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 | |
update_image_direction(new_direction)
Update the image direction with a new tuple, preserving the original image metadata.
Important
- The new direction must be a tuple of the same length as the original image dimension.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
new_direction
|
tuple
|
The new direction for the image. |
required |
Source code in asltk/utils/io.py
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 | |
update_image_origin(new_origin)
Update the image origin with a new tuple, preserving the original image metadata.
Important
- The new origin must be a tuple of the same length as the original image dimension.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
new_origin
|
tuple
|
The new origin for the image. |
required |
Source code in asltk/utils/io.py
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 | |
update_image_spacing(new_spacing)
Update the image spacing with a new tuple, preserving the original image metadata.
Important
- The new spacing must be a tuple of the same length as the original image dimension.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
new_spacing
|
tuple
|
The new spacing for the image. |
required |
Source code in asltk/utils/io.py
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 | |
check_image_properties(first_image, ref_image)
Check the properties of two images to ensure they are compatible.
The first image can be a SimpleITK image, a numpy array, an ANTsPy image, or an ImageIO object. The reference image must be an ImageIO object.
This function checks the size, spacing, origin, and direction of the first image against the reference image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
first_image
|
Union[Image, ndarray, ANTsImage, ImageIO]
|
The first image to check. |
required |
ref_image
|
ImageIO
|
The reference image to compare against. |
required |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the reference image is not an ImageIO object. |
ValueError
|
If the image properties (size, spacing, origin, direction) do not match. |
ValueError
|
If the image properties (size, spacing, origin, direction) do not match. |
Source code in asltk/utils/io.py
611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 | |
check_path(path)
Check if the image path is valid.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
The image path to check. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the image path is not set. |
FileNotFoundError
|
If the image file does not exist. |
Source code in asltk/utils/io.py
715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 | |
clone_image(source, include_path=False)
Clone an image getting a deep copy.
All the image properties are copied, including the image path if include_path is True.
Tip
This a useful method to create a copy of an image for processing without modifying the original image.
Also, after making a clone, you can modify the image properties without affecting the original image.
The image array representation can be modified, but the original image metadata will remain unchanged,
however the update_image_data method can be used to update the image data while preserving the original metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
ImageIO
|
The source image to clone. |
required |
include_path
|
bool
|
Whether to include the image path in the clone. Defaults to False. |
False
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If the source image is not an ImageIO object. |
Returns:
| Name | Type | Description |
|---|---|---|
ImageIO |
The cloned image. |
Source code in asltk/utils/io.py
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 | |
load_asl_data(fullpath)
Load ASL data from a specified file path to an ASLData object previously saved on disk.
This function uses the dill library to load and deserialize data from a
file. Therefore, the file must have been saved using the save_asl_data function.
Note
The file must have been saved with dill. Files saved with dill may not be compatible with standard pickle, especially for custom classes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fullpath
|
str
|
The full path to the file containing the serialized ASL data. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
ASLData |
The deserialized ASL data object from the file. |
Examples:
>>> from asltk.asldata import ASLData
>>> asldata = ASLData(pcasl='./tests/files/pcasl_mte.nii.gz', m0='./tests/files/m0.nii.gz',ld_values=[1.8, 1.8, 1.8], pld_values=[1.8, 1.8, 1.8], te_values=[1.8, 1.8, 1.8])
>>> import tempfile
>>> with tempfile.NamedTemporaryFile(delete=False, suffix='.pkl') as temp_file:
... temp_file_path = temp_file.name
>>> save_asl_data(asldata, temp_file_path)
>>> loaded_asldata = load_asl_data(temp_file_path)
>>> loaded_asldata.get_ld()
[1.8, 1.8, 1.8]
>>> loaded_asldata('pcasl').get_as_numpy().shape
(8, 7, 5, 35, 35)
Source code in asltk/utils/io.py
808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 | |
save_asl_data(asldata, fullpath=None, *, bids_root=None, subject=None, session=None)
Save ASL data to a pickle file using dill serialization.
This method saves the ASL data to a pickle file using the dill library. All
the ASL data will be saved in a single file. After the file is saved, it
can be loaded using the load_asl_data method.
Note
This method only accepts the ASLData object as input. If you want to
save an image, use the save_image method.
The file is serialized with dill, which supports more Python objects than standard pickle. However, files saved with dill may not be compatible with standard pickle, especially for custom classes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
asldata
|
ASLData The ASL data to be saved. This can be any Python object that is serializable by dill. |
required | |
fullpath
|
str The full path where the pickle file will be saved. The filename must end with '.pkl'. |
required |
Examples:
>>> from asltk.asldata import ASLData
>>> asldata = ASLData(pcasl='./tests/files/pcasl_mte.nii.gz', m0='./tests/files/m0.nii.gz',ld_values=[1.8, 1.8, 1.8], pld_values=[1.8, 1.8, 1.8], te_values=[1.8, 1.8, 1.8])
>>> import tempfile
>>> with tempfile.NamedTemporaryFile(delete=False, suffix='.pkl') as temp_file:
... temp_file_path = temp_file.name
>>> save_asl_data(asldata, temp_file_path)
Raises:
| Type | Description |
|---|---|
ValueError
|
If the provided filename does not end with '.pkl'. |
Source code in asltk/utils/io.py
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 | |