首页 > 解决方案 > Python中3D数组的任意切片

问题描述

我有一个 3D 体积数据存储在一个背景值为 0 和体积值为 1 的 3 维数组中。现在我想获得这个体积的任意截面。我在这里阅读了答案:matplotlib 如何绘制 3D 数据集中的几乎任意平面?

但似乎接受的答案是错误的,它生成 xoy 平面的映射坐标而不是切片坐标。那么如何得到切片平面的正确形状呢?有没有将映射形状转换为原始形状的方法?谢谢!

标签: pythonarraysslice

解决方案


该问题可能已过时,但看起来以下功能scipy.ndimage可能会解决您的问题。

它的作用是scipy.ndimage.interpolation.rotate将完整的 3d 数组围绕 3 个轴中的任何一个旋转一定角度,将存储的值内插到新的“单元格”。它还相应地调整(扩展)新数组的大小,用您指定的值填充新的空单元格。之后,您可以像往常一样进行切片,例如:array[:,sy//2,:]

简而言之,这里是围绕平行于 z 轴的对角线的中心切割(为简单起见):

sz, sy, sx = array.shape
array[:,sy//2,:] # this is a cut in the x-z plane ... 
                 # ... passing through the middle of the y-axis

# rotating by 45 degrees around the z axis ... 
# ... `(2,1)` is `(x,y)` which defines the rotation plane
array_rotated = scipy.ndimage.interpolation.rotate(array, angle=45, axes=(2,1))

sz, sy, sx = array_rotated.shape
# now you'll notice that `sz` is the same ... 
# ... but `sx` and `sy` have increased because the diagonal is longer

array_rotated[:,sy//2,:] # this slice is now in the new x'-z' plane ...
                         # ... but in terms of the original array ...
                         # ... it passes through the diagonal of x-y along z

实际上,您可以进一步思考并通过围绕不同轴旋转几次来将其扩展到任意切片。

PS。如果您觉得需要太多时间,您可以通过传递order=0(默认为order=3)来牺牲插值质量。这将运行得更快。


推荐阅读