演示结果参考:
功能实现:运行程序,会显示图片的尺寸,按回车键后,依次点击需矫正的图片的左上、右上、左下、右下角,结果弹出矫正后的图片,如图上的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 p1[5]; int flag = 1; int cnt = 0; static void mouse_callback(int event, int x, int y, int, void *) { //当鼠标左键按下时,记录其坐标 if(event == EVENT_LBUTTONDOWN) { p1[cnt].x = x*1.0; p1[cnt].y = y*1.0; cout << "p1 is recorded at " << p1[cnt++] << endl; } if(cnt==4) { cnt=0; //变换前图像四个点 vector<Point2f>src(4); src[0] = p1[0]; src[1] = p1[1]; src[2] = p1[2]; src[3] = p1[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; }
原文地址:https://www.cnblogs.com/GraceSkyer/p/8585105.html
时间: 2024-11-07 04:04:18