1. 程式人生 > >【OpenCV】透視變換矯正

【OpenCV】透視變換矯正

file info 事件 ima 變換 data include imshow spec

演示結果參考技術分享圖片

功能實現:運行程序,會顯示圖片的尺寸,按回車鍵後,依次點擊需矯正的圖片的左上、右上、左下、右下角,結果彈出矯正後的圖片,如圖上的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; }

【OpenCV】透視變換矯正