繁体   English   中英

如何使用插值将任意 Numpy NDArray 调整为新形状

[英]How to resize an arbitrary Numpy NDArray to a new shape with interpolation

评论:

这是一个贡献而不是一个问题,因为我将回答我自己的问题。 但是,我仍然对社区如何解决这个问题感兴趣。 所以随意回答。


故事:

因此,当我在 Python(即 PySide6)中使用 QT 和它的 Volumerendering 功能时,我在设置我的数据数组时注意到了一些问题。 长话短说:我不知道(如果 QT 文档中的某处有说明)所提供的纹理必须是每个维度都是 2 的幂的形状。

因此,我想将我的数组重新调整为满足此标准的形状。

用 numpy 计算这个形状很容易:
new_shape = numpy.power(2, numpy.ceil(numpy.log2(old_shape))).astype(int)

现在剩下的唯一问题是将形状为new_shape的数组重新缩放为形状为old_shape的新数组,并正确插入值。

而且由于我通常只对某种通用方法感兴趣(谁知道这可能对谁有利以及将来对谁有利),所以确实出现了以下问题:

问题

如何通过适当的插值将任意 Numpy NDArray 形状old_shape调整为 Numpy NDArray 形状new shape

我尝试使用 scipy RegularGridInterpolator 重新调整我的数组,它确实有效。

我使用 scipy 的RegularGridInterpolator来插入我的数组。

其他插值器也应该工作。

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.

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