数字图像处理-插值

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值