OpenCV实现透视变换矫正

Gita ·
更新时间:2024-09-20
· 37 次阅读

本文实例为大家分享了OpenCV实现透视变换矫正的具体代码,供大家参考,具体内容如下

演示结果参考:

功能实现:运行程序,会显示图片的尺寸,按回车键后,依次点击需矫正的图片的左上、右上、左下、右下角,并能显示其坐标,结果弹出矫正后的图片,如图上的PIC2对话框。可以继续选择图片四个点进行实验,按下字符'q'后退出。

代码如下:(注:图中的11.jpg图片自己选取放到该程序目录下。)

//使用鼠标在原图像上选取感兴趣区域 #include <opencv2/opencv.hpp> #include <iostream> #include <vector> using namespace std; using namespace cv; const int N = 400; const int M = 220; Mat img; Point p[5]; int flag = 1; int cnt = 0; static void mouse_callback(int event, int x, int y, int, void *) {     //当鼠标左键按下时,记录其坐标     if(event == EVENT_LBUTTONDOWN) {         p[cnt].x = x*1.0; p[cnt++].y = y*1.0;         cout << "p" << cnt << " is recorded at " << p[cnt-1] << endl;     }     if(cnt==4) {             cnt=0;             //变换前图像四个点             vector<Point2f>src(4);             src[0] = p[0];             src[1] = p[1];             src[2] = p[2];             src[3] = p[3];             //变换后             vector<Point2f>dst(4);             dst[0] = Point2f(0, 0);//左上             dst[1] = Point2f(N, 0);//右上             dst[2] = Point2f(0, M);//左下             dst[3] = Point2f(N, M);//右下             //获取透视变换矩阵             Mat m = getPerspectiveTransform(src, dst);             Mat res;             warpPerspective(img, res, m, Size(N, M),INTER_LINEAR);//实现图像透视变换             namedWindow("PIC2",1);             imshow("PIC2", res);             waitKey(0);         }     } int main() {     img = imread("11.jpg");     if(!img.data) {cout<<"read image file wrong!"<<endl; getchar(); return 0;}     cout << "height = " << img.size().height << ",width = " << img.size().width << endl;     getchar();     namedWindow("PIC");     imshow("PIC", img);     setMouseCallback("PIC", mouse_callback);//设置鼠标事件回调函数     while(char(waitKey(1)) != 'q') {}     return 0; }



透视变换 opencv

需要 登录 后方可回复, 如果你还没有账号请 注册新账号