Skip to content

Instantly share code, notes, and snippets.

@zerebom
Last active April 14, 2020 03:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zerebom/9c7bc55f3a2d243fb6f6e27c9accefeb to your computer and use it in GitHub Desktop.
Save zerebom/9c7bc55f3a2d243fb6f6e27c9accefeb to your computer and use it in GitHub Desktop.
SimpleITK

This repository describe 'SimpleITK' which python module is inheritence by 3D voxel image processing module 'ITK'

def resampleImage(img, new_spacing, image=True):
'''Spacing幅を変えるときのコード
img:sitk.Image
new_spacing: tuple(x,y,z)
image: image or label. if label, image=False
sitk.SetSpacingだけではnumpy.shapeは変更されないので注意。
'''
def calc_new_size():
np_size = np.array(img.GetSize())
np_cur_spacing = np.array(img.GetSpacing())
np_new_spacing = np.array(new_spacing)
np_new_size = np_size * np_cur_spacing / new_spacing
return np_new_size.astype(int).tolist()
origin = img.GetOrigin()
size = img.GetSize()
cur_spacing = img.GetSpacing()
direction = img.GetDirection()
new_size = calc_new_size()
transform = sitk.Transform() # default is 'IdentityTransform'
# interpolator = sitk.sitkNearestNeighbor
interpolator = sitk.sitkBSpline if image else sitk.sitkNearestNeighbor
return sitk.Resample(img, new_size, transform, interpolator,
origin, new_spacing, direction, 0.0, img.GetPixelIDValue())
def save_niigz(save_path: Path, array: np.array, spacing:tuple):
# (z,x,y)の方向になるようにする。
DIRECTION = (1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, -1.0)
array = array.astype(np.int16)
save_image = sitk.GetImageFromArray(array)
save_image.SetSpacing(spacing)
save_image.SetDirection(DIRECTION)
if not save_path.parent.is_dir():
save_path.parent.mkdir()
print(save_path)
sitk.WriteImage(save_image, str(save_path), True)
from pathlib import Path
def get_data(path: str, spacing:tuple, image=True):
"""pathからスペーシング幅を決めて画像とarrayを返す"""
if Path(path).is_file():
img = sitk.ReadImage(str(path))
# boolを渡して、interpolatorを変更している
img = self.resampleImage(img, spacing, image=image)
img_array = sitk.GetArrayFromImage(img)
return img_array
else:
print(f'{path} is not exist.')
return False
def resampleImage(img, new_spacing, image=True):
'''Spacing幅を変えるときのコード
img:sitk.Image
new_spacing: tuple(x,y,z)
image: image or label. if label, image=False
sitk.SetSpacingだけではnumpy.shapeは変更されないので注意。
'''
def calc_new_size():
np_size = np.array(img.GetSize())
np_cur_spacing = np.array(img.GetSpacing())
np_new_spacing = np.array(new_spacing)
np_new_size = np_size * np_cur_spacing / new_spacing
return np_new_size.astype(int).tolist()
origin = img.GetOrigin()
size = img.GetSize()
cur_spacing = img.GetSpacing()
direction = img.GetDirection()
new_size = calc_new_size()
transform = sitk.Transform() # default is 'IdentityTransform'
# interpolator = sitk.sitkNearestNeighbor
interpolator = sitk.sitkBSpline if image else sitk.sitkNearestNeighbor
return sitk.Resample(img, new_size, transform, interpolator,
origin, new_spacing, direction, 0.0, img.GetPixelIDValue())
def spacing_changer(impath,sepath,save_impath,save_sepath,spacing,z_pad_size=3):
def get_data(path: str, spacing=False, image=True):
"""pathからスペーシング幅を決めて画像とarrayを返す"""
if Path(path).is_file():
img = sitk.ReadImage(str(path))
img_array = sitk.GetArrayFromImage(img)
direction = img.GetDirection()
spacing = img.GetSpacing()
print('spacing:',img.GetSpacing())
print('shape:',img.GetSize())
return img,img_array,direction,spacing
else:
print(f'{path} is not exist.')
return False
im,im_arr,im_direction,im_spacing = get_data(impath,image=True)
se,se_arr,se_direction,se_spacing = get_data(sepath,image=False)
#ガンがある領域だけ
z_indexes = np.argwhere(np.sum(np.where(se_arr==2,se_arr,0),axis=(0,1))!=0)
# z_indexes = np.argwhere(np.sum(se_arr,axis=(0,1))!=0)
z_top = np.squeeze(z_indexes)[0]
z_end = np.squeeze(z_indexes)[-1]
new_se_arr = se_arr[...,z_top-5:z_end+5].astype(np.int16)
new_im_arr = im_arr[...,z_top-5:z_end+5].astype(np.int16)
save_image = sitk.GetImageFromArray(new_im_arr)
save_segmentation = sitk.GetImageFromArray(new_se_arr)
save_image.SetSpacing(im_spacing)
save_image.SetDirection(im_direction)
save_segmentation.SetSpacing(se_spacing)
save_segmentation.SetDirection(im_direction)
save_image = resampleImage(save_image, spacing, image=True)
save_segmentation = resampleImage(save_segmentation, spacing, image=False)
save_image.SetSpacing(spacing)
save_segmentation.SetSpacing(spacing)
save_segmentation = resampleImage(save_segmentation, spacing, image=False)
print('resampled shape:', save_image.GetSize(), save_segmentation.GetSize())
sitk.WriteImage(save_image, str(save_impath), True)
sitk.WriteImage(save_segmentation, str(save_sepath), True)
impaths = sorted(glob.glob('/home/higuchi/ssd2/kits19/data/case_00*/imaging.nii.gz'))
sepaths = sorted(glob.glob('/home/higuchi/ssd2/kits19/data/case_00*/segmentation.nii.gz'))
save_impaths = [re.sub('imaging','imaging_078_078_1',path) for path in impaths]
save_sepaths = [re.sub('imaging','imaging_078_078_1',path) for path in sepaths]
spacing = (1.0, 0.781624972820282, 0.781624972820282)
for impath,sepath,save_impath,save_sepath in zip(impaths,sepaths,save_impaths,save_sepaths):
try:
spacing_changer(impath,sepath,save_impath,save_sepath,spacing,z_pad_size=5)
except:
print(impath)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment