farrell236 commited on
Commit
146f108
1 Parent(s): b1e7f32

update DL-save_nifti.py

Browse files
Files changed (1) hide show
  1. scripts/DL_save_nifti.py +12 -32
scripts/DL_save_nifti.py CHANGED
@@ -10,6 +10,8 @@ import numpy as np
10
  import pandas as pd
11
  import SimpleITK as sitk
12
 
 
 
13
 
14
  dir_in = '../Images_png'
15
  dir_out = '../Images_nifti'
@@ -22,19 +24,17 @@ def slices2nifti(ims, fn_out, spacing):
22
  image_itk.SetSpacing(spacing)
23
  image_itk.SetDirection((1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, -1.0))
24
  sitk.WriteImage(image_itk, os.path.join(dir_out, fn_out))
25
- print(fn_out, 'saved')
26
 
27
 
28
  def load_slices(dir, slice_idxs):
29
  """load slices from 16-bit png files"""
30
- slice_idxs = np.array(slice_idxs)
31
- assert np.all(slice_idxs[1:] - slice_idxs[:-1] == 1)
32
  ims = []
33
  for slice_idx in slice_idxs:
34
  path = os.path.join(dir_in, dir, f'{slice_idx:03d}.png')
35
  im = cv2.imread(path, cv2.IMREAD_UNCHANGED) # Read as 16-bit image
36
- assert im is not None, f'error reading {path}'
37
- print(f'read {path}')
38
 
39
  # the 16-bit png file has an intensity bias of 32768
40
  ims.append((im.astype(np.int32) - 32768).astype(np.int16))
@@ -45,34 +45,14 @@ if __name__ == '__main__':
45
 
46
  # Read spacings and image indices in DeepLesion
47
  dl_info = pd.read_csv(info_fn)
48
- idxs = dl_info[['Patient_index', 'Study_index', 'Series_ID']].values
49
- spacings = dl_info['Spacing_mm_px_'].apply(lambda x: np.array(x.split(", "), dtype=float)).values
50
- spacings = np.stack(spacings)
51
 
52
  if not os.path.exists(dir_out):
53
  os.mkdir(dir_out)
54
- img_dirs = sorted(os.listdir(dir_in))
55
- for dir1 in img_dirs:
56
- # find the image info according to the folder's name
57
- idxs1 = np.array([int(d) for d in dir1.split('_')])
58
- i1 = np.where(np.all(idxs == idxs1, axis=1))[0]
59
- spacings1 = spacings[i1[0]]
60
-
61
- fns = os.listdir(os.path.join(dir_in, dir1))
62
- slices = sorted([int(d[:-4]) for d in fns if d.endswith('.png')])
63
-
64
- # Each folder contains png slices from one series (volume)
65
- # There may be several sub-volumes in each volume depending on the key slices
66
- # We group the slices into sub-volumes according to continuity of the slice indices
67
- groups = []
68
- for slice_idx in slices:
69
- if len(groups) != 0 and slice_idx == groups[-1][-1]+1:
70
- groups[-1].append(slice_idx)
71
- else:
72
- groups.append([slice_idx])
73
 
74
- for group in groups:
75
- # group contains slices indices of a sub-volume
76
- ims = load_slices(dir1, group)
77
- fn_out = f'{dir1}_{group[0]:03d}-{group[-1]:03d}.nii.gz'
78
- slices2nifti(ims, fn_out, spacings1)
 
10
  import pandas as pd
11
  import SimpleITK as sitk
12
 
13
+ from tqdm import tqdm
14
+
15
 
16
  dir_in = '../Images_png'
17
  dir_out = '../Images_nifti'
 
24
  image_itk.SetSpacing(spacing)
25
  image_itk.SetDirection((1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, -1.0))
26
  sitk.WriteImage(image_itk, os.path.join(dir_out, fn_out))
27
+ # print(f'{fn_out} saved')
28
 
29
 
30
  def load_slices(dir, slice_idxs):
31
  """load slices from 16-bit png files"""
 
 
32
  ims = []
33
  for slice_idx in slice_idxs:
34
  path = os.path.join(dir_in, dir, f'{slice_idx:03d}.png')
35
  im = cv2.imread(path, cv2.IMREAD_UNCHANGED) # Read as 16-bit image
36
+ assert im is not None, f'Error reading: {path}'
37
+ # print(f'read {path}')
38
 
39
  # the 16-bit png file has an intensity bias of 32768
40
  ims.append((im.astype(np.int32) - 32768).astype(np.int16))
 
45
 
46
  # Read spacings and image indices in DeepLesion
47
  dl_info = pd.read_csv(info_fn)
48
+ spacings = dl_info['Spacing_mm_px_'].str.split(',', expand=True).astype(float).values
49
+ ranges = dl_info['Slice_range'].str.split(',', expand=True).astype(int).values
50
+ img_dirs = dl_info['File_name'].str.rsplit('_', n=1).str[0].values
51
 
52
  if not os.path.exists(dir_out):
53
  os.mkdir(dir_out)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
 
55
+ for idx, (img_dir, range, spacing) in tqdm(enumerate(zip(img_dirs, ranges, spacings)), total=len(img_dirs)):
56
+ ims = load_slices(img_dir, np.arange(*range))
57
+ fn_out = f'{img_dir}_{range[0]:03d}-{range[-1]:03d}.nii.gz'
58
+ slices2nifti(ims, fn_out, spacing)