本文整理汇总了Python中SimpleITK.Cast方法的典型用法代码示例。如果您正苦于以下问题:Python SimpleITK.Cast方法的具体用法?Python SimpleITK.Cast怎么用?Python SimpleITK.Cast使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类SimpleITK
的用法示例。
在下文中一共展示了SimpleITK.Cast方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: N4BiasFieldCorrection
# 需要导入模块: import SimpleITK [as 别名]
# 或者: from SimpleITK import Cast [as 别名]
def N4BiasFieldCorrection(src_path, dst_path):
'''
This function carry out BiasFieldCorrection for the files in a specific directory
:param src_path: path of the source file
:param dst_path: path of the target file
:return:
'''
print("N4 bias correction runs.")
inputImage = sitk.ReadImage(src_path)
maskImage = sitk.OtsuThreshold(inputImage, 0, 1, 200)
sitk.WriteImage(maskImage, dst_path)
inputImage = sitk.Cast(inputImage, sitk.sitkFloat32)
corrector = sitk.N4BiasFieldCorrectionImageFilter()
# corrector.SetMaximumNumberOfIterations(10)
output = corrector.Execute(inputImage, maskImage)
sitk.WriteImage(output, dst_path)
print("Finished N4 Bias Field Correction.....")
# normalize the data(zero mean and unit variance)
示例2: get_stack_multiplied_with_mask
# 需要导入模块: import SimpleITK [as 别名]
# 或者: from SimpleITK import Cast [as 别名]
def get_stack_multiplied_with_mask(self, filename=None, mask_sitk=None):
if mask_sitk is None:
mask_sitk = self.sitk_mask
# Multiply stack with its mask
image_sitk = self.sitk * \
sitk.Cast(mask_sitk, self.sitk.GetPixelIDValue())
if filename is None:
filename = self.get_filename()
return Stack.from_sitk_image(
image_sitk=image_sitk,
filename=filename,
image_sitk_mask=mask_sitk,
slice_thickness=self.get_slice_thickness(),
)
# Get stack resampled on isotropic grid based on the actual position of
# its slices
# \param[in] resolution length of voxel side, scalar
# \return isotropically, resampled stack as Stack object
示例3: write_image
# 需要导入模块: import SimpleITK [as 别名]
# 或者: from SimpleITK import Cast [as 别名]
def write_image(
image_sitk,
path_to_file,
compress=True,
verbose=True,
description=None,
):
info = "Write image to %s" % path_to_file
if compress:
image_sitk = sitk.Cast(image_sitk, sitk.sitkFloat32)
info += " (float32)"
if verbose:
ph.print_info("%s ... " % info, newline=False)
header_update = DataWriter._get_header_update(description=description)
sitkh.write_nifti_image_sitk(
image_sitk, path_to_file, header_update=header_update)
if verbose:
print("done")
示例4: write_mask
# 需要导入模块: import SimpleITK [as 别名]
# 或者: from SimpleITK import Cast [as 别名]
def write_mask(
mask_sitk,
path_to_file,
compress=True,
verbose=True,
description=None,
):
info = "Write mask to %s" % path_to_file
if compress:
mask_sitk = sitk.Cast(mask_sitk, sitk.sitkUInt8)
info += " (uint8)"
if verbose:
ph.print_info("%s ... " % info, newline=False)
header_update = DataWriter._get_header_update(description=description)
sitkh.write_nifti_image_sitk(
mask_sitk, path_to_file, header_update=header_update)
if verbose:
print("done")
示例5: itkRegionGrow
# 需要导入模块: import SimpleITK [as 别名]
# 或者: from SimpleITK import Cast [as 别名]
def itkRegionGrow(im_arr, type_str, seedlist, lower=0, upper=1):
func_1 = 'CT'
func_2 = 'CC'
# get an image from the array input
image = itkEdgePreservedSmoothing.itkEdgePreservedSmoothing(im_arr, 'CF')
image = sitk.GetImageFromArray(im_arr)
image = sitk.Cast(image, sitk.sitkFloat32)
# find out the way to process the image according to type_str
if type_str == func_1:
im_new = sitk.ConnectedThreshold(image, seedlist, lower, upper)
elif type_str == func_2:
im_new = sitk.ConfidenceConnected(image, seedlist)
else:
print('Please check your spelling,'
'and try again.')
return im_new
# an example of using the function
示例6: normalize_image
# 需要导入模块: import SimpleITK [as 别名]
# 或者: from SimpleITK import Cast [as 别名]
def normalize_image(image,
valid_min=-1024,
valid_max=3071):
image = sitk.Cast(image, sitk.sitkFloat32)
f_min_max = sitk.MinimumMaximumImageFilter()
f_min_max.Execute(image)
min_ = f_min_max.GetMinimum()
max_ = f_min_max.GetMaximum()
log.debug(f'Got image with value range [{min_}, {max_}]')
if min_ < valid_min or max_ > valid_max:
log.warning(
f'Got image with non-default hounsfield scale range: Got range ' \
f'[{min_}, {max_}]. Values will be clipped to [{valid_min}, {valid_max}].'
)
f_clamp = sitk.ClampImageFilter()
f_clamp.SetLowerBound(valid_min)
f_clamp.SetUpperBound(valid_max)
image = f_clamp.Execute(image)
f_subtract = sitk.SubtractImageFilter()
image = f_subtract.Execute(image, valid_min)
f_divide = sitk.DivideImageFilter()
return f_divide.Execute(image, valid_max - valid_min)
示例7: load_itk
# 需要导入模块: import SimpleITK [as 别名]
# 或者: from SimpleITK import Cast [as 别名]
def load_itk(filename):
"""
load mhd files and normalization 0-255
:param filename:
:return:
"""
rescalFilt = sitk.RescaleIntensityImageFilter()
rescalFilt.SetOutputMaximum(255)
rescalFilt.SetOutputMinimum(0)
# Reads the image using SimpleITK
itkimage = rescalFilt.Execute(sitk.Cast(sitk.ReadImage(filename), sitk.sitkFloat32))
return itkimage
开发者ID:junqiangchen,项目名称:LiTS---Liver-Tumor-Segmentation-Challenge,代码行数:14,代码来源:getPatchImageAndMask.py
示例8: loadImages
# 需要导入模块: import SimpleITK [as 别名]
# 或者: from SimpleITK import Cast [as 别名]
def loadImages(self):
self.sitkImages=dict()
rescalFilt=sitk.RescaleIntensityImageFilter()
rescalFilt.SetOutputMaximum(1)
rescalFilt.SetOutputMinimum(0)
stats = sitk.StatisticsImageFilter()
m = 0.
for f in self.fileList:
self.sitkImages[f]=rescalFilt.Execute(sitk.Cast(sitk.ReadImage(join(self.srcFolder, f)),sitk.sitkFloat32))
stats.Execute(self.sitkImages[f])
m += stats.GetMean()
self.meanIntensityTrain=m/len(self.sitkImages)
示例9: loadGT
# 需要导入模块: import SimpleITK [as 别名]
# 或者: from SimpleITK import Cast [as 别名]
def loadGT(self):
self.sitkGT=dict()
for f in self.gtList:
self.sitkGT[f]=sitk.Cast(sitk.ReadImage(join(self.srcFolder, f))>0.5,sitk.sitkFloat32)
示例10: write_dicom
# 需要导入模块: import SimpleITK [as 别名]
# 或者: from SimpleITK import Cast [as 别名]
def write_dicom(self):
self.dicom_dir = self.dir / 'dicom'
self.dicom_dir.mkdir(exist_ok=True)
self.dicom_path = self.dicom_dir / 'dicom.dcm'
self.nii_path = self.get_image_path('read_image')
writer = sitk.ImageFileWriter()
writer.SetFileName(str(self.dicom_path))
image = sitk.ReadImage(str(self.nii_path))
image = sitk.Cast(image, sitk.sitkUInt16)
image = image[0] # dicom reader supports 2D only
writer.Execute(image)
示例11: getLesionDetection
# 需要导入模块: import SimpleITK [as 别名]
# 或者: from SimpleITK import Cast [as 别名]
def getLesionDetection(testImage, resultImage):
"""Lesion detection metrics, both recall and F1."""
# Connected components will give the background label 0, so subtract 1 from all results
ccFilter = sitk.ConnectedComponentImageFilter()
ccFilter.SetFullyConnected(True)
# Connected components on the test image, to determine the number of true WMH.
# And to get the overlap between detected voxels and true WMH
ccTest = ccFilter.Execute(testImage)
lResult = sitk.Multiply(ccTest, sitk.Cast(resultImage, sitk.sitkUInt32))
ccTestArray = sitk.GetArrayFromImage(ccTest)
lResultArray = sitk.GetArrayFromImage(lResult)
# recall = (number of detected WMH) / (number of true WMH)
recall = float(len(np.unique(lResultArray)) - 1) / (len(np.unique(ccTestArray)) - 1)
# Connected components of results, to determine number of detected lesions
ccResult = ccFilter.Execute(resultImage)
ccResultArray = sitk.GetArrayFromImage(ccResult)
# precision = (number of detected WMH) / (number of all detections)
precision = float(len(np.unique(lResultArray)) - 1) / float(len(np.unique(ccResultArray)) - 1)
f1 = 2.0 * (precision * recall) / (precision + recall)
return recall, f1
示例12: run
# 需要导入模块: import SimpleITK [as 别名]
# 或者: from SimpleITK import Cast [as 别名]
def run(self):
# create zero image
coverage_sitk = sitk.Image(self._reconstruction_sitk) * 0
for i, stack in enumerate(self._stacks):
print("Slices of stack %d/%d ... " % (i + 1, len(self._stacks)))
# Add each individual slice contribution
for slice in stack.get_slices():
coverage_sitk = self._add_slice_contribution(
slice, coverage_sitk)
# Cast to unsigned integer
self._coverage_sitk = sitk.Cast(coverage_sitk, sitk.sitkUInt8)
##
# Adds a slice contribution.
# \date 2019-02-23 21:27:12+0000
#
# \param slice Slice as sl.Slice object
# \param coverage_sitk sitk.Image reflecting the current iteration of
# slice coverage
#
# \return Updated slice contribution, sitk.Image
#
示例13: _get_masked_image_slice
# 需要导入模块: import SimpleITK [as 别名]
# 或者: from SimpleITK import Cast [as 别名]
def _get_masked_image_slice(slice):
slice_sitk = slice.sitk * \
sitk.Cast(slice.sitk_mask, slice.sitk.GetPixelIDValue())
return slice_sitk
示例14: resample_image
# 需要导入模块: import SimpleITK [as 别名]
# 或者: from SimpleITK import Cast [as 别名]
def resample_image(image, out_spacing=(1.0, 1.0, 1.0), out_size=None, is_label=False, pad_value=0):
"""Resamples an image to given element spacing and output size."""
original_spacing = np.array(image.GetSpacing())
original_size = np.array(image.GetSize())
if out_size is None:
out_size = np.round(np.array(original_size * original_spacing / np.array(out_spacing))).astype(int)
else:
out_size = np.array(out_size)
original_direction = np.array(image.GetDirection()).reshape(len(original_spacing),-1)
original_center = (np.array(original_size, dtype=float) - 1.0) / 2.0 * original_spacing
out_center = (np.array(out_size, dtype=float) - 1.0) / 2.0 * np.array(out_spacing)
original_center = np.matmul(original_direction, original_center)
out_center = np.matmul(original_direction, out_center)
out_origin = np.array(image.GetOrigin()) + (original_center - out_center)
resample = sitk.ResampleImageFilter()
resample.SetOutputSpacing(out_spacing)
resample.SetSize(out_size.tolist())
resample.SetOutputDirection(image.GetDirection())
resample.SetOutputOrigin(out_origin.tolist())
resample.SetTransform(sitk.Transform())
resample.SetDefaultPixelValue(pad_value)
if is_label:
resample.SetInterpolator(sitk.sitkNearestNeighbor)
else:
#resample.SetInterpolator(sitk.sitkBSpline)
resample.SetInterpolator(sitk.sitkLinear)
return resample.Execute(sitk.Cast(image, sitk.sitkFloat32))
示例15: write_data
# 需要导入模块: import SimpleITK [as 别名]
# 或者: from SimpleITK import Cast [as 别名]
def write_data(self):
if self._filename is None:
raise ValueError("Filename is not set")
ph.create_directory(os.path.dirname(self._filename))
header_update = DataWriter._get_header_update(
description=self._description)
info = "Write image to '%s'" % self._filename
vector_image_sitk = sitkh.get_sitk_vector_image_from_components(
[stack.sitk for stack in self._stacks])
if self._compress:
if not "integer" in vector_image_sitk.GetPixelIDTypeAsString():
vector_image_sitk = sitk.Cast(
vector_image_sitk, sitk.sitkVectorFloat32)
info += " (float32)"
ph.print_info("%s ... " % info, newline=False)
sitkh.write_sitk_vector_image(
vector_image_sitk,
self._filename,
verbose=False,
header_update=header_update,
)
print("done")
if self._write_mask:
info = "Write image mask to '%s'" % self._filename
filename_split = (self._filename).split(".")
filename = filename_split[0]
filename += self._suffix_mask + "." + \
(".").join(filename_split[1:])
vector_image_sitk = sitkh.get_sitk_vector_image_from_components(
[stack.sitk_mask for stack in self._stacks])
if self._compress:
vector_image_sitk = sitk.Cast(
vector_image_sitk, sitk.sitkVectorUInt8)
info += " (uint8)"
ph.print_info("%s ... " % info, newline=False)
sitkh.write_sitk_vector_image(
vector_image_sitk,
filename,
verbose=False,
header_update=header_update,
)
print("done")