圖片縮放的兩種常見演算法:
- 最近鄰域內插法(Nearest Neighbor interpolation)
- 雙向性內插法(bilinear interpolation)
本文主要講述最近鄰插值(Nearest Neighbor interpolation演算法的原理以及python實作
基本原理
最簡單的影像縮放演算法就是最近鄰插值,顧名思義,就是將目標影像各點的像素值設為源影像中與其最近的點,演算法優點在與簡單、速度快,
如下圖所示,一個4*4的圖片縮放為8*8的圖片,步驟:
- 生成一張空白的8*8的圖片,然后在縮放位置填充原始圖片值(可以這么理解)
- 在圖片的未填充區域(黑色部分),填充為原有圖片最近的位置的像素值,

實作代碼:
import cv2
import numpy as np
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 range(new_h):
for j in range(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
img_path = './dice.jpg'
img = cv2.imread(img_path)
#ret_img = nearest_neighbor_resize(img, 222, 220)
ret_img = nearest_neighbor_resize(img, 640, 480)
cv2.imshow("source image", img)
cv2.imshow("after bilinear image", ret_img)
cv2.waitKey()
cv2.destroyAllWindows()
將一個96*96的影像經過演算法轉換,變成了一張640*480的影像,

放大到1920*1080

縮小,從892*650->96*96

結束!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/297940.html
標籤:其他
下一篇:技術百科——中國宇翔技術作業站
