版权声明:本文为博主原创文章,未经博主允许不得转载。 https://cloud.tencent.com/developer/article/1338324
图片缩放的两种常见算法:
本文主要讲述最近邻插值(Nearest Neighbor interpolation
算法的原理以及python实现
最简单的图像缩放算法就是最近邻插值。顾名思义,就是将目标图像各点的像素值设为源图像中与其最近的点。算法优点在与简单、速度快。
如下图所示,一个4*4的图片缩放为8*8的图片。步骤:
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/