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

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

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

双向性内插法(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/

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wangchuang2017

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值