原理介绍参见:
一个
二个
import numpy as np
import cv2
import math
def nearest(im,dst_size):
'''
最近邻插值(适用于灰度图)
:param im: 输入图像
:param 输出图像的尺寸(h, w, c)
:return: 缩放后的图像
'''
dst = np.zeros(dst_size)
dst_h = dst_size[0]
dst_w = dst_size[1]
sf_h = im.shape[0]/dst_size[0]
sf_w = im.shape[1]/dst_size[1]
for i in range(dst_h):
for j in range(dst_w):
src_i = int(sf_h*i)
src_j = int(sf_w*j)
dst[i,j] = im[src_i,src_j]
return dst
def double_linear(im,dst_size):
'''
双线性插值(适用于灰度图)
:param im: 输入图像
:param 输出图像的尺寸(h, w, c)
:return: 缩放后的图像
'''
dst = np.zeros(dst_size)
dst_h = dst_size[0]
dst_w = dst_size[1]
sf_h = im.shape[0]/dst_size[0]
sf_w = im.shape[1]/dst_size[1]
for i in range(dst_h):
for j in range(dst_w):
src_i = sf_h*i
src_j = sf_w*j
x1 = math.floor(src_i)
y1 = math.floor(src_j)
u = src_i-x1
v = src_j-y1
x2 = x1+1
y2 = y1
x3 = x1
y3 = y1+1
x4 = x1+1
y4 = y1+1
if x1+1>=im.shape[0]:
x4 = im.shape[0] - 1
x2 = x4
x1 = x4 - 1
x3 = x4 - 1
if y1+1>=im.shape[1]:
y4 = im.shape[1] - 1
y3 = y4
y1 = y4 - 1
y2 = y4 - 1
dst[i, j] = (1 - u) * (1 - v) * im[x1, y1] + (1 - u) * v * im[x2, y2] + u * (1 - v) * im[x3, y3] + u * v * im[x4, y4]
return dst
def Bicubic_Bell( num ):
if -1.5 <= num <= -0.5:
return -0.5 * ( num + 1.5) ** 2
if -0.5 < num <= 0.5:
return 3/4 - num ** 2
if 0.5 < num <= 1.5:
return 0.5 * ( num - 1.5 ) ** 2
else:
return 0
def Bicubic(img, bigger_height, bigger_width, channels):
'''
最三次插值(适用于灰度图)
:param img: 输入图像
:param bigger_height:输出图像的h
: bigger_width:输出图像的w
: channel: 输出图像的c
:return: 缩放后的图像
'''
Bicubic_img = np.zeros(shape=(bigger_height, bigger_width, channels), dtype=np.uint8)
for i in range(0, bigger_height):
for j in range(0, bigger_width):
row = (i / bigger_height) * img.shape[0]
col = (j / bigger_width) * img.shape[1]
row_int = int(row)
col_int = int(col)
u = row - row_int
v = col - col_int
tmp = 0
for m in range(-1, 3):
for n in range(-1, 3):
if (row_int + m) < 0 or (col_int + n) < 0 or (row_int + m) >= img.shape[0] or (col_int + n) >= \
img.shape[1]:
row_int = img.shape[0] - 1 - m
col_int = img.shape[1] - 1 - n
numm = img[row_int + m][col_int + n] * Bicubic_Bell(m - u) * Bicubic_Bell(n - v)
tmp += np.abs(np.trunc(numm))
Bicubic_img[i][j] = tmp
return Bicubic_img
if __name__=='__main__':
im = cv2.imread(r'E:\\1.png')
cv2.imshow('Image',im)
cv2.waitKey(0)
res = Bicubic(im, 300, 300, 3)
cv2.imshow('Image', np.uint8(res))
cv2.waitKey(0)