0

SimpleITK我可以这样做

img = sitk.ReadImage(file_path)
array = sitk.GetArrayFromImage(img)
array[array > 10] = 10
array[array < 0] = 0

或者我可以这样做,

img = sitk.ReadImage(file_path)
binthresh = sitk.BinaryThresholdFilter()
... # set up params for binthresh
img = binthresh.Execute(img)

但问题是,我想利用 SimpleITK.ResampleImageFilter` 的快速速度,因此我必须像这样使用它,

img = sitk.ReadImage(file_path)
binthresh = sitk.BinaryThresholdFilter()
... # set up params for binthresh
img = binthresh.Execute(img)
resample = sitk.ResampleImageFilter()
... # set up params for resample
img = resample.Execute(img)

其实我希望有这样的方法,

img = sitk.ReadImage(file_path)
array_view = sitk.GetArrayViewFromImage(img)
array_view[array_view > 10] = 10
array_view[array_view < 0] = 0
resample = sitk.ResampleImageFilter()
... # set up params for resample
img = resample.Execute(img)

上面的代码块看起来很紧凑,但是array_viewfromGetArrayViewFromImage是只读的。因此,有没有办法做到这一点?

4

1 回答 1

2

使用 SimpleITK 当前的 实现GetArrayViewFromImage,防止别名(浅拷贝)是最安全的,这样可以避免潜在的无效内存访问。因此,没有实现可写访问方法。然而,当前的开发正在开发一种安全的引用计数访问方法,该方法将支持写入。

但是,SimpleITK 中有一个等效的图像过滤器来执行与ClampImageFilter相同的操作。它也更快:


In [1]: import numpy as np                                                                                                                                      

In [2]: import SimpleITK as sitk                                                                                                                                

In [3]: a = np.random.rand(512,512,128)*100-50                                                                                                                  

In [4]: img = sitk.GetImageFromArray(a)                                                                                                                         

In [5]: %timeit -n 10 sitk.Clamp(img, lowerBound=0, upperBound=10)                                                                                              
41.5 ms ± 1.11 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [6]: def f(a, copy=False): 
   ...:     out = a 
   ...:     if copy: 
   ...:         out = np.copy(a) 
   ...:     out[out>10] = 10 
   ...:     out[out<0] = 0 
   ...:     return out 
   ...:                                                                                                                                                         

In [7]: %timeit -n 10 f(a, copy=False)                                                                                                                          
49.7 ms ± 11.7 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [8]: %timeit -n 10 f(a, copy=True)                                                                                                                           
84.8 ms ± 228 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
于 2019-09-18T18:25:00.627 回答