|
| 1 | +"""Resampling utiltiies for longitudinal templates.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from typing import TYPE_CHECKING |
| 6 | + |
| 7 | +import nibabel as nib |
| 8 | +from nibabel.processing import resample_from_to |
| 9 | + |
| 10 | +if TYPE_CHECKING: |
| 11 | + from pathlib import Path |
| 12 | + |
| 13 | +from rbc.core.niwrap import generate_exec_folder |
| 14 | + |
| 15 | + |
| 16 | +def resample_template_to_bold(bold_ref: Path, template: Path) -> Path: |
| 17 | + """Resample template to BOLD grid if shapes differ. |
| 18 | +
|
| 19 | + Args: |
| 20 | + bold_ref: BOLD reference volume (used for ITK conversion). |
| 21 | + template: Brain template in target space. |
| 22 | +
|
| 23 | + Returns: |
| 24 | + Resampled template image with BOLD grid |
| 25 | +
|
| 26 | + Raises: |
| 27 | + FileNotFoundError: No motion .mat files found in the directory. |
| 28 | + ValueError: Number of motion matrices does not match STC volumes. |
| 29 | + """ |
| 30 | + bold_ref_img = nib.nifti1.load(bold_ref) |
| 31 | + template_img = nib.nifti1.load(template) |
| 32 | + |
| 33 | + # If 4D, extract first volume |
| 34 | + if len(bold_ref_img.shape) > 3: |
| 35 | + bold_ref_img = bold_ref_img[..., 0] |
| 36 | + # If same shape, no need to resample |
| 37 | + if bold_ref_img.shape == template_img.shape: |
| 38 | + return template_img |
| 39 | + |
| 40 | + template_img = resample_from_to(template_img, bold_ref_img) |
| 41 | + template_img_path = ( |
| 42 | + generate_exec_folder("template_resample_to_bold_grid") |
| 43 | + / "template_resampled.nii.gz" |
| 44 | + ) |
| 45 | + nib.save(template_img, template_img_path) |
| 46 | + return template_img_path |
0 commit comments