viralTracing2MTPL.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import os
  2. import argparse
  3. import numpy as np
  4. import nibabel as nib
  5. import glob
  6. def main():
  7. parser = argparse.ArgumentParser(description="Resample multiple flo images using a reference image and an affine transformation file.")
  8. parser.add_argument("-i", "--input", help="Input folder containing viraltracing images", required=True)
  9. parser.add_argument("-o", "--output", help="Output folder for flipped images", required=True)
  10. args = parser.parse_args()
  11. # Create the output folder if it doesn't exist
  12. if not os.path.exists(args.output):
  13. os.makedirs(args.output)
  14. # List all flo images in the input folder
  15. flo_images = glob.glob(os.path.join(args.input, "**", "*.nii.gz"), recursive=True)
  16. # Loop through flo images and perform resampling
  17. for flo_image in flo_images:
  18. output_filename = os.path.basename(flo_image).replace(".nii.gz", "_flipped.nii.gz")
  19. output_path = os.path.join(args.output, output_filename)
  20. mask_output_path = os.path.join(args.output, output_filename.replace("_flipped.nii.gz", "_mask.nii.gz"))
  21. # Load the image using nibabel
  22. img = nib.load(flo_image)
  23. data = img.get_fdata()
  24. # Perform the dimension manipulation to achieve the desired shape
  25. data_swapped = np.swapaxes(data, 0, 2) # Swap axes as per the desired shape (264, 160, 228) -> (228, 160, 264)
  26. data_flipped = np.flip(data_swapped, axis=2) # Flip along the third axis
  27. # Save the modified data back to a NIfTI file
  28. img_flipped = nib.Nifti1Image(data_flipped, img.affine)
  29. nib.save(img_flipped, output_path)
  30. # Create mask data
  31. mask_data = np.where(data_flipped != 0, 1, 0)
  32. mask_img = nib.Nifti1Image(mask_data.astype(np.uint8), img.affine)
  33. nib.save(mask_img, mask_output_path)
  34. if __name__ == "__main__":
  35. main()