本文主要是介绍双线性插值理解与Python实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
双线性插值
公式就是这么推来的,主要就是在x方向和y方向上都进行线性插值,利用临近点进行计算
在计算的时候利用了几何中心对齐来优化原来的直接缩放
__author__ = 'Alex Wang'import cv2
import time
from math import ceil, floor
import numpy as np'''
python implementation of bilinear interpolation
'''def bilinear_interpolation(img, out_dim):src_h, src_w, channel = img.shapedst_h, dst_w = out_dim[1], out_dim[0]if src_h == dst_h and src_w == dst_w:return img.copy()dst_img = np.zeros((dst_h, dst_w, channel), dtype=np.uint8)scale_x, scale_y = float(src_w) / dst_w, float(src_h) / dst_hfor i in range(channel):for dst_y in range(dst_h):for dst_x in range(dst_w):# find the origin x and y coordinates of dst image x and y# use geometric center symmetry# if use direct way, src_x = dst_x * scale_xsrc_x = (dst_x + 0.5) * scale_x - 0.5src_y = (dst_y + 0.5) * scale_y - 0.5# find the coordinates of the points which will be used to compute the interpolationsrc_x0 = int(floor(src_x))src_x1 = min(src_x0 + 1, src_w - 1)src_y0 = int(floor(src_y))src_y1 = min(src_y0 + 1, src_h - 1)if src_x0 != src_x1 and src_y1 != src_y0:# calculate the interpolationtemp0 = ((src_x1 - src_x) * img[src_y0, src_x0,i] + (src_x - src_x0) * img[src_y0, src_x1, i]) / (src_x1 - src_x0)temp1 = (src_x1 - src_x) * img[src_y1, src_x0,i] + (src_x - src_x0) * img[src_y1, src_x1, i] / (src_x1 - src_x0)dst_img[dst_y, dst_x, i] = int((src_y1 - src_y) * temp0 + (src_y - src_y0) * temp1) / (src_y1 - src_y0)return dst_imgif __name__ == '__main__':img = cv2.imread('bounding_box_and_polygon.png')start = time.time()dst = bilinear_interpolation(img, (1000, 1000))print('cost {} seconds'.format(time.time() - start))cv2.imshow('result', dst)cv2.waitKey()
References:
https://blog.csdn.net/xbinworld/article/details/65660665
https://blog.csdn.net/wudi_X/article/details/79782832
https://en.wikipedia.org/wiki/Bilinear_interpolation
这篇关于双线性插值理解与Python实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!