您的位置:首页 > 运维架构

opencv透视变换

2016-05-30 19:36 429 查看
关于透视投影的几何知识,以及求解方法,可以参考
http://media.cs.tsinghua.edu.cn/~ahz/digitalimageprocess/chapter06/chapt06_ahz.htm http://blog.csdn.net/xiaowei_cqu/article/details/26471527
此外,opencv1那本书183页也有讲

这里,实现一个贴图,主要参考
http://www.cnblogs.com/tiandsp/p/4033071.html
那篇博客用的matlab,这里使用opencv2实现

原图

#include <cv.h>
#include <highgui.h>
#include <iostream>
#include <vector>
#include <fstream>

using namespace std;
using namespace cv;

Mat rawImg, dstImg,boardImg,dstboard,maskboard;
vector<Point2f>srcQuad(4);
vector<Point2f>dstQuad(4);

void on_mouse(int event, int x, int y, int flags, void *ustc)//event鼠标事件代号,x,y鼠标坐标,flags拖拽和键盘操作的代号
{
Point pt;//坐标点;
char coordinateName[16];
static int n=0;

if (event == CV_EVENT_LBUTTONDOWN)//左键按下,读取坐标,并在图像上该点处划圆
{
pt = Point(x, y);
cout << x << " " << y << endl;
dstQuad
= pt;
n++;
circle(boardImg, pt, 2, Scalar(255, 0, 0, 0), CV_FILLED, CV_AA, 0);//划圆
sprintf(coordinateName, "(%d,%d)", x, y);
putText(boardImg, coordinateName, pt, FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 0, 0, 255), 1, 8);//在窗口上显示坐标
if (n >= 4)
{
//imshow("board", boardImg);
cvDestroyAllWindows();
}
}
}
int main()
{
rawImg = imread("lena.jpg",0);//图片路径
boardImg = imread("board.jpg",0);
dstboard = boardImg.clone();
cvNamedWindow("board",0);
setMouseCallback("board",on_mouse,0);
imshow("board",boardImg);
waitKey(0);
imshow("raw", rawImg);
imshow("board", boardImg);
int imgHeigth = rawImg.rows;
int imgWidth = rawImg.cols;
int dstHeigth = boardImg.rows;
int dstWidth = boardImg.cols;
srcQuad[0] = Point2f(0,0);//左上 右上 左下 右下
srcQuad[1] = Point2f(imgWidth-1, 0);
srcQuad[2] = Point2f(0, imgHeigth - 1);
srcQuad[3] = Point2f(imgWidth - 1, imgHeigth - 1);
/*dstQuad[0] = Point2f(imgWidth*0.05, imgHeigth*0.33);
dstQuad[1] = Point2f(imgWidth*0.9, imgHeigth*0.25);
dstQuad[2] = Point2f(imgWidth*0.2, imgHeigth*0.7);
dstQuad[3] = Point2f(imgWidth*0.8, imgHeigth*0.9);*/
for (int i = 0; i < 4; i++)
cout << dstQuad[i] << endl;

Mat warpMatrix = getPerspectiveTransform(srcQuad, dstQuad);
cout << warpMatrix << endl;
warpPerspective(rawImg, dstImg, warpMatrix, Size(dstWidth, dstHeigth));

threshold(dstImg, maskboard, 0, 1, THRESH_BINARY);
cout << "begin a test of cout to file." << endl;
// 保存cout流缓冲区指针
streambuf* coutBuf = cout.rdbuf();
ofstream of("out.txt");
// 获取文件out.txt流缓冲区指针
streambuf* fileBuf = of.rdbuf();
// 设置cout流缓冲区指针为out.txt的流缓冲区指针
cout.rdbuf(fileBuf);
cout << maskboard << endl;

of.flush();
of.close();
// 恢复cout原来的流缓冲区指针
cout.rdbuf(coutBuf);
//imshow("rawboard", dstboard);
cout << "Write Personal Information over..." << endl;
for (int i = 0; i < dstHeigth - 1; i++)
for (int j = 0; j < dstWidth - 1; j++)
dstImg.at<uchar>(i, j) = dstImg.at<uchar>(i, j)*maskboard.at<uchar>(i, j)
+ dstboard.at<uchar>(i, j)*(1-maskboard.at<uchar>(i, j));
imshow("result", dstImg);
waitKey();
return 0;
}


View Code
结果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: