插值的本质:利用已知数据估计未知位置数值。
# coding=utf-8
import cv2
import numpy as np
def Nearest(img, up_height, up_width, channels):
nearest_img = np.zeros(shape=(up_height, up_width, channels), dtype=np.uint8)
img_height, img_width, img_channels = img.shape
for i in range(up_height):
for j in range(up_width):
row = int(i * img_height/up_height + 0.5)
col = int(j * img_width/up_width + 0.5)
if row == img_height: row -= 1
if col == img_width: col -= 1
nearest_img[i][j] = img[row][col]
return nearest_img
if __name__ == "__main__":
# 无法处理透明度通道(压根就没读进来)
img_source = cv2.imread(r"Image_restoration\source\1.png")
img_height, img_width, img_channels = img_source.shape
print("height {}, width {}, channels {}".format( img_height, img_width, img_channels))
times = 3 # 放大3倍
up_height = int(img_height * times)
up_width = int(img_width * times)
print("up_height {}, up_width {}".format(up_height, up_width))
nearest_img = Nearest(img_source, up_height, up_width, img_channels)
cv2.imshow("img_source", img_source)
cv2.imshow("nearest_img", nearest_img)
cv2.imwrite(r"Image_restoration\result\1_nearest.png", nearest_img)
cv2.waitKey(0)
cv2.destroyAllWindows()