在网上找了一圈,没有找到完整且正确的python代码,所以在这里发出来

理论可以直接看一下​ ​百度百科:双线性插值​

公式很简单,画一下图就知道怎么回事了,简单说就是根据相邻点的远近乘以对应的权重,离得越远权重越小,离得越近权重越大

重点就是一个公式:

f(x,y) = f(0,0)*(1-a)*(1-b) +f(0,1)*(1-a)*b + f(1,0)*a*(1-b) + f(1,1)*a*b

这里要特别说明的是,在边缘处理上,我也采用了类似的方法:

在底部边缘采用:f(x,y) = f(0,0)*(1-b) + f(0,1)*b

在右部边缘采用:f(x,y) = f(0,0)*(1-a) + f(1,0)*a

在四角采用:f(x,y) = f(0,0)

# -------------------------------------------------------------------------------
# Description: 双线性内插(该方法针对图像放大)
# Description: 效果:双线性内插 > 最近邻插值 > 图片通过Ctrl键进行放大
# Description: 《数字图像处理》P.44
# Reference:
# Author: Sophia
# Date: 2021/3/24
# -------------------------------------------------------------------------------
import numpy as np
import cv2

ep = 1e-5


def BI(img, img_shape, tar_shape):
srcH, srcW = img_shape
tarH, tarW = tar_shape
ratioH = tarH / srcH
ratioW = tarW / srcW
tarImg = np.zeros((int(tarH), int(tarW), 3))
for h in range(int(tarH)):
for w in range(int(tarW)):
x, y = h / ratioH, w / ratioW
x_int, y_int = int(x), int(y)
a, b = x - x_int, y - y_int
if abs(x_int + 1 - srcH) < ep:
if abs(y_int + 1 - srcW) < ep:
tarImg[h, w, :] = img[x_int, y_int, :]
else:
tarImg[h, w, :] = img[x_int, y_int, :] * (1 - b) + img[x_int, y_int + 1, :] * b
elif abs(y_int + 1 - srcW) < ep:
tarImg[h, w, :] = img[x_int, y_int, :] * (1 - a) + img[x_int + 1, y_int, :] * a
else:
tarImg[h, w, :] = img[x_int, y_int, :] * (1 - a) * (1 - b) \
+ img[x_int + 1, y_int, :] * a * (1 - b) \
+ img[x_int, y_int + 1, :] * (1 - a) * b \
+ img[x_int + 1, y_int + 1, :] * a * b
return tarImg


img = cv2.imread('./images/bug.png')
img_shape = (img.shape[0], img.shape[1])
tar_shape = (img.shape[0] * 1.5, img.shape[1] * 1.5)
tarImg = BI(img, img_shape, tar_shape)
cv2.imwrite('./images/bug_BI_1.5.png', tarImg)

bug.png

双线性内插法&最近邻内插法-python(详细)_python代码

结果: 放大五倍 之后的效果图, 前一张是双线性内插法 生成图, 后一张是最近邻内插法 生成图,明显前者比后者的效果要好

双线性内插法&最近邻内插法-python(详细)_python代码_02


双线性内插法&最近邻内插法-python(详细)_插值_03

这里顺便放一下最近邻内插法的python代码:

# -------------------------------------------------------------------------------
# Description: 最近邻内插(该方法针对图像放大)
# Description: 效果:最近邻插值 > 图片通过Ctrl键进行放大
# Description: 《数字图像处理》P.44
# Reference:
# Author: Sophia
# Date: 2021/3/24
# -------------------------------------------------------------------------------
import numpy as np
import cv2


def NNI(img, img_shape, tar_shape):
ratioH = tar_shape[0] / img_shape[0]
ratioW = tar_shape[1] / img_shape[1]
tarImg = np.zeros((int(tar_shape[0]), int(tar_shape[1]), 3))
for h in range(int(tar_shape[0])):
for w in range(int(tar_shape[1])):
srch = int(h / ratioH)
srcw = int(w / ratioW)
tarImg[h][w] = img[srch][srcw]
return tarImg


img = cv2.imread('./images/sophia.jpg')
img_shape = (img.shape[0], img.shape[1])
tar_shape = (img.shape[0] * 2, img.shape[1] * 2)
tarImg = NNI(img, img_shape, tar_shape)
cv2.imwrite('./images/sophia_NNI_2.png', tarImg)