如何在图像/ ndarray上应用scipy.interpolate.RBFInterpolator?

0 投票
1 回答
35 浏览
提问于 2025-04-12 13:20

比如,我想知道怎么在用opencv加载的图像上使用 RBFInterpolator

我需要用numpy的向量运算来进行插值,因为这样速度很快。

我想对图像进行非仿射变换,也就是在图像的点之间定义插值。

我该怎么做呢?

1 个回答

1
import cv2
import numpy as np
from scipy.interpolate import RBFInterpolator

# Load the image
image = cv2.imread('image.png')
width,height = image.shape[:2]
w=width
h=height

# Your source points and corresponding destination points
src_points = np.array([
    [0, 0],
    [w,h],
    [w,0],
    [0,h],
])

dst_points = np.array([
    [0, 0],
    [w,h],
    [w,0],
    [0,h],
])

# Create the RBF interpolator instance
rbfx = RBFInterpolator(src_points,dst_points[:,0],kernel="thin_plate_spline")
rbfy = RBFInterpolator(src_points,dst_points[:,1],kernel="thin_plate_spline")

# Create a meshgrid to interpolate over the entire image
img_grid = np.mgrid[0:width, 0:height]

# flatten grid so it could be feed into interpolation
flatten=img_grid.reshape(2, -1).T

# Interpolate the displacement using the RBF interpolators
map_x = rbfx(flatten).reshape(width,height).astype(np.float32)
map_y = rbfy(flatten).reshape(width,height).astype(np.float32)
# Apply the remapping to the image using OpenCV
warped_image = cv2.remap(image, map_y, map_x, cv2.INTER_LINEAR)

# Save or display the result
cv2.imwrite('remap.png', warped_image)

上面的代码应该能生成和输入图片一样的图像。

你可以改变源点和目标点来进行图像变换。

我觉得还有更快的方法来做这个插值,但这是我想到的。

如果你需要对同一张图片进行多次变换,我建议你缓存一下flatten,这样就可以重复使用,而不是每次都重新创建。

撰写回答