Image interpolation - nearest neighbor interpolation

Theoretical basis

The essence of interpolation: using known data to estimate unknown position values.

Nearest neighbor interpolation: The pixel value of an unknown point is equal to the pixel value of the nearest pixel.
One-dimensional nearest neighbor interpolation

Coding implementation (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()

other

  1. Enlarging and reducing images: In addition to enlarging images, nearest neighbor interpolation can also be used to reduce images (downsampling). For specific implementation, just change times to decimals.
  2. Repair images: Nearest neighbor interpolation can also perform simple image repair, which is suitable for situations where pixels are randomly destroyed.
  3. It is easy to form color blocks after enlarging the image, which has little effect on improving the high definition of the image. (Visually there is no difference between the image enlarged by the mouse)
    Insert image description here
    The right side shows the enlargement by clicking the mouse, and the left side shows the enlargement after algorithm processing. The visual effects are almost the same.

おすすめ

転載: blog.csdn.net/2201_75691823/article/details/129625075