本文整理汇总了Python中SimpleITK.GetArrayFromImage方法的典型用法代码示例。如果您正苦于以下问题:Python SimpleITK.GetArrayFromImage方法的具体用法?Python SimpleITK.GetArrayFromImage怎么用?Python SimpleITK.GetArrayFromImage使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类SimpleITK
的用法示例。
在下文中一共展示了SimpleITK.GetArrayFromImage方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: load_itk_image
# 需要导入模块: import SimpleITK [as 别名]
# 或者: from SimpleITK import GetArrayFromImage [as 别名]
def load_itk_image(filename):
with open(filename) as f:
contents = f.readlines()
line = [k for k in contents if k.startswith('TransformMatrix')][0]
transformM = np.array(line.split(' = ')[1].split(' ')).astype('float')
transformM = np.round(transformM)
if np.any( transformM!=np.array([1,0,0, 0, 1, 0, 0, 0, 1])):
isflip = True
else:
isflip = False
itkimage = sitk.ReadImage(filename)
numpyImage = sitk.GetArrayFromImage(itkimage)
numpyOrigin = np.array(list(reversed(itkimage.GetOrigin())))
numpySpacing = np.array(list(reversed(itkimage.GetSpacing())))
return numpyImage, numpyOrigin, numpySpacing,isflip
示例2: estimate
# 需要导入模块: import SimpleITK [as 别名]
# 或者: from SimpleITK import GetArrayFromImage [as 别名]
def estimate(self):
### "segmented"
color_region_growing = sitk.VectorConfidenceConnectedImageFilter()
color_region_growing.SetNumberOfIterations(4)
color_region_growing.SetMultiplier(5.3)
color_region_growing.SetInitialNeighborhoodRadius(2)
color_region_growing.SetReplaceValue(255)
color_region_growing.AddSeed(self.seed_point)
eyes_segmented = color_region_growing.Execute(self.input_image)
### "radius"
distance_filter = sitk.SignedMaurerDistanceMapImageFilter()
distance_filter.SetInsideIsPositive(True)
distance_map = distance_filter.Execute(eyes_segmented)
radius_estimate = np.amax(sitk.GetArrayFromImage(distance_map))
return eyes_segmented,radius_estimate
### "overlay"
示例3: get_image
# 需要导入模块: import SimpleITK [as 别名]
# 或者: from SimpleITK import GetArrayFromImage [as 别名]
def get_image(self):
if self.frame == len(self.time_table):
raise CrappyStop
img_t = self.time_table[self.frame]
img = sitk.GetArrayFromImage(sitk.ReadImage(self.img_dict[img_t]))
t = time()
delay = self.time_table[self.frame] - t + self.t0
if delay > 0:
if t > self.t0:
sleep(delay)
else:
return img_t,img
#else:
# print("Streamer is",-1000*delay,"ms late")
self.frame += 1
return img_t,img
示例4: load_nifty_volume_as_4d_array
# 需要导入模块: import SimpleITK [as 别名]
# 或者: from SimpleITK import GetArrayFromImage [as 别名]
def load_nifty_volume_as_4d_array(filename):
"""Read a nifty image and return a dictionay storing data array, spacing and direction
output['data_array'] 4d array with shape [C, D, H, W]
output['spacing'] a list of spacing in z, y, x axis
output['direction'] a 3x3 matrix for direction
"""
img_obj = sitk.ReadImage(filename)
data_array = sitk.GetArrayFromImage(img_obj)
origin = img_obj.GetOrigin()
spacing = img_obj.GetSpacing()
direction = img_obj.GetDirection()
shape = data_array.shape
if(len(shape) == 4):
assert(shape[3] == 1)
elif(len(shape) == 3):
data_array = np.expand_dims(data_array, axis = 0)
else:
raise ValueError("unsupported image dim: {0:}".format(len(shape)))
output = {}
output['data_array'] = data_array
output['origin'] = origin
output['spacing'] = (spacing[2], spacing[1], spacing[0])
output['direction'] = direction
return output
示例5: produceRandomlyTranslatedImage
# 需要导入模块: import SimpleITK [as 别名]
# 或者: from SimpleITK import GetArrayFromImage [as 别名]
def produceRandomlyTranslatedImage(image, label):
sitkImage = sitk.GetImageFromArray(image, isVector=False)
sitklabel = sitk.GetImageFromArray(label, isVector=False)
itemindex = np.where(label > 0)
randTrans = (0,np.random.randint(-np.min(itemindex[1])/2,(image.shape[1]-np.max(itemindex[1]))/2),np.random.randint(-np.min(itemindex[0])/2,(image.shape[0]-np.max(itemindex[0]))/2))
translation = sitk.TranslationTransform(3, randTrans)
resampler = sitk.ResampleImageFilter()
resampler.SetReferenceImage(sitkImage)
resampler.SetInterpolator(sitk.sitkLinear)
resampler.SetDefaultPixelValue(0)
resampler.SetTransform(translation)
outimgsitk = resampler.Execute(sitkImage)
outlabsitk = resampler.Execute(sitklabel)
outimg = sitk.GetArrayFromImage(outimgsitk)
outimg = outimg.astype(dtype=float)
outlbl = sitk.GetArrayFromImage(outlabsitk) > 0
outlbl = outlbl.astype(dtype=float)
return outimg, outlbl
示例6: sitk_to_nib
# 需要导入模块: import SimpleITK [as 别名]
# 或者: from SimpleITK import GetArrayFromImage [as 别名]
def sitk_to_nib(image: sitk.Image) -> Tuple[np.ndarray, np.ndarray]:
data = sitk.GetArrayFromImage(image).transpose()
spacing = np.array(image.GetSpacing())
direction = np.array(image.GetDirection())
origin = image.GetOrigin()
if len(direction) == 9:
rotation = direction.reshape(3, 3)
elif len(direction) == 4: # ignore first dimension if 2D (1, 1, H, W)
rotation_2d = direction.reshape(2, 2)
rotation = np.eye(3)
rotation[1:3, 1:3] = rotation_2d
spacing = 1, *spacing
origin = 0, *origin
rotation = np.dot(FLIP_XY, rotation)
rotation_zoom = rotation * spacing
translation = np.dot(FLIP_XY, origin)
affine = np.eye(4)
affine[:3, :3] = rotation_zoom
affine[:3, 3] = translation
return data, affine
示例7: read_images
# 需要导入模块: import SimpleITK [as 别名]
# 或者: from SimpleITK import GetArrayFromImage [as 别名]
def read_images(self, path, affix):
t1 = sitk.GetArrayFromImage(sitk.ReadImage(glob.glob(os.path.join(path, '*_t1' + affix))[0]))
t1ce = sitk.GetArrayFromImage(sitk.ReadImage(glob.glob(os.path.join(path, '*_t1ce' + affix))[0]))
t2 = sitk.GetArrayFromImage(sitk.ReadImage(glob.glob(os.path.join(path, '*_t2' + affix))[0]))
flair = sitk.GetArrayFromImage(sitk.ReadImage(glob.glob(os.path.join(path, '*_flair' + affix))[0]))
# scale to 0 to 1
t1 = (t1 - np.amin(t1)) / (np.amax(t1) - np.amin(t1))
t1ce = (t1ce - np.amin(t1ce)) / (np.amax(t1ce) - np.amin(t1ce))
t2 = (t2 - np.amin(t2)) / (np.amax(t2) - np.amin(t2))
flair = (flair - np.amin(flair)) / (np.amax(flair) - np.amin(flair))
# scale to 0 mean, 1 std
#t1 = (t1 - np.mean(t1)) / np.std(t1)
#t1ce = (t1ce - np.mean(t1ce)) / np.std(t1ce)
#t2 = (t2 - np.mean(t2)) / np.std(t2)
#flair = (flair - np.mean(flair)) / np.std(flair)
images = np.stack((t1, t1ce, t2, flair), axis=-1).astype(np.float32)
return images
示例8: pp_patient
# 需要导入模块: import SimpleITK [as 别名]
# 或者: from SimpleITK import GetArrayFromImage [as 别名]
def pp_patient(self, path):
pid = path.split('/')[-1]
img = sitk.ReadImage(os.path.join(path, '{}_ct_scan.nrrd'.format(pid)))
img_arr = sitk.GetArrayFromImage(img)
print('processing {} with GT(s) {}, spacing {} and img shape {}.'.format(
pid, " and ".join(self.cf.gts_to_produce), img.GetSpacing(), img_arr.shape))
img_arr = resample_array(img_arr, img.GetSpacing(), self.cf.target_spacing)
img_arr = np.clip(img_arr, -1200, 600)
#img_arr = (1200 + img_arr) / (600 + 1200) * 255 # a+x / (b-a) * (c-d) (c, d = new)
img_arr = img_arr.astype(np.float32)
img_arr = (img_arr - np.mean(img_arr)) / np.std(img_arr).astype('float16')
df = pd.read_csv(os.path.join(self.cf.root_dir, 'characteristics.csv'), sep=';')
df = df[df.PatientID == pid]
np.save(os.path.join(self.cf.pp_dir, '{}_img.npy'.format(pid)), img_arr)
if 'single_annotator' in self.cf.gts_to_produce or 'sa' in self.cf.gts_to_produce:
self.produce_sa_gt(path, pid, df, img.GetSpacing(), img_arr.shape)
if 'merged' in self.cf.gts_to_produce:
self.produce_merged_gt(path, pid, df, img.GetSpacing(), img_arr.shape)
示例9: __init__
# 需要导入模块: import SimpleITK [as 别名]
# 或者: from SimpleITK import GetArrayFromImage [as 别名]
def __init__ (self, uid):
CaseBase.__init__(self)
self.uid = uid
self.path = os.path.join(LUNA_DIR_LOOKUP[uid], uid + '.mhd')
if not os.path.exists(self.path):
raise Exception('data not found for uid %s at %s' % (uid, self.path))
pass
#self.thumb_path = os.path.join(DATA_DIR, 'thumb', uid)
# load path
itkimage = itk.ReadImage(self.path)
self.HU = (1.0, 0.0)
self.images = itk.GetArrayFromImage(itkimage).astype(np.float32)
#print type(self.images), self.images.dtype
self.origin = list(reversed(itkimage.GetOrigin()))
self.spacing = list(reversed(itkimage.GetSpacing()))
self.view = AXIAL
_, a, b = self.spacing
self.anno = LUNA_ANNO.get(uid, None)
assert a == b
# sanity check
pass
示例10: __init__
# 需要导入模块: import SimpleITK [as 别名]
# 或者: from SimpleITK import GetArrayFromImage [as 别名]
def __init__ (self, path, uid=None):
VolumeBase.__init__(self)
self.uid = uid
self.path = path
if not os.path.exists(self.path):
raise Exception('data not found for uid %s at %s' % (uid, self.path))
pass
#self.thumb_path = os.path.join(DATA_DIR, 'thumb', uid)
# load path
itkimage = itk.ReadImage(self.path)
self.HU = (1.0, 0.0)
self.images = itk.GetArrayFromImage(itkimage).astype(np.float32)
#print type(self.images), self.images.dtype
self.origin = list(reversed(itkimage.GetOrigin()))
self.spacing = list(reversed(itkimage.GetSpacing()))
self.view = AXIAL
_, a, b = self.spacing
#self.anno = LUNA_ANNO.get(uid, None)
assert a == b
# sanity check
pass
示例11: create_tensor_image_from_itk_image
# 需要导入模块: import SimpleITK [as 别名]
# 或者: from SimpleITK import GetArrayFromImage [as 别名]
def create_tensor_image_from_itk_image(itk_image, dtype=th.float32, device='cpu'):
# transform image in a unit direction
image_dim = itk_image.GetDimension()
if image_dim == 2:
itk_image.SetDirection(sitk.VectorDouble([1, 0, 0, 1]))
else:
itk_image.SetDirection(sitk.VectorDouble([1, 0, 0, 0, 1, 0, 0, 0, 1]))
image_spacing = itk_image.GetSpacing()
image_origin = itk_image.GetOrigin()
np_image = np.squeeze(sitk.GetArrayFromImage(itk_image))
image_size = np_image.shape
# adjust image spacing vector size if image contains empty dimension
if len(image_size) != image_dim:
image_spacing = image_spacing[0:len(image_size)]
tensor_image = th.tensor(np_image, dtype=dtype, device=device).unsqueeze(0).unsqueeze(0)
return Image(tensor_image, image_size, image_spacing, image_origin)
示例12: copy_BraTS_segmentation_and_convert_labels
# 需要导入模块: import SimpleITK [as 别名]
# 或者: from SimpleITK import GetArrayFromImage [as 别名]
def copy_BraTS_segmentation_and_convert_labels(in_file, out_file):
# use this for segmentation only!!!
# nnUNet wants the labels to be continuous. BraTS is 0, 1, 2, 4 -> we make that into 0, 1, 2, 3
img = sitk.ReadImage(in_file)
img_npy = sitk.GetArrayFromImage(img)
uniques = np.unique(img_npy)
for u in uniques:
if u not in [0, 1, 2, 4]:
raise RuntimeError('unexpected label')
seg_new = np.zeros_like(img_npy)
seg_new[img_npy == 4] = 3
seg_new[img_npy == 2] = 1
seg_new[img_npy == 1] = 2
img_corr = sitk.GetImageFromArray(seg_new)
img_corr.CopyInformation(img)
sitk.WriteImage(img_corr, out_file)
示例13: preprocess_img
# 需要导入模块: import SimpleITK [as 别名]
# 或者: from SimpleITK import GetArrayFromImage [as 别名]
def preprocess_img(inputfile, output_preprocessed, zooms):
img = nib.load(inputfile)
data = img.get_data()
affine = img.affine
zoom = img.header.get_zooms()[:3]
data, affine = reslice(data, affine, zoom, zooms, 1)
data = np.squeeze(data)
data = np.pad(data, [(0, 256 - len_) for len_ in data.shape], "constant")
data_sub = data - gaussian_filter(data, sigma=1)
img = sitk.GetImageFromArray(np.copy(data_sub))
img = sitk.AdaptiveHistogramEqualization(img)
data_clahe = sitk.GetArrayFromImage(img)[:, :, :, None]
data = np.concatenate((data_clahe, data[:, :, :, None]), 3)
data = (data - np.mean(data, (0, 1, 2))) / np.std(data, (0, 1, 2))
assert data.ndim == 4, data.ndim
assert np.allclose(np.mean(data, (0, 1, 2)), 0.), np.mean(data, (0, 1, 2))
assert np.allclose(np.std(data, (0, 1, 2)), 1.), np.std(data, (0, 1, 2))
data = np.float32(data)
img = nib.Nifti1Image(data, affine)
nib.save(img, output_preprocessed)
示例14: load_itk_image
# 需要导入模块: import SimpleITK [as 别名]
# 或者: from SimpleITK import GetArrayFromImage [as 别名]
def load_itk_image(filename):
with open(filename) as f:
contents = f.readlines()
line = [k for k in contents if k.startswith('TransformMatrix')][0]
transformM = np.array(line.split(' = ')[1].split(' ')).astype('float')
transformM = np.round(transformM)
if np.any(transformM != np.array([1, 0, 0, 0, 1, 0, 0, 0, 1])):
isflip = True
else:
isflip = False
itkimage = sitk.ReadImage(filename)
numpyImage = sitk.GetArrayFromImage(itkimage)
numpyOrigin = np.array(list(reversed(itkimage.GetOrigin())))
numpySpacing = np.array(list(reversed(itkimage.GetSpacing())))
return numpyImage, numpyOrigin, numpySpacing, isflip
示例15: load_itk_image
# 需要导入模块: import SimpleITK [as 别名]
# 或者: from SimpleITK import GetArrayFromImage [as 别名]
def load_itk_image(filename):
with open(filename) as f:
contents = f.readlines()
line = [k for k in contents if k.startswith('TransformMatrix')][0]
transformM = np.array(line.split(' = ')[1].split(' ')).astype('float')
transformM = np.round(transformM)
if np.any( transformM!=np.array([1,0,0, 0, 1, 0, 0, 0, 1])):
isflip = True
else:
isflip = False
itkimage = sitk.ReadImage(filename)
numpyImage = sitk.GetArrayFromImage(itkimage)
numpyOrigin = np.array(list(reversed(itkimage.GetOrigin())))
numpySpacing = np.array(list(reversed(itkimage.GetSpacing())))
return numpyImage, numpyOrigin, numpySpacing, isflip