思路
鼠标拾取图像四个角点,然后定义透视变换后图像尺寸,得到透视变换后图像。
源码
//********************************************************************************
//
// 透视变换
//
//********************************************************************************
#include<opencv2/opencv.hpp>
#include<iostream>
//变换后尺寸
#define HANG 600
#define LIE 600
using namespace cv;
using namespace std;
Mat src, resultImg;
vector<Point2f> src_corner;
void tou_shi();
void on_Mouse(int event, int x, int y, int flags, void* param);
int main()
{
src = imread("1.png");
if (src.empty())
{
cout << "图像未找到" << endl;
return -1;
}
imshow("yuan_image", src);
setMouseCallback("yuan_image", on_Mouse);//窗口名必须和之前创建窗口同名
waitKey(0);
return 0;
}
void on_Mouse(int event, int x, int y, int flags, void* param)
{
if (event == CV_EVENT_LBUTTONDOWN)//鼠标点击将会触发此事件
{
cout << "x:" << x << "y:" << y << endl;
Point2f thispoint;
thispoint.x = x;
thispoint.y = y;
src_corner.push_back(thispoint);
}
if (src_corner.size() == 4)
tou_shi();
}
//透视变换
void tou_shi()
{
//透视变换后的四个点所在坐标
vector<Point2f> dst_corner(4);
dst_corner[0] = Point(0, 0);
dst_corner[1] = Point(HANG, 0);
dst_corner[2] = Point(HANG, LIE);
dst_corner[3] = Point(0, LIE);
Mat M = getPerspectiveTransform(src_corner, dst_corner); //求变换矩阵
warpPerspective(src, resultImg, M, cv::Size(HANG,LIE), INTER_LINEAR);//透视
imshow("result_image", resultImg);
imwrite("tou_shi.png ", resultImg);
}
|