代码如下
import cv2
import numpy as np
import argparse
def zjlcz(image, new_height, new_width): #最近邻插值法
height=image.shape[0]
width = image.shape[1]
hp = height / new_height
wp = width / new_width #wp表示宽度变化比例,hp表示高度变化比例
new_image = np.zeros((new_height, new_width, 3), dtype=np.uint8)
for i in range(new_height):
for j in range(new_width):
x = int(j * wp)
y = int(i * hp)
new_image[i, j] = image[y, x]
return new_image
def sxxcz(image, new_height, new_width): #双线性插值法
height=image.shape[0]
width = image.shape[1]
hp = height / new_height
wp = width / new_width #wp表示宽度变化比例,hp表示高度变化比例
new_image = np.zeros((new_height, new_width, 3), dtype=np.uint8)
for i in range(new_height):
for j in range(new_width):
x = j * wp
y = i * hp
x1 = int(x)
y1 = int(y)
x2 = min(x1 + 1, width - 1)
y2 = min(y1 + 1, height - 1)
bl_1=(1 - (x - x1)) * (1 - (y - y1)) * image[y1, x1]
bl_2=(x - x1) * (1 - (y - y1)) * image[y1, x2]
bl_3=(1 - (x - x1)) * (y - y1) * image[y2, x1]
bl_4=(x - x1) * (y - y1) * image[y2, x2]
new_image[i, j] = bl_1+bl_2+bl_3+bl_4
return new_image
parser = argparse.ArgumentParser(description='图像插值')
parser.add_argument('in_path', type=str, help='原始图片路径')
parser.add_argument('out_path', type=str, help='生成图片路径')
parser.add_argument('new_height', type=int, help='图片高度')
parser.add_argument('new_width', type=int, help='图片宽度')
args = parser.parse_args()
img = cv2.imread(args.in_path)
zjlcz = zjlcz(img, args.new_height, args.new_width)#zjlcz()函数是最近邻插值法
sxxcz = sxxcz(img, args.new_height, args.new_width)#sxxcz()函数是双线性插值法
cv2.imwrite(args.out_path+"nearst_fa.png", zjlcz)
cv2.imwrite(args.out_path+"double_fa.png", sxxcz)
测试图片如下
双线性插值法结果如下
最近邻插值法结果如下