Last active
January 11, 2023 14:00
-
-
Save liuhh02/4d4cef6f6e1d4d8897a8348755811e26 to your computer and use it in GitHub Desktop.
Convert multiple tiff images in a directory to a single 3D nifti file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
tif_to_nii | |
Convert multiple tiff images in a directory to a single 3D nifti file. | |
Naming Convention: root001_01 - root001_100, root002_01 - root002_100, ... | |
Usage instructions: change the source path (src_path) [represents the path to your tiff images], | |
destination path (dest_path) [represents the path you want to store your 3D nifti file in] and bases | |
[this represents the name of the files] accordingly | |
Author: liuhh02 https://machinelearningtutorials.weebly.com/ | |
""" | |
import re | |
import glob | |
import os | |
import nibabel as nib | |
from PIL import Image | |
# Function to sort | |
def sort( l ): | |
""" Sort the given list in the way that humans expect.""" | |
convert = lambda text: int(text) if text.isdigit() else text | |
alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ] | |
l.sort( key=alphanum_key ) | |
return l | |
# define paths | |
src_path = './valid/' | |
dest_path = './volumes/' | |
# define list of base names | |
bases = ['root001', 'root002', 'root003'] | |
# loop through each base | |
for base in bases: | |
# get names for the file | |
names = glob.glob(src_path + base + '*.tif') | |
# check all the files have been found | |
print(names) | |
names = sort(names) | |
# check the sorting has been done correctly | |
print(names) | |
# check the correct number of slices have been found | |
print(len(names)) | |
i = 0 | |
# create an empty 3d numpy array with the desired shape: number of slices, dimensions of each slice | |
image_stacks = np.zeros(shape=(len(names), 256, 256), dtype=np.float32) | |
# loop through all the files in the list and open them | |
for filename in names: | |
img = Image.open(filename) | |
# add the slice to the 3D volume | |
image_stacks[i] = np.array(img) | |
i+=1 | |
# check shape is correct | |
print(image_stacks.shape) | |
# create nifti file | |
nifti = nib.Nifti1Image(image_stacks, affine=np.eye(4)) | |
# define filename | |
out_fn = os.path.join(dest_path, base + '.nii.gz') | |
nifti.to_filename(out_fn) | |
print("Saved", out_fn) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment