# -------------------------------------------------------------------------------
# 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)