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 下面 ...
随机推荐
- UWP深入学习六:Build better apps: Windows 10 by 10 development series
Promotion in the Windows Store In this article, I walk through how to Give your Store listing a mak ...
- jsp_注释
jsp支持两种注释的语法操作,一种是显示注释(在客户端允许看的见),另一种是隐式注释 显示注释:<!--注释内容--> 隐式注释: 格式一://单行注释 格式二:/*多行注释*/ 格式三: ...
- 6.1-6.5关于html
网页一般是两种元素组合起来的,一种是内联元素, 也就是行内显示,加上width和height没效果.一种是区块元素,可以加上对应的width和height, 通常使用在网页的布局,最常用的就是< ...
- JBOSS通过Apache负载均衡方法二:使用mod_cluster
本文介绍使用mod_cluster组件通过apache来对JBOSS做负载均衡.基本环境为:linux RH6.3 64bit下使用jboss-eap-6.0和mod-cluster 1.2.6(集成 ...
- haskell io模块
haskell中的io模块主要是用于读写文件屏幕的,通过import IO来导入 其中有如下常用定义 data IOMode = ReadMode | WriteMode | AppendMode | ...
- AutoMapper指定列名进行映射
有了AutoMapper,就再也不用进行手工一对一的从IDataReader到实体字段的赋值.这篇博文是一个实际案例的记录. 实体类型定义如下: public class UploadImage { ...
- C语言 数组 列优先 实现
C语言数组结构列优先顺序存储的实现 (GCC编译). 从行优先转换为列优先存储方式, 与行优先相比, 不同之处在于改变了数组维界基址的先后顺序, 从而改变了映像函数常量基址. /** * @brief ...
- 学习WPF——初识依赖项属性
入门 首先创建一个依赖项属性 然后绑定父容器的DataContext到这个依赖项的实例 接着绑定子元素的属性到依赖项属性(注意Button的Content属性) 程序最终的运行结果: 说明 首先是 ...
- NBIbatis web/winform框架
Web框架 调用Bussiness和DataAccess可参考微信框架的后台. Pages/Meeting/MeetingList.aspx Pages/Meeting/MeetingEdit.asp ...
- Oracle dmp文件导入(还原)到不同的表空间和不同的用户下
------------------------------------- 从生产环境拷贝一个dmp备份文件,在另外一台电脑上搭建测试环境,用imp命令导入dmp文件时提示如下错误: 问题描述: IM ...