Commit ·
4021c62
1
Parent(s): 39b990a
update scripts
Browse filesFiles changed (4)
- scripts/DL_save_nifti.py+26-70
- scripts/LICENSEAdded+15
- scripts/apply_window.pyAdded+54
- scripts/batch_download_zips.py+29-7
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354552 unmodified lines5859606162636465666768697071727374757677787980818283848586878889909192939495969798991001 unmodified line1021031041051061071081098 unmodified lines118119120121122#!/usr/bin/env python"""Ke YanImaging Biomarkers and Computer-Aided Diagnosis LaboratoryNational Institutes of Health Clinical CenterMay 2018THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS ORIMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIESOF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUTNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANYTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OFTHIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.""""""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 numpy as npimport nibabel as nibimport osimport cv2import csvdir_in = 'Images_png'dir_out = 'Images_nifti'out_fmt = '%s_%03d-%03d.nii.gz' # format of the nifti file name to outputinfo_fn = 'DL_info.csv' # file name of the information filedef slices2nifti(ims, fn_out, spacing):"""save 2D slices to 3D nifti file considering the spacing"""if len(ims) < 300: # cv2.merge does not support too many channelsV = cv2.merge(ims)else:V = np.empty((ims[0].shape[0], ims[0].shape[1], len(ims)))for i in range(len(ims)):V[:, :, i] = ims[i]# the transformation matrix suitable for 3D slicer and ITK-SNAPT = np.array([[0, -spacing[1], 0, 0], [-spacing[0], 0, 0, 0], [0, 0, -spacing[2], 0], [0, 0, 0, 1]])img = nib.Nifti1Image(V, T)path_out = os.path.join(dir_out, fn_out)nib.save(img, path_out)print fn_out, 'saved'def load_slices(dir, slice_idxs):2 unmodified linesassert np.all(slice_idxs[1:] - slice_idxs[:-1] == 1)ims = []for slice_idx in slice_idxs:fn = '%03d.png' % slice_idxpath = os.path.join(dir_in, dir, fn)im = cv2.imread(path, -1) # -1 is needed for 16-bit imageassert im is not None, 'error reading %s' % pathprint 'read', path# the 16-bit png file has a intensity bias of 32768ims.append((im.astype(np.int32) - 32768).astype(np.int16))return imsdef read_DL_info():"""read spacings and image indices in DeepLesion"""spacings = []idxs = []with open(info_fn, 'rb') as csvfile:reader = csv.reader(csvfile)rownum = 0for row in reader:if rownum == 0:header = rowrownum += 1else:idxs.append([int(d) for d in row[1:4]])spacings.append([float(d) for d in row[12].split(',')])idxs = np.array(idxs)spacings = np.array(spacings)return idxs, spacingsif __name__ == '__main__':idxs, spacings = read_DL_info()if not os.path.exists(dir_out):os.mkdir(dir_out)img_dirs = os.listdir(dir_in)img_dirs.sort()for dir1 in img_dirs:# find the image info according to the folder's nameidxs1 = np.array([int(d) for d in dir1.split('_')])1 unmodified linespacings1 = spacings[i1[0]]fns = os.listdir(os.path.join(dir_in, dir1))slices = [int(d[:-4]) for d in fns if d.endswith('.png')]slices.sort()# Each folder contains png slices from one series (volume)# There may be several sub-volumes in each volume depending on the key slices8 unmodified linesfor group in groups:# group contains slices indices of a sub-volumeims = load_slices(dir1, group)fn_out = out_fmt % (dir1, group[0], group[-1])slices2nifti(ims, fn_out, spacings1)123456789101112131415161718192021222324252627282 unmodified lines3132333435363738394041424344454647484950515253545556571 unmodified line596061626364658 unmodified lines7475767778"""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 osimport cv2import numpy as npimport pandas as pdimport SimpleITK as sitkdir_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):2 unmodified linesassert 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 imageassert im is not None, f'error reading {path}'print(f'read {path}')# the 16-bit png file has an intensity bias of 32768ims.append((im.astype(np.int32) - 32768).astype(np.int16))return imsif __name__ == '__main__':# Read spacings and image indices in DeepLesiondl_info = pd.read_csv(info_fn)idxs = dl_info[['Patient_index', 'Study_index', 'Series_ID']].valuesspacings = dl_info['Spacing_mm_px_'].apply(lambda x: np.array(x.split(", "), dtype=float)).valuesspacings = 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 nameidxs1 = np.array([int(d) for d in dir1.split('_')])1 unmodified linespacings1 = 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 slices8 unmodified linesfor group in groups:# group contains slices indices of a sub-volumeims = load_slices(dir1, group)fn_out = f'{dir1}_{group[0]:03d}-{group[-1]:03d}.nii.gz'slices2nifti(ims, fn_out, spacings1)
123456789101112131415Copyright (c) Feb 2024, Benjamin HouCopyright (c) May 2018, Ke YanImaging Biomarkers and Computer-Aided Diagnosis LaboratoryNational Institutes of Health Clinical Center
THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS ORIMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIESOF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUTNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANYTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OFTHIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354"""Apply CT windowing parameter from DL_info.csv to Images_png"""
import osimport cv2
import numpy as npimport pandas as pd
from glob import globfrom tqdm import tqdm
dir_in = '../Images_png'dir_out = '../Images_png_wn'info_fn = '../DL_info.csv'
if not os.path.exists(dir_out): os.mkdir(dir_out)
dl_info = pd.read_csv(info_fn)
def clip_and_normalize(np_image: np.ndarray, clip_min: int = -150, clip_max: int = 250 ) -> np.ndarray: np_image = np.clip(np_image, clip_min, clip_max) np_image = (np_image - clip_min) / (clip_max - clip_min) return np_image
for idx, row in tqdm(dl_info.iterrows(), total=len(dl_info)):
folder = row['File_name'].rsplit('_', 1)[0] images = sorted(glob(f'{dir_in}/{folder}/*.png'))
if not os.path.exists(f'{dir_out}/{folder}'): os.mkdir(f'{dir_out}/{folder}') DICOM_windows = [float(value.strip()) for value in row['DICOM_windows'].split(',')]
for im in images: try: image = cv2.imread(im, cv2.IMREAD_UNCHANGED) image = image.astype('int32') - 32768 image = clip_and_normalize(image, *DICOM_windows) image = (image*255).astype('uint8') cv2.imwrite(f'{dir_out}/{folder}/{os.path.basename(im)}', image) except AttributeError: # Broken Images # 001821_07_01/372.png # 002161_04_02/116.png print(f'Conversion failed: {im}') continue1234560 unmodified lines66676869707172737475# Download the 56 zip files in Images_png in batchesimport urllib# URLs for the zip fileslinks = [60 unmodified lines'https://nihcc.box.com/shared/static/kqg4peb9j53ljhrxe3l3zrj4ac6xogif.zip']md5_link = 'https://nihcc.box.com/shared/static/q0f8gy79q2spw96hs6o4jjjfsrg17t55.txt'urllib.urlretrieve(md5_link, "MD5_checksums.txt") # download the MD5 checksum filefor idx, link in enumerate(links):fn = 'Images_png_%02d.zip' % (idx+1)print 'downloading', fn, '...'urllib.urlretrieve(link, fn) # download the zip fileprint "Download complete. Please check the MD5 checksums"1234567891011121314151617181960 unmodified lines808182838485868788899091929394959697"""Download the 56 zip files in Images_png in batches"""import osimport urllib.requestfrom tqdm import tqdmclass DownloadProgressBar(tqdm):def update_to(self, b=1, bsize=1, tsize=None):if tsize is not None:self.total = tsizeself.update(b * bsize - self.n)# URLs for the zip fileslinks = [60 unmodified lines'https://nihcc.box.com/shared/static/kqg4peb9j53ljhrxe3l3zrj4ac6xogif.zip']# Download directorydir_out = '../Images_zip'if not os.path.exists(dir_out):os.mkdir(dir_out)# Download MD5 checksum filemd5_link = 'https://nihcc.box.com/shared/static/q0f8gy79q2spw96hs6o4jjjfsrg17t55.txt'urllib.request.urlretrieve(md5_link, f'{dir_out}/MD5_checksums.txt')# Download DeepLesion zip filesfor idx, link in enumerate(links):fn = f'{dir_out}/Images_png_{idx+1:02d}.zip'with DownloadProgressBar(unit='B', unit_scale=True, miniters=1, desc=f'Downloading: {fn}') as t:urllib.request.urlretrieve(link, fn, t.update_to)print('Download complete. Please check the MD5 checksums')
scripts/DL_save_nifti.py+26-70
scripts/LICENSEAdded+15
scripts/apply_window.pyAdded+54
scripts/batch_download_zips.py+29-7