最近邻内插值法

内插是使用已知数据来估计未知位置的数据的处理方法。以图像放大为例,将一张50X50像素的图片放大10倍到500X500。通过其缩放的比例,来获取原图中最接近的像素,并把该像素灰度赋值给新像素。

设:原图大小为n*m像素的图片,要扩展到a*b像素的图片

则纵向缩放比例为:Z_{r}=a/n,同理横向缩放比例为:Z_{l}=b/m

那么未知像素点(x,y),对应的原图像的像素点(x_{0},y_{0}),对应关系为:

                                                                          x_{0}=x * Z_{r}y_{0}=y*Z_{l}

下面使用Python实现任意RGB彩色图片,缩放到任意像素大小:

使用的图片如下:

 引用使用到的第三方库:

from PIL import Image
import matplotlib.pyplot as plt
import numpy as np

 读取图片数据并可视化:

img = Image.open('灰原.jpg')
plt.axis('off')
plt.imshow(img)
plt.show()

 将图像数据转换为numpy数组:

img_data = np.array(img)

查看图像大小和通道数:

np.shape(img_data)

 可以看到,原图片是300*533像素,RGB三通道的彩色图片

(300, 533, 3)

 定义最近邻内插值法的实现函数:

def Nearest_neighbor_interpolation(n, m, img):
    new_img = [[] for _ in range(n)]
    r = n / float(np.shape(img)[0])
    l = m / float(np.shape(img)[1])
    for i in range(n):
        for j in range(m):
            x0 = int(i / r)
            y0 = int(j / l)
            new_img[i].append(list(img[x0][y0]))
    return new_img

新图片数据暂时使用数组存储 

下面来看看结果:

调用函数,得到新图片,这里对原图片大小扩大一倍

new_img = Nearest_neighbor_interpolation(600, 1066, img_data)

 查看新图片大小:

np.shape(new_img)

大小与预期一致

(600, 1066, 3)

 将数组数据,转换为图片数据:

new_img = Image.fromarray(np.uint8(new_img))

 可视化结果:

plt.figure(figsize=(60,107))
plt.subplot(121)
plt.imshow(new_img)
plt.axis('off')
plt.subplot(122)
plt.imshow(img_data)
plt.axis('off')
plt.show()

 左侧为缩放结果,右侧为原图像:

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

猫猫虫(——)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值