[英]How to resize an arbitrary Numpy NDArray to a new shape with interpolation
This is rather a contribution than a question since I will answer my own question.这是一个贡献而不是一个问题,因为我将回答我自己的问题。 However, I am still interested in how the community would solve this problem.但是,我仍然对社区如何解决这个问题感兴趣。 So feel free to answer.所以随意回答。
So when I was playing around with QT in Python (ie, PySide6) and it's Volumerendering capabilities I noticed some problems when setting my data array.因此,当我在 Python(即 PySide6)中使用 QT 和它的 Volumerendering 功能时,我在设置我的数据数组时注意到了一些问题。 Long story short: I didn't know (and if it is stated somwhere in the QT documentation at all) that the provided texture has to be of a shape where each dimension is a power of two.长话短说:我不知道(如果 QT 文档中的某处有说明)所提供的纹理必须是每个维度都是 2 的幂的形状。
Thus, I wanted to rescale my array to a shape which fulfills this criteria.因此,我想将我的数组重新调整为满足此标准的形状。
Calculating this shape with numpy is easy:用 numpy 计算这个形状很容易:
new_shape = numpy.power(2, numpy.ceil(numpy.log2(old_shape))).astype(int)
Now the only problem left is to rescale my array with shape old_shape
to the new array with shape new_shape
and properly interpolate the values.现在剩下的唯一问题是将形状为new_shape
的数组重新缩放为形状为old_shape
的新数组,并正确插入值。
And since I am usually only interested in some sort of generic approaches (who knows what this might be good for and for whom in the future), the following question did arise:而且由于我通常只对某种通用方法感兴趣(谁知道这可能对谁有利以及将来对谁有利),所以确实出现了以下问题:
How to resize an arbitrary Numpy NDArray of shape old_shape
to a Numpy NDArray of shape new shape
with proper interpolation?如何通过适当的插值将任意 Numpy NDArray 形状old_shape
调整为 Numpy NDArray 形状new shape
?
I tried using scipy RegularGridInterpolator to rescale my array and it actually worked.我尝试使用 scipy RegularGridInterpolator 重新调整我的数组,它确实有效。
I used scipy's RegularGridInterpolator to interpolate my array.我使用 scipy 的RegularGridInterpolator来插入我的数组。
Other interpolators should work as well.其他插值器也应该工作。
def resample_array_to_shape(array: np.array, new_shape, method="linear"):
# generate points for each entry in the array
entries = [np.arange(s) for s in array.shape]
# the value for each point corresponds to its value in the original array
interp = RegularGridInterpolator(entries, array, method=method)
# new entries
new_entries = [np.linspace(0, array.shape[i] - 1, new_shape[i]) for i in range(len(array.shape))]
# use 'ij' indexing to avoid swapping axes
new_grid = np.meshgrid(*new_entries, indexing='ij')
# interpolate and return
return interp(tuple(new_grid)).astype(array.dtype)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.