图像插值——最近邻插值

理论基础

插值的本质:利用已知数据估计未知位置数值。

最近邻插值:未知点像素值等于距离其最近的像素点的像素值。
一维最近邻插值

编码实现(Python)

# 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()

其他

  1. 放大缩小图像:除了放大图像外,最近邻插值也可以用于缩小图像(下采样),具体实现起来仅需将times变为小数即可。
  2. 修复图像:最近邻插值还可以进行简单的图像修复,适用于随机对像素点进行破坏的情况。
  3. 将图像放大后容易形成色块,对图像高清化的效果几乎没有。(视觉上与鼠标放大图像并无差异)
    在这里插入图片描述
    右侧为鼠标点击放大,左侧为算法处理后放大,视觉效果差不多。

猜你喜欢

转载自blog.csdn.net/2201_75691823/article/details/129625075
今日推荐