插值法的第一次都是相同的,計算新圖的坐標點對應原圖中哪個坐標點來填充,計算公式為:
srcX = dstX* (srcWidth/dstWidth)
srcY = dstY * (srcHeight/dstHeight)
srcWidth/dstWidth和srcHeight/dstHeight分別表示寬和高的放縮比。
那么問題來了,通過這個公式算出來的srcX,scrY有可能是小數,但是坐標點是不存在小數的,都是整數,得想辦法把它轉換成整數才行。
不同的插值法的區別就體現在srcX,scrY是小數時,怎么變成整數去取原圖片中的像素值。
最鄰近:看名字就很直白,四舍五入選取最接近的整數。這樣的做法就會導致像素的變化不連續,在圖像中的體現就是會有鋸齒。
雙線性插值:雙線性就是利用與坐標軸平行的兩條直線去把小數坐標分解到相鄰的四個整數坐標點的和,權重為距離。
例如P點是小數坐標,Q是相鄰的四個整數坐標
雙三次插值:與雙線性插值類似,只不過用了相鄰的16個點。但是需要注意的是,前面兩種方法能回保證兩個方向的坐標權重和為1,但是雙三次插值不能保證這點,所以又可能去出現像素值越界的情況,需要截斷。
直接看代碼,清晰明了。實驗結果圖:
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
import math
def NN_interpolation(img,dstH,dstW):
scrH,scrW,_=img.shape
retimg=np.zeros((dstH,dstW,3),dtype=np.uint8)
for i in range(dstH):
for j in range(dstW):
scrx=round((i+1)*(scrH/dstH))
scry=round((j+1)*(scrW/dstW))
retimg[i,j]=img[scrx-1,scry-1]
return retimg
def BiLinear_interpolation(img,dstH,dstW):
scrH,scrW,_=img.shape
img=np.pad(img,((0,1),(0,1),(0,0)),'constant')
retimg=np.zeros((dstH,dstW,3),dtype=np.uint8)
for i in range(dstH):
for j in range(dstW):
scrx=(i+1)*(scrH/dstH)-1
scry=(j+1)*(scrW/dstW)-1
x=math.floor(scrx)
y=math.floor(scry)
u=scrx-x
v=scry-y
retimg[i,j]=(1-u)*(1-v)*img[x,y]+u*(1-v)*img[x+1,y]+(1-u)*v*img[x,y+1]+u*v*img[x+1,y+1]
return retimg
def BiBubic(x):
x=abs(x)
if x<=1:
return 1-2*(x**2)+(x**3)
elif x<2:
return 4-8*x+5*(x**2)-(x**3)
else:
return 0
def BiCubic_interpolation(img,dstH,dstW):
scrH,scrW,_=img.shape
#img=np.pad(img,((1,3),(1,3),(0,0)),'constant')
retimg=np.zeros((dstH,dstW,3),dtype=np.uint8)
for i in range(dstH):
for j in range(dstW):
scrx=i*(scrH/dstH)
scry=j*(scrW/dstW)
x=math.floor(scrx)
y=math.floor(scry)
u=scrx-x
v=scry-y
tmp=0
for ii in range(-1,2):
for jj in range(-1,2):
if x+ii<0 or y+jj<0 or x+ii>=scrH or y+jj>=scrW:
continue
tmp+=img[x+ii,y+jj]*BiBubic(ii-u)*BiBubic(jj-v)
retimg[i,j]=np.clip(tmp,0,255)
return retimg
im_path='C:/Users/11358/Pictures/Camera Roll/1.png'
image=np.array(Image.open(im_path))
image1=NN_interpolation(image,image.shape[0]*2,image.shape[1]*2)
image1=Image.fromarray(image1.astype('uint8')).convert('RGB')
image1.save('C:/Users/11358/Pictures/Camera Roll/2.png')
image2=BiLinear_interpolation(image,image.shape[0]*2,image.shape[1]*2)
image2=Image.fromarray(image2.astype('uint8')).convert('RGB')
image2.save('C:/Users/11358/Pictures/Camera Roll/3.png')
image3=BiCubic_interpolation(image,image.shape[0]*2,image.shape[1]*2)
image3=Image.fromarray(image3.astype('uint8')).convert('RGB')
image3.save('C:/Users/11358/Pictures/Camera Roll/4.png')