DeepLesion / scripts /DL_save_nifti.py
farrell236's picture
update scripts
4021c62
raw
history blame
2.82 kB
"""
A simple demo to load 2D 16-bit slices from DeepLesion and save to 3D nifti volumes.
The nifti volumes can be viewed in software such as 3D slicer and ITK-SNAP.
"""
import os
import cv2
import numpy as np
import pandas as pd
import SimpleITK as sitk
dir_in = '../Images_png'
dir_out = '../Images_nifti'
info_fn = '../DL_info.csv'
def slices2nifti(ims, fn_out, spacing):
"""save 2D slices to 3D nifti file considering the spacing"""
image_itk = sitk.GetImageFromArray(np.stack(ims, axis=0))
image_itk.SetSpacing(spacing)
image_itk.SetDirection((1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, -1.0))
sitk.WriteImage(image_itk, os.path.join(dir_out, fn_out))
print(fn_out, 'saved')
def load_slices(dir, slice_idxs):
"""load slices from 16-bit png files"""
slice_idxs = np.array(slice_idxs)
assert np.all(slice_idxs[1:] - slice_idxs[:-1] == 1)
ims = []
for slice_idx in slice_idxs:
path = os.path.join(dir_in, dir, f'{slice_idx:03d}.png')
im = cv2.imread(path, cv2.IMREAD_UNCHANGED) # Read as 16-bit image
assert im is not None, f'error reading {path}'
print(f'read {path}')
# the 16-bit png file has an intensity bias of 32768
ims.append((im.astype(np.int32) - 32768).astype(np.int16))
return ims
if __name__ == '__main__':
# Read spacings and image indices in DeepLesion
dl_info = pd.read_csv(info_fn)
idxs = dl_info[['Patient_index', 'Study_index', 'Series_ID']].values
spacings = dl_info['Spacing_mm_px_'].apply(lambda x: np.array(x.split(", "), dtype=float)).values
spacings = np.stack(spacings)
if not os.path.exists(dir_out):
os.mkdir(dir_out)
img_dirs = sorted(os.listdir(dir_in))
for dir1 in img_dirs:
# find the image info according to the folder's name
idxs1 = np.array([int(d) for d in dir1.split('_')])
i1 = np.where(np.all(idxs == idxs1, axis=1))[0]
spacings1 = spacings[i1[0]]
fns = os.listdir(os.path.join(dir_in, dir1))
slices = sorted([int(d[:-4]) for d in fns if d.endswith('.png')])
# Each folder contains png slices from one series (volume)
# There may be several sub-volumes in each volume depending on the key slices
# We group the slices into sub-volumes according to continuity of the slice indices
groups = []
for slice_idx in slices:
if len(groups) != 0 and slice_idx == groups[-1][-1]+1:
groups[-1].append(slice_idx)
else:
groups.append([slice_idx])
for group in groups:
# group contains slices indices of a sub-volume
ims = load_slices(dir1, group)
fn_out = f'{dir1}_{group[0]:03d}-{group[-1]:03d}.nii.gz'
slices2nifti(ims, fn_out, spacings1)