何爲內插——最近鄰插值,引用自《數字圖像處理——第三版》
代碼演示
1、設置縮放倍數來放大、縮小圖像
# -*- coding: utf-8 -*-
"""
@File : 最近鄰插值.py
@Time : 2020/6/23 9:53
@Author : Dontla
@Email : [email protected]
@Software: PyCharm
"""
import cv2 as cv
import numpy as np
def nni(img, scale):
srcH, srcW, _ = img.shape
dstH, dstW = round(srcH * scale[0]), round(srcW * scale[1])
img_ = np.zeros((dstH, dstW, 3), dtype=np.uint8)
# 列外層,行內層
# for i in range(dstH - 1): # 錯了,不用減一
for i in range(dstH):
# for j in range(dstW - 1): # 錯了,不用減一
for j in range(dstW):
img_[i, j] = img[round(srcH * i / dstH), round(srcW * j / dstW)]
return img_
# 在這裏設置放大倍數(縱,橫)
scale = 0.3, 0.5
# print(type(scale)) # <class 'tuple'>
img = cv.imread('Lenna_clip.jpg')
img_ = nni(img, scale)
cv.imshow('win1', img) # 現實原圖
cv.imshow('win2', img_) # 顯示縮放後的圖
cv.waitKey(0)
運行結果:
可見圖片按照我們的要求,縱向變成了原來的0.3倍,橫向變成了原來的0.5倍
2、設置圖片最終分辨率來放大、縮小圖像
# -*- coding: utf-8 -*-
"""
@File : 最近鄰插值.py
@Time : 2020/6/23 9:53
@Author : Dontla
@Email : [email protected]
@Software: PyCharm
"""
import cv2 as cv
import numpy as np
def nni(img, resolution):
srcH, srcW, _ = img.shape
dstH, dstW = resolution
img_ = np.zeros((dstH, dstW, 3), dtype=np.uint8)
# 列外層,行內層
for i in range(dstH - 1):
for j in range(dstW - 1):
img_[i, j] = img[round(srcH * i / dstH), round(srcW * j / dstW)]
return img_
# 在這裏設置圖片最終分辨率(縱,橫)
resolution = 300, 600
# print(type(scale)) # <class 'tuple'>
img = cv.imread('Lenna_clip.jpg')
img_ = nni(img, resolution)
cv.imshow('win1', img)
cv.imshow('win2', img_)
cv.waitKey(0)
結果:
可見圖片按照我們的要求,將圖片最終分辨率縮放成了600×300
代碼中使用的源圖
參考文章1:圖像處理中的“內插”是什麼?插值、圖像內插值、圖像間插值、重取樣(用已知數據來估計未知位置的數值的處理)(最近鄰內插法、雙線性內插)
參考文章2:最近鄰插值(nearest neighbor)-----python
20200625 注意bug
注意以上代碼可能有bug,當圖片橫向或縱向放大時,使用round()函數有可能會使得靠近邊緣的像素下標越界導致報錯,如果要優化,需增加if判斷!!!!