【问题标题】:Simple, efficient bilinear interpolation of images in numpy and python在 numpy 和 python 中对图像进行简单、高效的双线性插值
【发布时间】:2020-06-09 06:49:14
【问题描述】:

如何在 python 中为表示为 numpy 数组的图像数据实现双线性插值?

【问题讨论】:

    标签: python numpy interpolation


    【解决方案1】:

    我发现了很多关于这个主题的问题和很多答案,但对于数据由网格上的样本(即矩形图像)组成并表示为 numpy 数组的常见情况,没有一个是有效的。此函数可以将列表作为 x 和 y 坐标,并且无需循环即可执行查找和求和。

    def bilinear_interpolate(im, x, y):
        x = np.asarray(x)
        y = np.asarray(y)
    
        x0 = np.floor(x).astype(int)
        x1 = x0 + 1
        y0 = np.floor(y).astype(int)
        y1 = y0 + 1
    
        x0 = np.clip(x0, 0, im.shape[1]-1);
        x1 = np.clip(x1, 0, im.shape[1]-1);
        y0 = np.clip(y0, 0, im.shape[0]-1);
        y1 = np.clip(y1, 0, im.shape[0]-1);
    
        Ia = im[ y0, x0 ]
        Ib = im[ y1, x0 ]
        Ic = im[ y0, x1 ]
        Id = im[ y1, x1 ]
    
        wa = (x1-x) * (y1-y)
        wb = (x1-x) * (y-y0)
        wc = (x-x0) * (y1-y)
        wd = (x-x0) * (y-y0)
    
        return wa*Ia + wb*Ib + wc*Ic + wd*Id
    

    【讨论】:

    • 嗨,Alex,我正在寻找同样的东西,您的实现看起来不错。我掌握了基本用法,但是您能否提供一些高级示例(带有多个坐标)以使这个答案更好?
    • @ffriend:$im$ 是一个 2D numpy 数组,$x$ 和 $y$ 都是具有相同长度的普通 python 列表。
    • 嘿@AlexFlint,感谢您发布此内容,我有一个小建议。最后一行中的这个小差异将使它与 D 维值的 2D 网格兼容,即 [WxHxD],如 D​​=3 rgb 图像或更高:return (Ia.T*wa).T + (Ib.T*wb).T + (Ic.T*wc).T + (Id.T*wd).T 如果您有任何问题,请告诉我?谢谢!
    • @AlexFlint 我正在查看 wiki 定义:en.wikipedia.org/wiki/Bilinear_interpolation 并且我在您的解决方案中缺少 (y1-y0)*(x1-x0) 我缺少什么?有理由不分裂吗?
    • @ohadedelstain 请注意,在答案y1 = y0 + 1x1 = x0 + 1 中,因此(y1-y0)*(x1-x0) 始终为1。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-23
    • 1970-01-01
    • 2018-03-19
    相关资源
    最近更新 更多