1.最近邻插值
import cv2
import numpy as np
import time
from traitlets.config.application import catch_config_error
def function(img,dstHeight,dstWidth):
height,width,channels =img.shape
emptyImage=np.zeros((dstHeight,dstWidth,channels),np.uint8)
sh=dstHeight/height
sw=dstWidth/width
for i in range(dstHeight):
for j in range(dstWidth):
x=min(round(i/sh), height-1)
y=min(round(j/sw), width-1)
emptyImage[i,j]=img[x,y]
return emptyImage
if __name__ == '__main__':
img_in = cv2.imread('1.jpg')
start = time.time()
dstHeight=200
dstWidth=200
img_out=function(img_in,dstHeight,dstWidth)
print ('cost %f seconds' % (time.time() - start))
cv2.imshow('src_image', img_in)
cv2.imshow('dst_image', img_out)
cv2.waitKey()
2.双线性插值
# coding=utf-8
import cv2
import numpy as np
import time
def resize(src, new_size):
dst_w, dst_h = new_size # 目标图像宽高
src_h, src_w = src.shape[:2] # 源图像宽高
if src_h == dst_h and src_w == dst_w:
return src.copy()
scale_x = float(src_w) / dst_w # x缩放比例
scale_y = float(src_h) / dst_h # y缩放比例
# 遍历目标图像,插值
dst = np.zeros((dst_h, dst_w, 3), dtype=np.uint8)
for n in range(3): # 对channel循环
for dst_y in range(dst_h): # 对height循环
for dst_x in range(dst_w): # 对width循环
# 目标在源上的座标
src_x = (dst_x + 0.5) * scale_x - 0.5 #定位像素点:中心对齐
src_y = (dst_y + 0.5) * scale_y - 0.5
# 计算在源图上四个近邻点的位置
src_x_0 = int(np.floor(src_x))
src_y_0 = int(np.floor(src_y))
src_x_1 = min(src_x_0 + 1, src_w - 1)
src_y_1 = min(src_y_0 + 1, src_h - 1)
# 双线性插值
# 设(x,y)为插值点在源图像的座标,待计算插值为z
# 首先x方向上插值:相邻两点为(x0,y0)、(x1,y0),像素值分别为z0=f(x0,y0)、z1=f(x1,y0),从而有公式:z−z0x−x0=z1−z0x1−x0,从而插值z=x1−xx1−x0z0+x−x0x1−x0z1
#
# 然后y方向上插值:以上得到的上方插值z
# 记为ztop,同理可得下方插值为zbot,那么最后插值为:Z=y1−yy1−y0ztop+y−y0y1−y0zbot
value0 = (src_x_1 - src_x) * src[src_y_0, src_x_0, n] + (src_x - src_x_0) * src[src_y_0, src_x_1, n]
value1 = (src_x_1 - src_x) * src[src_y_1, src_x_0, n] + (src_x - src_x_0) * src[src_y_1, src_x_1, n]
dst[dst_y, dst_x, n] = int((src_y_1 - src_y) * value0 + (src_y - src_y_0) * value1)
return dst
if __name__ == '__main__':
img_in = cv2.imread('1.jpg')
start = time.time()
img_out = cv2.resize(img_in, (600,600))
print ('cost %f seconds' % (time.time() - start))
cv2.imshow('src_image', img_in)
cv2.imshow('dst_image', img_out)
cv2.waitKey()
相关博客:
https://blog.csdn.net/smf0504/article/details/51303962
https://blog.csdn.net/xbinworld/article/details/65660665
https://blog.csdn.net/qq_29058565/article/details/52769497