最近鄰內插值法

內插是使用已知數據來估計未知位置的數據的處理方法。以圖像放大爲例,將一張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()

 左側爲縮放結果,右側爲原圖像:

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章