本文实例为大家分享了OpenCV实现透视变换矫正的具体代码,供大家参考,具体内容如下
演示结果参考:
功能实现:运行程序,会显示图片的尺寸,按回车键后,依次点击需矫正的图片的左上、右上、左下、右下角,并能显示其坐标,结果弹出矫正后的图片,如图上的PIC2对话框。可以继续选择图片四个点进行实验,按下字符'q'后退出。
代码如下:(注:图中的11.jpg图片自己选取放到该程序目录下。)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
|
//使用鼠标在原图像上选取感兴趣区域 #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; } |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://www.cnblogs.com/GraceSkyer/p/8585105.html