OpenCV實(shí)現(xiàn)透視變換矯正
本文實(shí)例為大家分享了OpenCV實(shí)現(xiàn)透視變換矯正的具體代碼,供大家參考,具體內(nèi)容如下
演示結(jié)果參考:

功能實(shí)現(xiàn):運(yùn)行程序,會顯示圖片的尺寸,按回車鍵后,依次點(diǎn)擊需矯正的圖片的左上、右上、左下、右下角,并能顯示其坐標(biāo),結(jié)果彈出矯正后的圖片,如圖上的PIC2對話框??梢岳^續(xù)選擇圖片四個點(diǎn)進(jìn)行實(shí)驗(yàn),按下字符'q'后退出。
代碼如下:(注:圖中的11.jpg圖片自己選取放到該程序目錄下。)
//使用鼠標(biāo)在原圖像上選取感興趣區(qū)域
#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 *) {
? ? //當(dāng)鼠標(biāo)左鍵按下時,記錄其坐標(biāo)
? ? 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;
? ? ? ? ? ? //變換前圖像四個點(diǎn)
? ? ? ? ? ? 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);//實(shí)現(xiàn)圖像透視變換
? ? ? ? ? ? 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);//設(shè)置鼠標(biāo)事件回調(diào)函數(shù)
? ??
? ? while(char(waitKey(1)) != 'q') {}
? ? return 0;
}以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C++實(shí)現(xiàn)LeetCode(36.驗(yàn)證數(shù)獨(dú))
這篇文章主要介紹了C++實(shí)現(xiàn)LeetCode(36.驗(yàn)證數(shù)獨(dú)),本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-07-07
Visual Studio2000系列版本安裝OpenGL的圖文教程
這篇文章主要介紹了Visual Studio2000系列版本安裝OpenGL的圖文教程,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-04-04
C++實(shí)現(xiàn)LeetCode(131.拆分回文串)
這篇文章主要介紹了C++實(shí)現(xiàn)LeetCode(131.拆分回文串),本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-07-07

