算法学习笔记1:畸变矫正算法
以下代码均在win10+VS2015+OpenCV4.5环境下编译
相机在进行拍照时,由于客观原因,经常会导致图片不正,图片畸形,进而影响后期图像处理的效果,因此需要对图像进行矫正处理。
以下为检测代码:
#include<opencv2/opencv.hpp>
#include<iostream>
using namespace std;
using namespace cv;
int i = 1;
struct userdata {
Mat im;
vector<Point2f> points;
};
void mouseHandle(int event, int x, int y, int flags, void* ptr)
{
if (event == EVENT_LBUTTONDOWN)
{
userdata *data = (userdata*)ptr;
circle(data->im, Point(x, y), 5, Scalar(0, 0, 255), -1);
imshow("dst", data->im);
if (data->points.size() < 4)
{
//i++;
cout << "第" << i++ << "个点坐标" << Point(x, y) << endl;
data->points.push_back(Point2f(x, y));
}
}
}
int main()
{
Mat Image = imread("输入自己的图片地址");
//Size dsize = Size(1000, 562);
Size dsize = Image.size();
Mat re_img;
resize(Image, re_img, dsize);
//imshow("Image", Image);
imshow("re_img", re_img);
//Mat result = Mat::zeros(400, 300, CV_8UC3);
//输出图像的尺寸大小
Mat result = Mat::zeros(730, 610, CV_8UC3);
//用于矩阵运算的四个点
vector<Point2f> obj;
obj.push_back(Point2f(150, 150));//原点
obj.push_back(Point2f(450, 150));
obj.push_back(Point2f(450, 550));
obj.push_back(Point2f(150, 550));
/*
* 修改#if的值切换手动抓取点或使用默认点
*/
#if 0
//将输出点写入下方方便接下来操作,
vector<Point2f> constant_data;
constant_data.push_back(Point2f(269, 285));//原点
constant_data.push_back(Point2f(458, 290));
constant_data.push_back(Point2f(457, 419));
constant_data.push_back(Point2f(287, 416));
Mat H = findHomography(constant_data, obj, RANSAC);
//应用仿射变换,可以恢复出原图
warpPerspective(re_img, result, H, result.size());
//cout << "H" << H << endl;
imshow("result", result);
#else
Mat dst = re_img.clone();
userdata data;
data.im = dst;
imshow("dst", dst);
setMouseCallback("dst", mouseHandle, &data);
waitKey(0);
//findHomography找到两个平面之间的转换矩阵
Mat H = findHomography(data.points, obj, RANSAC);
//应用仿射变换,可以恢复出原图
warpPerspective(re_img, result, H, result.size());
//cout << "H" << H << endl;
imshow("result", result);
//cv::imwrite("输入保存图片地址图片名字加格式结尾", result);
#endif // 0
waitKey(0);
}
原图
画点图,画点时顺时针画,可在打印输出窗口看到所画的每个点的坐标
结果
此矫正方式有待验证!