简体   繁体   English

SimpleItk 裁剪图像

[英]SimpleItk crop image

I would like to crop a 3D image using simpleItk in Python3我想在 Python3 中使用 simpleItk 裁剪 3D 图像

first, loading the image and get numpy array首先,加载图像并获取 numpy 数组

image_ct = sitk.ReadImage(path_ct, sitk.sitkInt16)
array_ct = sitk.GetArrayFromImage(image_ct)

then I do a crop on array data然后我对数组数据进行裁剪

center = (200, 200, 200)
array_gt = array_gt[center[0]-50:center[0]+51, center[1]-50:center[1]+51, center[2]-40:center[2]+41]

now I wanna create an sitk.Image from the array and save the result现在我想从数组创建一个 sitk.Image 并保存结果

def create_ref_image(image, size=(101, 101, 81), spacing=(0.97, 0.97, 0.97), dimension=3):

    ref_origin = np.zeros(dimension)
    ref_direction = np.identity(dimension).flatten()
    ref_image = sitk.Image(size, image.GetPixelIDValue())
    ref_image.SetOrigin(ref_origin)
    ref_image.SetSpacing(spacing)
    ref_image.SetDirection(ref_direction)

    return ref_image

ref_img = create_ref_image(image_ct)
cropped_img = sitk._SimpleITK._SetImageFromArray(np.ascontiguousarray(array_gt), ref_img)
sitk.WriteImage(cropped_img, "/DATA/exemple.nii")

but then I get this error但后来我得到了这个错误

File ".../anaconda3/envs/objD/lib/python3.6/site-packages/SimpleITK/SimpleITK.py", line 8207, in WriteImage return _SimpleITK.WriteImage(*args) ValueError: invalid null reference in method 'WriteImage', argument 1 of type 'itk::simple::Image const &'文件“.../anaconda3/envs/objD/lib/python3.6/site-packages/SimpleITK/SimpleITK.py”,第 8207 行,在 WriteImage 中返回 _SimpleITK.WriteImage(*args) ValueError:无效 null 引用在方法' WriteImage','itk::simple::Image const &' 类型的参数 1

How can I crop an image using SimpleItk (in python)?如何使用 SimpleItk(在 python 中)裁剪图像?

Turn out you can simply use slicing operator directly on sitk.Image;结果你可以直接在sitk.Image上使用切片操作符;

image_ct = image_ct[center[0]-50:center[0]+51, center[1]-50:center[1]+51, center[2]-40:center[2]+41]

sitk.WriteImage(image_ct, "/DATA/exemple.nii")

In addition to cropping via Python slicing, SimpleITK has a Crop function and a CropImageFilter.除了通过 Python 切片进行裁剪外,SimpleITK 还有一个 Crop function 和一个 CropImageFilter。

Here's the doc for the Crop function:这是作物 function 的文档:

https://itk.org/SimpleITKDoxygen/html/namespaceitk_1_1simple.html#a4458c40720e7d78ace07181e13064865 https://itk.org/SimpleITKDoxygen/html/namespaceitk_1_1simple.html#a4458c40720e7d78ace07181e13064865

and the CropImageFilter:和 CropImageFilter:

https://itk.org/SimpleITKDoxygen/html/classitk_1_1simple_1_1CropImageFilter.html https://itk.org/SimpleITKDoxygen/html/classitk_1_1simple_1_1CropImageFilter.html

The functionality is the same as slicing, but if you need to crop a number of images the same way it may be convenient to have a CropImageFilter object that is executed for all the images.功能与切片相同,但如果您需要以相同的方式裁剪大量图像,则可以方便地为所有图像执行 CropImageFilter object。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM