当前位置: 首页>>代码示例>>Python>>正文


Python SimpleITK.GetImageFromArray方法代码示例

本文整理汇总了Python中SimpleITK.GetImageFromArray方法的典型用法代码示例。如果您正苦于以下问题:Python SimpleITK.GetImageFromArray方法的具体用法?Python SimpleITK.GetImageFromArray怎么用?Python SimpleITK.GetImageFromArray使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在SimpleITK的用法示例。


在下文中一共展示了SimpleITK.GetImageFromArray方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: loop

# 需要导入模块: import SimpleITK [as 别名]
# 或者: from SimpleITK import GetImageFromArray [as 别名]
def loop(self):
    if self.trigger == "internal":
      if self.fps_label:
        while self.inputs[0].poll():
          self.camera.max_fps = self.inputs[0].recv()[self.fps_label]
      t,img = self.camera.read_image()
    elif self.trigger == "external":
      data = self.inputs[0].recv()  # wait for a signal
      if data is None:
        return
      t,img = self.camera.get_image()
    self.timer = time.time()
    if self.save_folder:
      if not sitk:
        raise IOError("[Camera] Cannot save image, sitk is not installed !")
      image = sitk.GetImageFromArray(img)
      sitk.WriteImage(image,
               self.save_folder + "img_%.6d_%.5f.tiff" % (
               self.loops, t-self.t0))
    self.loops += 1
    self.send([t-self.t0,img]) 
开发者ID:LaboratoireMecaniqueLille,项目名称:crappy,代码行数:23,代码来源:camera.py

示例2: produceRandomlyTranslatedImage

# 需要导入模块: import SimpleITK [as 别名]
# 或者: from SimpleITK import GetImageFromArray [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 
开发者ID:faustomilletari,项目名称:VNet,代码行数:26,代码来源:utilities.py

示例3: get_borders_mean

# 需要导入模块: import SimpleITK [as 别名]
# 或者: from SimpleITK import GetImageFromArray [as 别名]
def get_borders_mean(image, filter_otsu=True):
    # pylint: disable=bad-whitespace
    array = sitk.GetArrayViewFromImage(image)
    borders_tuple = (
        array[ 0,  :,  :],
        array[-1,  :,  :],
        array[ :,  0,  :],
        array[ :, -1,  :],
        array[ :,  :,  0],
        array[ :,  :, -1],
    )
    borders_flat = np.hstack([border.ravel() for border in borders_tuple])
    if not filter_otsu:
        return borders_flat.mean()
    borders_reshaped = borders_flat.reshape(1, 1, -1)
    borders_image = sitk.GetImageFromArray(borders_reshaped)
    otsu = sitk.OtsuThresholdImageFilter()
    otsu.Execute(borders_image)
    threshold = otsu.GetThreshold()
    values = borders_flat[borders_flat < threshold]
    if values.any():
        default_value = values.mean()
    else:
        default_value = borders_flat.mean()
    return default_value 
开发者ID:fepegar,项目名称:torchio,代码行数:27,代码来源:random_affine.py

示例4: itk

# 需要导入模块: import SimpleITK [as 别名]
# 或者: from SimpleITK import GetImageFromArray [as 别名]
def itk(self):

        # flip axis to
        df = Displacement(self.image.clone(), self.size, self.spacing, self.origin)
        df._reverse_axis()
        df.image = df.image.squeeze()
        df.image = df.image.cpu()

        if len(self.size) == 2:
            itk_displacement = sitk.GetImageFromArray(df.image.numpy(), isVector=True)
        elif len(self.size) == 3:
            itk_displacement = sitk.GetImageFromArray(df.image.numpy())

        itk_displacement.SetSpacing(spacing=self.spacing)
        itk_displacement.SetOrigin(origin=self.origin)
        return itk_displacement 
开发者ID:airlab-unibas,项目名称:airlab,代码行数:18,代码来源:image.py

示例5: copy_BraTS_segmentation_and_convert_labels

# 需要导入模块: import SimpleITK [as 别名]
# 或者: from SimpleITK import GetImageFromArray [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) 
开发者ID:mlperf,项目名称:inference,代码行数:20,代码来源:Task043_BraTS_2019.py

示例6: preprocess_img

# 需要导入模块: import SimpleITK [as 别名]
# 或者: from SimpleITK import GetImageFromArray [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) 
开发者ID:Ryo-Ito,项目名称:brain_segmentation,代码行数:24,代码来源:preprocess.py

示例7: CalDice

# 需要导入模块: import SimpleITK [as 别名]
# 或者: from SimpleITK import GetImageFromArray [as 别名]
def CalDice(self, pred, gt, class_lbl=1):
        """
        Calculate dice score
        """
        # intersection = np.sum((pred == class_lbl) & (gt == class_lbl))
        # dice_4d = 2.0 *(intersection)/(np.sum(pred == class_lbl) + np.sum(gt == class_lbl))
        dices = []
        for i in range(pred.shape[3]):
            labelPred=sitk.GetImageFromArray(pred[:,:,:,i], isVector=False)
            labelTrue=sitk.GetImageFromArray(gt[:,:,:,i], isVector=False)
            dicecomputer=sitk.LabelOverlapMeasuresImageFilter()
            dicecomputer.Execute(labelTrue==class_lbl,labelPred==class_lbl)
            dice=dicecomputer.GetDiceCoefficient()
            dices.append(dice)
        # print (np.mean(dices), dice_4d)
        return np.mean(dices) 
开发者ID:mahendrakhened,项目名称:Automated-Cardiac-Segmentation-and-Disease-Diagnosis,代码行数:18,代码来源:test_utils.py

示例8: _add_slice_contribution

# 需要导入模块: import SimpleITK [as 别名]
# 或者: from SimpleITK import GetImageFromArray [as 别名]
def _add_slice_contribution(slice, coverage_sitk):

        #
        slice_sitk = sitk.Image(slice.sitk)
        spacing = np.array(slice_sitk.GetSpacing())
        spacing[-1] = slice.get_slice_thickness()
        slice_sitk.SetSpacing(spacing)

        contrib_nda = sitk.GetArrayFromImage(slice_sitk)
        contrib_nda[:] = 1
        contrib_sitk = sitk.GetImageFromArray(contrib_nda)
        contrib_sitk.CopyInformation(slice_sitk)

        coverage_sitk += sitk.Resample(
            contrib_sitk,
            coverage_sitk,
            sitk.Euler3DTransform(),
            sitk.sitkNearestNeighbor,
            0,
            coverage_sitk.GetPixelIDValue(),
        )

        return coverage_sitk 
开发者ID:gift-surg,项目名称:NiftyMIC,代码行数:25,代码来源:slice_coverage.py

示例9: run

# 需要导入模块: import SimpleITK [as 别名]
# 或者: from SimpleITK import GetImageFromArray [as 别名]
def run(self):
        mask_sitk = self._srr_mask_sitk

        # Smooth mask
        mask_sitk = sitk.SmoothingRecursiveGaussian(mask_sitk, self._sigma)

        # Binarize images given thresholds
        mask_sitk = sitk.BinaryThreshold(
            mask_sitk, lowerThreshold=self._lower, upperThreshold=self._upper)

        # Keep largest connected region only
        nda = sitk.GetArrayFromImage(mask_sitk)
        nda = tse.TemplateStackEstimator.get_largest_connected_region_mask(nda)

        self._mask_sitk = sitk.GetImageFromArray(nda)
        self._mask_sitk.CopyInformation(mask_sitk) 
开发者ID:gift-surg,项目名称:NiftyMIC,代码行数:18,代码来源:binary_mask_from_mask_srr_estimator.py

示例10: hausdorff_distance

# 需要导入模块: import SimpleITK [as 别名]
# 或者: from SimpleITK import GetImageFromArray [as 别名]
def hausdorff_distance(predictions, labels, one_hot=False, unindexed_classes=0, spacing=[1, 1, 1]):
    def one_class_hausdorff_distance(pred, lab):
        hausdorff_distance_filter = sitk.HausdorffDistanceImageFilter()
        batch = pred.shape[0]
        result = []
        for i in range(batch):
            pred_img = sitk.GetImageFromArray(pred[i].cpu().numpy())
            pred_img.SetSpacing(spacing)
            lab_img = sitk.GetImageFromArray(lab[i].cpu().numpy())
            lab_img.SetSpacing(spacing)
            hausdorff_distance_filter.Execute(pred_img, lab_img)
            result.append(hausdorff_distance_filter.GetHausdorffDistance())
        return torch.tensor(np.asarray(result))

    return multi_class_score(one_class_hausdorff_distance, predictions, labels, one_hot=one_hot,
                             unindexed_classes=unindexed_classes) 
开发者ID:biomedia-mira,项目名称:istn,代码行数:18,代码来源:metrics.py

示例11: average_surface_distance

# 需要导入模块: import SimpleITK [as 别名]
# 或者: from SimpleITK import GetImageFromArray [as 别名]
def average_surface_distance(predictions, labels, one_hot=False, unindexed_classes=0, spacing=[1, 1, 1]):
    def one_class_average_surface_distance(pred, lab):
        hausdorff_distance_filter = sitk.HausdorffDistanceImageFilter()
        batch = pred.shape[0]
        result = []
        for i in range(batch):
            pred_img = sitk.GetImageFromArray(pred[i].cpu().numpy())
            pred_img.SetSpacing(spacing)
            lab_img = sitk.GetImageFromArray(lab[i].cpu().numpy())
            lab_img.SetSpacing(spacing)
            hausdorff_distance_filter.Execute(pred_img, lab_img)
            result.append(hausdorff_distance_filter.GetAverageHausdorffDistance())
        return torch.tensor(np.asarray(result))

    return multi_class_score(one_class_average_surface_distance, predictions, labels, one_hot=one_hot,
                             unindexed_classes=unindexed_classes) 
开发者ID:biomedia-mira,项目名称:istn,代码行数:18,代码来源:metrics.py

示例12: zero_mean_unit_var

# 需要导入模块: import SimpleITK [as 别名]
# 或者: from SimpleITK import GetImageFromArray [as 别名]
def zero_mean_unit_var(image, mask=None, fill_value=0):
    """Normalizes an image to zero mean and unit variance."""

    img_array = sitk.GetArrayFromImage(image)
    img_array = img_array.astype(np.float32)

    msk_array = np.ones(img_array.shape)

    if mask is not None:
        msk_array = sitk.GetArrayFromImage(mask)

    mean = np.mean(img_array[msk_array>0])
    std = np.std(img_array[msk_array>0])

    if std > 0:
        img_array = (img_array - mean) / std
        img_array[msk_array==0] = fill_value

    image_normalised = sitk.GetImageFromArray(img_array)
    image_normalised.CopyInformation(image)

    return image_normalised 
开发者ID:biomedia-mira,项目名称:istn,代码行数:24,代码来源:processing.py

示例13: range_matching

# 需要导入模块: import SimpleITK [as 别名]
# 或者: from SimpleITK import GetImageFromArray [as 别名]
def range_matching(image, mask=None, low_percentile=4, high_percentile=96, fill_value=0):
    """Normalizes an image by mapping the low_percentile to zero, and the high_percentile to one."""

    img_array = sitk.GetArrayFromImage(image)
    img_array = img_array.astype(np.float32)

    msk_array = np.ones(img_array.shape)

    if mask is not None:
        msk_array = sitk.GetArrayFromImage(mask)

    lo_p = np.percentile(img_array[msk_array>0], low_percentile)
    hi_p = np.percentile(img_array[msk_array>0], high_percentile)

    img_array = (img_array - lo_p) / (hi_p - lo_p)
    img_array[msk_array == 0] = fill_value

    image_normalised = sitk.GetImageFromArray(img_array)
    image_normalised.CopyInformation(image)

    return image_normalised 
开发者ID:biomedia-mira,项目名称:istn,代码行数:23,代码来源:processing.py

示例14: zero_one

# 需要导入模块: import SimpleITK [as 别名]
# 或者: from SimpleITK import GetImageFromArray [as 别名]
def zero_one(image, mask=None, fill_value=0):
    """Normalizes an image by mapping the min to zero, and max to one."""

    img_array = sitk.GetArrayFromImage(image)
    img_array = img_array.astype(np.float32)

    msk_array = np.ones(img_array.shape)

    if mask is not None:
        msk_array = sitk.GetArrayFromImage(mask)

    min_value = np.min(img_array[msk_array>0])
    max_value = np.max(img_array[msk_array>0])

    img_array = (img_array - min_value) / (max_value - min_value)
    img_array[msk_array == 0] = fill_value

    image_normalised = sitk.GetImageFromArray(img_array)
    image_normalised.CopyInformation(image)

    return image_normalised 
开发者ID:biomedia-mira,项目名称:istn,代码行数:23,代码来源:processing.py

示例15: saveImagesFromDM

# 需要导入模块: import SimpleITK [as 别名]
# 或者: from SimpleITK import GetImageFromArray [as 别名]
def saveImagesFromDM(dataMatrix, outputPrefix, referenceImName):
    """Save 3D images from data matrix."""
    im_ref = sitk.ReadImage(referenceImName)
    im_ref_array = sitk.GetArrayFromImage(im_ref)  # get numpy array
    z_dim, x_dim, y_dim = im_ref_array.shape  # get 3D volume shape
    num_of_data = dataMatrix.shape[1]
    list_files = []
    for i in range(num_of_data):
        im = np.array(dataMatrix[:, i]).reshape(z_dim, x_dim, y_dim)
        img = sitk.GetImageFromArray(im)
        img.SetOrigin(im_ref.GetOrigin())
        img.SetSpacing(im_ref.GetSpacing())
        img.SetDirection(im_ref.GetDirection())
        fn = outputPrefix + str(i) + '.nrrd'
        list_files.append(fn)
        sitk.WriteImage(img, fn, True)
    del im_ref, im_ref_array
    return list_files 
开发者ID:KitwareMedical,项目名称:pyLAR,代码行数:20,代码来源:images.py


注:本文中的SimpleITK.GetImageFromArray方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。