我可以用numpy操作吗简单图像不使用GetArrayFromImag进行转换

2024-07-03 04:25:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我可以在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)

但问题是,我想利用SimpleTk.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)

上面的代码块似乎非常紧凑,但是来自GetArrayViewFromImagearray_view是只读的。因此,有没有办法做到等价呢?你知道吗


Tags: pathviewimgforexecuteparamsarrayfile
1条回答
网友
1楼 · 发布于 2024-07-03 04:25:31

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

但是,SimpleTk中有一个等效的图像过滤器来执行与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)

相关问题 更多 >