双线性插值其实就是 根据需要resize的大小和原始图像的大小之比得到缩放比例,然后在求目标图的每一个像素的时候,根据这个比例找到其应该在原图的位置,这个位置可能会是小数,就用到该位置周围4个整数像素点的值来计算该位置的像素,然后离该位置距离近的点所占该位置值的权重要大一些.实现代码如下,效率有点低,待改进
from PIL import Image
from datetime import datetime
import matplotlib.pyplot as plt
import numpy as np
import math
import os
img_path = r'C:\Users\king\Pictures\简历\微信图片_20190731154219.jpg'
img_arr = np.array(Image.open(img_path), np.uint8)
target_size = (800, 600, 3)
cur_size = img_arr.shape
ratio_x, ratio_y = target_size[0] / cur_size[0], target_size[1] / cur_size[1]
def cal(x, y, c):
t_left_x, t_left_y = math.floor(x), math.floor(y)
p1 = (t_left_x+1 - x)*img_arr[t_left_x, t_left_y, c] + (x - t_left_x)*img_arr[t_left_x+1, t_left_y, c]
p2 = (t_left_x+1 - x)*img_arr[t_left_x, t_left_y+1, c] + (x - t_left_x)*img_arr[t_left_x+1, t_left_y+1, c]
v = (t_left_y+1 - y)*p1 + (y - t_left_y)*p2
return v
if __name__ == '__main__':
start = datetime.now()
resized_img = [cal(i/ratio_x, j/ratio_y, c) for i in range(target_size[0]) for j in range(target_size[1]) for c in range(target_size[2])]
resized_img = np.array(resized_img).reshape((target_size[0], target_size[1], target_size[2]))
end = datetime.now()
seconds = (end-start).seconds
print('process cost {}s'.format(seconds))
resized_show = Image.fromarray(resized_img.astype(np.uint8))
plt.imshow(resized_show)
plt.show()