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

我会带着你远行 2022-05-21 09:52 232阅读 0赞

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

  1. 最近邻域内插法(Nearest Neighbor interpolation)
  2. 双向性内插法(bilinear interpolation)

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


基本原理

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

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

  1. 生成一张空白的8*8的图片,然后在缩放位置填充原始图片值(可以这么理解)
  2. 在图片的未填充区域(黑色部分),填充为原有图片最近的位置的像素值。

这里写图片描述


实现代码如下:

  1. def nearest_neighbor_resize(img, new_w, new_h):
  2. # height and width of the input img
  3. h, w = img.shape[0], img.shape[1]
  4. # new image with rgb channel
  5. ret_img = np.zeros(shape=(new_h, new_w, 3), dtype='uint8')
  6. # scale factor
  7. s_h, s_c = (h * 1.0) / new_h, (w * 1.0) / new_w
  8. # insert pixel to the new img
  9. for i in xrange(new_h):
  10. for j in xrange(new_w):
  11. p_x = int(j * s_c)
  12. p_y = int(i * s_h)
  13. ret_img[i, j] = img[p_y, p_x]
  14. return ret_img

测试代码如下:

  1. def test():
  2. img_path = 'F:/nearest_neighbor.jpg'
  3. img = cv2.imread(img_path)
  4. ret_img = nearest_neighbor_resize(img, 222, 220)
  5. cv2.imshow("source image", img)
  6. cv2.imshow("after bilinear image", ret_img)
  7. cv2.waitKey()
  8. cv2.destroyAllWindows()

运行结果如下:

这里写图片描述

主要参考:

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

发表评论

表情:
评论列表 (有 0 条评论,232人围观)

还没有评论,来说两句吧...

相关阅读