# @Time : 2023/8/15 19:03
# @Author : zp
# 参考书-----数字图像处理(第三版-冈萨雷斯)
# 图像缩放(最近邻插值,双线性插值,双三次插值)
import numpy as np
from matplotlib import pyplot as plt
from PIL import Image
plt.rcParams['font.sans-serif'] = ['FangSong'] # 设置字体以便正确显示中文
def resize(img, size, method=None):
"""
自己实现图像缩放函数(默认使用bilinear)
:param img: 待缩放的图像
:param size: 缩放后图像的尺寸 (width, height)
:param method: 缩放的方法 ("nearest", "bilinear", "bicubic")
:return: 已缩放的图像
"""
if method is None:
method = "bilinear"
old_h, old_w, depth = img.shape
new_h, new_w = size
r_img = np.zeros((new_h, new_w, depth), dtype=img.dtype)
# scale_h = min(old_h / new_h, new_h / old_h)
# scale_w = min(old_w / new_w, new_w / old_w)
scale_h = old_h / new_h
scale_w = old_w / new_w
if method == "nearest":
for i in range(new_h-1):
for j in range(new_w-1):
x = round(i*scale_h)
y = round(j*scale_w)
r_img[i, j] = img[x, y]
return r_img
elif method == "bilinear":
for i in range(new_h):
for j in range(new_w):
x = i*scale_h
y = j*scale_w
x1 = int(x)
y1 = int(y)
x2 = min(x1+1, old_h-1)
y2 = min(y1+1, old_w-1)
r_img[i, j] = ((x2-x)*(y2-y)*img[x1, y1] + (x-x1)*(y2-y)*img[x2, y1] +
(x2-x)*(y-y1)*img[x1, y2] + (x-x1)*(y-y1)*img[x2, y2])
return r_img
elif method == "bicubic":
# 暂时不写
return 0
img0 = np.asarray(Image.open('lena.jpg')) # PIL库读取图片,并转换为ndarray格式
h, w, _ = img0.shape
img1 = resize(img0, (int(h*2), int(w*2)), method='nearest')
img2 = resize(img0, (int(h*2), int(w*2)), method='bilinear')
plt.subplot(131)
plt.title('原图')
plt.imshow(img0)
plt.subplot(132)
plt.title('最近邻插值')
plt.imshow(img1)
plt.subplot(133)
plt.title('双线性插值')
plt.imshow(img2)
plt.show()