微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用numpy实现3D双线性插值?

如何解决如何使用numpy实现3D双线性插值?

我已经达到了这个双线性插值代码(在此处添加),但是我想将此代码改进为3D,这意味着将其更新为可以处理RGB图像(3D,而不是仅2D)。

如果您有什么建议,我想知道。

这是一维线性插值:

import math

def linear1D_resize(in_array,size):
    """
    `in_array` is the input array.
    `size` is the desired size.
    """
    ratio = (len(in_array) - 1) / (size - 1)
    out_array = []

    for i in range(size):
        low = math.floor(ratio * i)
        high = math.ceil(ratio * i)
        weight = ratio * i - low

        a = in_array[low]
        b = in_array[high]

        out_array.append(a * (1 - weight) + b * weight)

    return out_array

这对于2D:

import math
def bilinear_resize(image,height,width):
    """
    `image` is a 2-D numpy array
    `height` and `width` are the desired spatial dimension of the new 2-D array.
    """
    img_height,img_width = image.shape[:2]

    resized = np.empty([height,width])

    x_ratio = float(img_width - 1) / (width - 1) if width > 1 else 0
    y_ratio = float(img_height - 1) / (height - 1) if height > 1 else 0

    for i in range(height):
        for j in range(width):
            x_l,y_l = math.floor(x_ratio * j),math.floor(y_ratio * i)
            x_h,y_h = math.ceil(x_ratio * j),math.ceil(y_ratio * i)

            x_weight = (x_ratio * j) - x_l
            y_weight = (y_ratio * i) - y_l

            a = image[y_l,x_l]
            b = image[y_l,x_h]
            c = image[y_h,x_l]
            d = image[y_h,x_h]

            pixel = a * (1 - x_weight) * (1 - y_weight) + b * x_weight * (1 - y_weight) + c * y_weight * (1 - x_weight) + d * x_weight * y_weight
            resized[i][j] = pixel      # pixel is the scalar with the value comptued by the interpolation

    return resized

解决方法

检查一些scipy ndimage插值函数。他们会做您想要的并且正在使用numpy。

它们还非常实用,快速并且已经过多次测试。

理查德

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。