数字图像处理笔记二 - 图片缩放(最近邻插值(Nearest Neighbor interpolation))

图片缩放的两种常见算法:

  1. 最近邻域内插法(Nearest Neighbor interpolation)

  2. 双向性内插法(bilinear interpolation)

本文主要讲述最近邻插值(Nearest Neighbor interpolation算法的原理以及python实现


基本原理

最简单的图像缩放算法就是最近邻插值。顾名思义,就是将目标图像各点的像素值设为源图像中与其最近的点。算法优点在与简单、速度快。

如下图所示,一个4*4的图片缩放为8*8的图片。步骤:

  1. 生成一张空白的8*8的图片,然后在缩放位置填充原始图片值(可以这么理解)

  2. 在图片的未填充区域(黑色部分),填充为原有图片最近的位置的像素值。

这里写图片描述


实现代码如下:

def nearest_neighbor_resize(img, new_w, new_h):
    # height and width of the input img
    h, w = img.shape[0], img.shape[1]
    # new image with rgb channel
    ret_img = np.zeros(shape=(new_h, new_w, 3), dtype='uint8')
    # scale factor
    s_h, s_c = (h * 1.0) / new_h, (w * 1.0) / new_w

    # insert pixel to the new img
    for i in xrange(new_h):
        for j in xrange(new_w):
            p_x = int(j * s_c)
            p_y = int(i * s_h)

            ret_img[i, j] = img[p_y, p_x]

    return ret_img

测试代码如下:

def test():
    img_path = 'F:/nearest_neighbor.jpg'
    img = cv2.imread(img_path)

    ret_img = nearest_neighbor_resize(img, 222, 220)

    cv2.imshow("source image", img)
    cv2.imshow("after bilinear image", ret_img)
    cv2.waitKey()
    cv2.destroyAllWindows()

运行结果如下:

这里写图片描述

主要参考:

http://tech-algorithm.com/articles/nearest-neighbor-image-scaling/

猜你喜欢

转载自blog.csdn.net/haluoluo211/article/details/80918147