- 最常见四种插值算法
INTER_NEAREST = 0 # 最近邻插值
INTER_LINEAR = 1 # 双线性插值
INTER_CUBIC = 2 # 双立方插值,不仅考虑周围像素点,还具有反锯齿功能
INTER_LANCZOS4 = 4 # 卢卡斯插值,本质是基于能量场的插值算法
- 相关的应用场景:
几何变换、透视变换中插值计算新像素;
resize:如果size不为零,使用size做放缩插值,否则根据fx与fy放缩。
C++
#include<opencv2/opencv.hpp>
#include<iostream>
using namespace cv;
using namespace std;
int main(int argc, char** argv) {
Mat src = imread("D:/vcprojects/images/test.png");
if (src.empty()) {
printf("could not load image...\n");
return -1;
}
imshow("input", src);
int h = src.rows;
int w = src.cols;
float fx = 0.0, fy = 0.0;
Mat dst = Mat::zeros(src.size(), src.type());
resize(src, dst, Size(w * 2, h * 2), fx = 0, fy = 0, INTER_NEAREST);
imshow("INTER_NEAREST", dst);
resize(src, dst, Size(w * 2, h * 2), fx = 0, fy = 0, INTER_LINEAR);
imshow("INTER_LINEAR", dst);
resize(src, dst, Size(w * 2, h * 2), fx = 0, fy = 0, INTER_CUBIC);
imshow("INTER_CUBIC", dst);
resize(src, dst, Size(w * 2, h * 2), fx = 0, fy = 0, INTER_LANCZOS4);
imshow("INTER_LANCZOS4", dst);
waitKey(0);
return 0;
}
Python
import cv2 as cv
src = cv.imread("D:/vcprojects/images/test.png")
cv.namedWindow("input", cv.WINDOW_AUTOSIZE)
cv.imshow("input", src)
h, w = src.shape[:2]
print(h, w)
dst = cv.resize(src, (w*2, h*2), fx=0.75, fy=0.75, interpolation=cv.INTER_NEAREST) # size和fxfy都设置,则size生效。若size为(0,0)则fxfy生效。
cv.imshow("INTER_NEAREST", dst)
dst = cv.resize(src, (w*2, h*2), interpolation=cv.INTER_LINEAR)
cv.imshow("INTER_LINEAR", dst)
dst = cv.resize(src, (w*2, h*2), interpolation=cv.INTER_CUBIC)
cv.imshow("INTER_CUBIC", dst)
dst = cv.resize(src, (w*2, h*2), interpolation=cv.INTER_LANCZOS4)
cv.imshow("INTER_LANCZOS4", dst)
cv.warpAffine()
cv.waitKey(0)
cv.destroyAllWindows()