图像处理导论作业2——图片放大
瞎写的,写的比较烂,且健壮性不好
并不能适用于各种情况,完成作业而已
from PIL import Image
import numpy as np
def read_img(imgfile):
img = Image.open(imgfile)
return img
img = read_img('hj.jpeg')
1. 最近邻域插值
def resize1(img,n):
arr = np.array(img)
nline = n*arr.shape[0]
nrow = n*arr.shape[1]
newarr = np.zeros([nline,nrow,3],np.uint8)
for i in range(nline):
for j in range(nrow):
newarr[i][j] = arr[i//n][j//n]
newimg = Image.fromarray(newarr)
return newimg
2. 双线性插值
def resize2(img, n):
arr = np.array(img)
nline = n*arr.shape[0]
nrow = n*arr.shape[1]
newarr = np.zeros([nline,nrow,3],np.uint8)
fl = float(arr.shape[0]-1)/float(nline-1)
fr = float(arr.shape[1]-1)/float(nrow-1)
for i in range(nline):
for j in range(nrow):
x0 = i * fl
y0 = j * fr
x1, y1 = int(x0), int(y0)
x2 = arr.shape[0]-1 if x1+1 >= arr.shape[0] else x1+1
y2 = arr.shape[1]-1 if y1+1 >= arr.shape[1] else y1+1
fx1, fy1 = x0 - x1, y0 - y1
fx2, fy2 = 1 - fx1, 1 - fy1
v = [0,0,0]
for k in range(3):
v[k] = arr[x2,y2][k]*fx1*fy1+arr[x1,y2][k]*fx2*fy1+arr[x1,y1][k]*fx2*fy2+arr[x2,y1][k]*fx1*fy2
newarr[i][j] = v
newimg = Image.fromarray(newarr)
return newimg
3. 结果比较
img1 = resize1(img, 4)
img2 = resize2(img, 4)
img3 = img.resize([4*img.size[0], 4*img.size[1]],Image.ANTIALIAS)
img # 原图
img1 # 最近邻域插值
img2 # 双线性插值
img3 # PIL自带算法
#(滑稽)
EOF