slam14讲-pa4-图像去畸变
前言
在做一道图像去畸变的习题时,发现题目有些问题,修改后解决了问题
这里x,y应该为去畸变前图片相机坐标,x_undistorted = x…,y_undistortted =y…为去畸变之后的相机坐标,且均为归一化坐标。
下面开始做题,主要注意从图像中直接获取的是像素坐标,要先将像素坐标转化为相机坐标,(区分像素坐标,物理成像坐标,相机坐标,世界坐标)利用给定多项式矫正相机坐标,再转化为像素坐标。
具体实现过程
#include <opencv2/opencv.hpp>
#include <string>
#include <math.h>
using namespace std;
string image_file = "../test.png";
int main(int argc, char **argv) {
double k1 = -0.28340811, k2 = 0.07395907, p1 = 0.00019359, p2 = 1.76187114e-05;
double fx = 458.654, fy = 457.296, cx = 367.215, cy = 248.375;
cv::Mat image = cv::imread(image_file,0);
int rows = image.rows, cols = image.cols;
cv::Mat image_undistort = cv::Mat(rows, cols, CV_8UC1);
double u_distorted = 0, v_distorted = 0;
double x_distorted = 0, y_distorted = 0;
double u_undistorted = 0, v_undistorted = 0;
double x_undistorted = 0, y_undistorted = 0;
double r = 0;
for (int v = 0; v < rows; v++)
for (int u = 0; u < cols; u++) {
x_distorted = (u - cx)/fx;
y_distorted = (v - cy)/fy;
r= sqrt(pow(x_distorted,2) + pow(y_distorted,2));
x_undistorted = x_distorted*(1+k1*pow(r,2)+k2* pow(r,4))+2*p1*x_distorted*y_distorted+p2*(pow(r,2)+2* pow(x_distorted,2));
y_undistorted = y_distorted*(1+k1*pow(r,2)+k2* pow(r,4))+2*p2*x_distorted*y_distorted+p1*(pow(r,2)+2* pow(y_distorted,2));
u_undistorted = fx*x_undistorted+cx;
v_undistorted = fy*y_undistorted+cy;
if (u_undistorted >= 0 && v_undistorted >= 0 && u_undistorted < cols && v_undistorted < rows) {
image_undistort.at<uchar>(v, u) = image.at<uchar>((int) v_undistorted, (int) u_undistorted);
} else {
image_undistort.at<uchar>(v, u) = 0;
}
}
cv::imshow("image distorted", image);
cv::imshow("image undistorted", image_undistort);
cv::waitKey();
return 0;
}