|
""" |
|
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 |
|
|
|
from tqdm import tqdm |
|
|
|
|
|
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)) |
|
|
|
|
|
|
|
def load_slices(dir, slice_idxs): |
|
"""load slices from 16-bit png files""" |
|
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) |
|
assert im is not None, f'Error reading: {path}' |
|
|
|
|
|
|
|
ims.append((im.astype(np.int32) - 32768).astype(np.int16)) |
|
return ims |
|
|
|
|
|
if __name__ == '__main__': |
|
|
|
|
|
dl_info = pd.read_csv(info_fn) |
|
spacings = dl_info['Spacing_mm_px_'].str.split(',', expand=True).astype(float).values |
|
ranges = dl_info['Slice_range'].str.split(',', expand=True).astype(int).values |
|
img_dirs = dl_info['File_name'].str.rsplit('_', n=1).str[0].values |
|
|
|
if not os.path.exists(dir_out): |
|
os.mkdir(dir_out) |
|
|
|
for idx, (img_dir, range, spacing) in tqdm(enumerate(zip(img_dirs, ranges, spacings)), total=len(img_dirs)): |
|
|
|
|
|
ims = load_slices(img_dir, np.arange(*range)) |
|
fn_out = f'{img_dir}_{range[0]:03d}-{range[-1]:03d}.nii.gz' |
|
slices2nifti(ims, fn_out, spacing) |
|
|