OpenCV】透视变换 Perspective Transformation(续)
透视变换的原理和矩阵求解请参见前一篇《透视变换 Perspective Transformation》。在OpenCV中也实现了透视变换的公式求解和变换函数。
求解变换公式的函数:
- Mat getPerspectiveTransform(const Point2f src[], const Point2f dst[])
Mat getPerspectiveTransform(const Point2f src[], const Point2f dst[])
输入原始图像和变换之后的图像的对应4个点,便可以得到变换矩阵。之后用求解得到的矩阵输入perspectiveTransform便可以对一组点进行变换:
- void perspectiveTransform(InputArray src, OutputArray dst, InputArray m)
void perspectiveTransform(InputArray src, OutputArray dst, InputArray m)
注意这里src和dst的输入并不是图像,而是图像对应的坐标。应用前一篇的例子,做个相反的变换:
- int main( )
- {
- Mat img=imread("boy.png");
- int img_height = img.rows;
- int img_width = img.cols;
- vector<Point2f> corners(4);
- corners[0] = Point2f(0,0);
- corners[1] = Point2f(img_width-1,0);
- corners[2] = Point2f(0,img_height-1);
- corners[3] = Point2f(img_width-1,img_height-1);
- vector<Point2f> corners_trans(4);
- corners_trans[0] = Point2f(150,250);
- corners_trans[1] = Point2f(771,0);
- corners_trans[2] = Point2f(0,img_height-1);
- corners_trans[3] = Point2f(650,img_height-1);
- Mat transform = getPerspectiveTransform(corners,corners_trans);
- cout<<transform<<endl;
- vector<Point2f> ponits, points_trans;
- for(int i=0;i<img_height;i++){
- for(int j=0;j<img_width;j++){
- ponits.push_back(Point2f(j,i));
- }
- }
- perspectiveTransform( ponits, points_trans, transform);
- Mat img_trans = Mat::zeros(img_height,img_width,CV_8UC3);
- int count = 0;
- for(int i=0;i<img_height;i++){
- uchar* p = img.ptr<uchar>(i);
- for(int j=0;j<img_width;j++){
- int y = points_trans[count].y;
- int x = points_trans[count].x;
- uchar* t = img_trans.ptr<uchar>(y);
- t[x*3] = p[j*3];
- t[x*3+1] = p[j*3+1];
- t[x*3+2] = p[j*3+2];
- count++;
- }
- }
- imwrite("boy_trans.png",img_trans);
- return 0;
- }
int main( )
{
Mat img=imread("boy.png");
int img_height = img.rows;
int img_width = img.cols;
vector<Point2f> corners(4);
corners[0] = Point2f(0,0);
corners[1] = Point2f(img_width-1,0);
corners[2] = Point2f(0,img_height-1);
corners[3] = Point2f(img_width-1,img_height-1);
vector<Point2f> corners_trans(4);
corners_trans[0] = Point2f(150,250);
corners_trans[1] = Point2f(771,0);
corners_trans[2] = Point2f(0,img_height-1);
corners_trans[3] = Point2f(650,img_height-1); Mat transform = getPerspectiveTransform(corners,corners_trans);
cout<<transform<<endl;
vector<Point2f> ponits, points_trans;
for(int i=0;i<img_height;i++){
for(int j=0;j<img_width;j++){
ponits.push_back(Point2f(j,i));
}
} perspectiveTransform( ponits, points_trans, transform);
Mat img_trans = Mat::zeros(img_height,img_width,CV_8UC3);
int count = 0;
for(int i=0;i<img_height;i++){
uchar* p = img.ptr<uchar>(i);
for(int j=0;j<img_width;j++){
int y = points_trans[count].y;
int x = points_trans[count].x;
uchar* t = img_trans.ptr<uchar>(y);
t[x*3] = p[j*3];
t[x*3+1] = p[j*3+1];
t[x*3+2] = p[j*3+2];
count++;
}
}
imwrite("boy_trans.png",img_trans); return 0;
}
得到变换之后的图片:
注意这种将原图变换到对应图像上的方式会有一些没有被填充的点,也就是右图中黑色的小点。解决这种问题一是用差值的方式,再一种比较简单就是不用原图的点变换后对应找新图的坐标,而是直接在新图上找反向变换原图的点。说起来有点绕口,具体见前一篇《透视变换 Perspective Transformation》的代码应该就能懂啦。
除了getPerspectiveTransform()函数,OpenCV还提供了findHomography()的函数,不是用点来找,而是直接用透视平面来找变换公式。这个函数在特征匹配的经典例子中有用到,也非常直观:
- int main( int argc, char** argv )
- {
- Mat img_object = imread( argv[1], IMREAD_GRAYSCALE );
- Mat img_scene = imread( argv[2], IMREAD_GRAYSCALE );
- if( !img_object.data || !img_scene.data )
- { std::cout<< " --(!) Error reading images " << std::endl; return -1; }
- //-- Step 1: Detect the keypoints using SURF Detector
- int minHessian = 400;
- SurfFeatureDetector detector( minHessian );
- std::vector<KeyPoint> keypoints_object, keypoints_scene;
- detector.detect( img_object, keypoints_object );
- detector.detect( img_scene, keypoints_scene );
- //-- Step 2: Calculate descriptors (feature vectors)
- SurfDescriptorExtractor extractor;
- Mat descriptors_object, descriptors_scene;
- extractor.compute( img_object, keypoints_object, descriptors_object );
- extractor.compute( img_scene, keypoints_scene, descriptors_scene );
- //-- Step 3: Matching descriptor vectors using FLANN matcher
- FlannBasedMatcher matcher;
- std::vector< DMatch > matches;
- matcher.match( descriptors_object, descriptors_scene, matches );
- double max_dist = 0; double min_dist = 100;
- //-- Quick calculation of max and min distances between keypoints
- for( int i = 0; i < descriptors_object.rows; i++ )
- { double dist = matches[i].distance;
- if( dist < min_dist ) min_dist = dist;
- if( dist > max_dist ) max_dist = dist;
- }
- printf("-- Max dist : %f \n", max_dist );
- printf("-- Min dist : %f \n", min_dist );
- //-- Draw only "good" matches (i.e. whose distance is less than 3*min_dist )
- std::vector< DMatch > good_matches;
- for( int i = 0; i < descriptors_object.rows; i++ )
- { if( matches[i].distance < 3*min_dist )
- { good_matches.push_back( matches[i]); }
- }
- Mat img_matches;
- drawMatches( img_object, keypoints_object, img_scene, keypoints_scene,
- good_matches, img_matches, Scalar::all(-1), Scalar::all(-1),
- vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS );
- //-- Localize the object from img_1 in img_2
- std::vector<Point2f> obj;
- std::vector<Point2f> scene;
- for( size_t i = 0; i < good_matches.size(); i++ )
- {
- //-- Get the keypoints from the good matches
- obj.push_back( keypoints_object[ good_matches[i].queryIdx ].pt );
- scene.push_back( keypoints_scene[ good_matches[i].trainIdx ].pt );
- }
- Mat H = findHomography( obj, scene, RANSAC );
- //-- Get the corners from the image_1 ( the object to be "detected" )
- std::vector<Point2f> obj_corners(4);
- obj_corners[0] = Point(0,0); obj_corners[1] = Point( img_object.cols, 0 );
- obj_corners[2] = Point( img_object.cols, img_object.rows ); obj_corners[3] = Point( 0, img_object.rows );
- std::vector<Point2f> scene_corners(4);
- perspectiveTransform( obj_corners, scene_corners, H);
- //-- Draw lines between the corners (the mapped object in the scene - image_2 )
- Point2f offset( (float)img_object.cols, 0);
- line( img_matches, scene_corners[0] + offset, scene_corners[1] + offset, Scalar(0, 255, 0), 4 );
- line( img_matches, scene_corners[1] + offset, scene_corners[2] + offset, Scalar( 0, 255, 0), 4 );
- line( img_matches, scene_corners[2] + offset, scene_corners[3] + offset, Scalar( 0, 255, 0), 4 );
- line( img_matches, scene_corners[3] + offset, scene_corners[0] + offset, Scalar( 0, 255, 0), 4 );
- //-- Show detected matches
- imshow( "Good Matches & Object detection", img_matches );
- waitKey(0);
- return 0;
- }
int main( int argc, char** argv )
{
Mat img_object = imread( argv[1], IMREAD_GRAYSCALE );
Mat img_scene = imread( argv[2], IMREAD_GRAYSCALE );
if( !img_object.data || !img_scene.data )
{ std::cout<< " --(!) Error reading images " << std::endl; return -1; } //-- Step 1: Detect the keypoints using SURF Detector
int minHessian = 400;
SurfFeatureDetector detector( minHessian );
std::vector<KeyPoint> keypoints_object, keypoints_scene;
detector.detect( img_object, keypoints_object );
detector.detect( img_scene, keypoints_scene ); //-- Step 2: Calculate descriptors (feature vectors)
SurfDescriptorExtractor extractor;
Mat descriptors_object, descriptors_scene;
extractor.compute( img_object, keypoints_object, descriptors_object );
extractor.compute( img_scene, keypoints_scene, descriptors_scene ); //-- Step 3: Matching descriptor vectors using FLANN matcher
FlannBasedMatcher matcher;
std::vector< DMatch > matches;
matcher.match( descriptors_object, descriptors_scene, matches );
double max_dist = 0; double min_dist = 100; //-- Quick calculation of max and min distances between keypoints
for( int i = 0; i < descriptors_object.rows; i++ )
{ double dist = matches[i].distance;
if( dist < min_dist ) min_dist = dist;
if( dist > max_dist ) max_dist = dist;
} printf("-- Max dist : %f \n", max_dist );
printf("-- Min dist : %f \n", min_dist ); //-- Draw only "good" matches (i.e. whose distance is less than 3*min_dist )
std::vector< DMatch > good_matches; for( int i = 0; i < descriptors_object.rows; i++ )
{ if( matches[i].distance < 3*min_dist )
{ good_matches.push_back( matches[i]); }
} Mat img_matches;
drawMatches( img_object, keypoints_object, img_scene, keypoints_scene,
good_matches, img_matches, Scalar::all(-1), Scalar::all(-1),
vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS ); //-- Localize the object from img_1 in img_2
std::vector<Point2f> obj;
std::vector<Point2f> scene; for( size_t i = 0; i < good_matches.size(); i++ )
{
//-- Get the keypoints from the good matches
obj.push_back( keypoints_object[ good_matches[i].queryIdx ].pt );
scene.push_back( keypoints_scene[ good_matches[i].trainIdx ].pt );
} Mat H = findHomography( obj, scene, RANSAC ); //-- Get the corners from the image_1 ( the object to be "detected" )
std::vector<Point2f> obj_corners(4);
obj_corners[0] = Point(0,0); obj_corners[1] = Point( img_object.cols, 0 );
obj_corners[2] = Point( img_object.cols, img_object.rows ); obj_corners[3] = Point( 0, img_object.rows );
std::vector<Point2f> scene_corners(4);
perspectiveTransform( obj_corners, scene_corners, H);
//-- Draw lines between the corners (the mapped object in the scene - image_2 )
Point2f offset( (float)img_object.cols, 0);
line( img_matches, scene_corners[0] + offset, scene_corners[1] + offset, Scalar(0, 255, 0), 4 );
line( img_matches, scene_corners[1] + offset, scene_corners[2] + offset, Scalar( 0, 255, 0), 4 );
line( img_matches, scene_corners[2] + offset, scene_corners[3] + offset, Scalar( 0, 255, 0), 4 );
line( img_matches, scene_corners[3] + offset, scene_corners[0] + offset, Scalar( 0, 255, 0), 4 ); //-- Show detected matches
imshow( "Good Matches & Object detection", img_matches );
waitKey(0);
return 0;
}
代码运行效果:
findHomography()函数直接通过两个平面上相匹配的特征点求出变换公式,之后代码又对原图的四个边缘点进行变换,在右图上画出对应的矩形。这个图也很好地解释了所谓透视变换的“Viewing
Plane”。
OpenCV】透视变换 Perspective Transformation(续)的更多相关文章
- OpenCV Intro - Perspective Transform
透视变换(Perspective Transformation)是将图片投影到一个新的视平面(Viewing Plane),也称作投影映射(Projective Mapping).通用的变换公式为: ...
- 对倾斜的图像进行修正——基于opencv 透视变换
这篇文章主要解决这样一个问题: 有一张倾斜了的图片(当然是在Z轴上也有倾斜,不然直接旋转得了o(╯□╰)o),如何尽量将它纠正到端正的状态. 而要解决这样一个问题,可以用到透视变换. 关于透视变换的原 ...
- OpenCV 透视变换实例
参考文献: http://www.cnblogs.com/self-control/archive/2013/01/18/2867022.html http://opencv-code.com/tut ...
- OpenCV-paper detection & perspective transformation 相关资料
经过一段时间的搜索,决定把搜过的资料都汇集在此,以免重复劳动,几乎来自stackoverflow OpenCV C++/Obj-C: Detecting a sheet of paper / Squa ...
- Java基于opencv—透视变换矫正图像
很多时候我们拍摄的照片都会产生一点畸变的,就像下面的这张图 虽然不是很明显,但还是有一点畸变的,而我们要做的就是把它变成下面的这张图 效果看起来并不是很好,主要是四个顶点找的不准确,会有一些偏差,而且 ...
- opencv透视变换GetPerspectiveTransform的总结
对于透视变换,必须为map_matrix分配一个3x3数组,除了3x3矩阵和三个控点变为四个控点外,透视变化在其他方面与仿射变换完全类似.具体可以参考:点击打开链接 主要用到两个函数WarpPersp ...
- opencv透视变换
关于透视投影的几何知识,以及求解方法,可以参考 http://media.cs.tsinghua.edu.cn/~ahz/digitalimageprocess/chapter06/chapt06_a ...
- cv2.getPerspectiveTransform 透视变换
简介 透视变换(Perspective Transformation)是将成像投影到一个新的视平面(Viewing Plane),也称作投影映射(Projective Mapping).如图1,通过透 ...
- 深入学习OpenCV文档扫描及OCR识别(文档扫描,图像矫正,透视变换,OCR识别)
如果需要处理的原图及代码,请移步小编的GitHub地址 传送门:请点击我 如果点击有误:https://github.com/LeBron-Jian/ComputerVisionPractice 下面 ...
随机推荐
- 用Fragment制作的Tab页面产生的UI重叠问题
本文出处:http://blog.csdn.net/twilight041132/article/details/43812745 在用Fragment做Tab页面,发现有时候进入应用会同时显示多个T ...
- Node.js-提供了四种形式的定时器
Node.js提供了四种形式的定时器 global.setTimeout(); //一次性定时器 global.setInterval(); //周期性定时器 global.nextTick(); / ...
- 纯css径向渐变(CSS3--Gradient)
渐变 一.CSS3的径向渐变 效果图网址:http://www.spritecow.com 图像拼接技术 CSS3 Gradient分为linear-gradient(线性渐变)和radial-gra ...
- umask函数
umask函数为进程设置文件模式创建屏蔽字,并返回以前的值. #include <sys/stat.h> mode_t umask( mode_t cmask); 返回值:以前的文件模式创 ...
- 使用MyBatis Generator自动创建代码
SSM框架--使用MyBatis Generator自动创建代码 1. 目录说明 使用自动生成有很多方式,可以在eclipse中安装插件,但是以下将要介绍的这种方式我认为很轻松,最简单,不需要装插件, ...
- 对IEnumerable<T>和IQueryable<T>的一点见解
今天学习了用EF模型做查询,感觉数据库上下文对象的扩展方法很强大,所以研究了一下where的实现原理,其中遇到了一个问题,就是关于IEnumerable和IQueryable的区别,所以查了查资料,这 ...
- PHP程序员的技术成长规划(转)
第一阶段:基础阶段(基础PHP程序员) 重点:把LNMP搞熟练(核心是安装配置基本操作) 目标:能够完成基本的LNMP系统安装,简单配置维护:能够做基本的简单系统的PHP开发:能够在PHP中型系统中支 ...
- 使用 Python 进行稳定可靠的文件操作
程序需要更新文件.虽然大部分程序员知道在执行I/O的时候会发生不可预期的事情,但是我经常看到一些异常幼稚的代码.在本文中,我想要分享一些如何在Python代码中改善I/O可靠性的见解. 考虑下述Pyt ...
- jQuery document window load ready 区别详解
用过JavaScript的童鞋,应该知道window对象和document对象,也应该听说过load事件和ready事件,小菜当然也知道,而且自认为很了解,直到最近出了问题,才知道事情并不是那么简单. ...
- 拉勾网ThoughtWorks面试题代码实现
今天看到一个很有意思的面试活动(活动链接),不需要简历,只有一道编程题目,在线提交你的代码即可. 本菜鸟对面试不感兴趣,但题目让我很兴奋,特来挑战一下~ 或许当你看到这篇博文的时候活动已经失效了,所以 ...