【OpenCV】透视变换 Perspective Transformation(续)(2)

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;
}

代码运行效果:

【OpenCV】透视变换 Perspective Transformation(续)

findHomography()函数直接通过两个平面上相匹配的特征点求出变换公式,之后代码又对原图的四个边缘点进行变换,在右图上画出对应的矩形。这个图也很好地解释了所谓透视变换的“Viewing Plane”。

--------------------------------------分割线 --------------------------------------

Ubuntu Linux下安装OpenCV2.4.1所需包

Ubuntu 12.04 安装 OpenCV2.4.2

CentOS下OpenCV无法读取视频文件

Ubuntu 12.04下安装OpenCV 2.4.5总结

Ubuntu 10.04中安装OpenCv2.1九步曲

基于QT和OpenCV的人脸识别系统

[翻译]Ubuntu 14.04, 13.10 下安装 OpenCV 2.4.9 

--------------------------------------分割线 --------------------------------------

OpenCV的详细介绍请点这里
OpenCV的下载地址请点这里

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/147920e8a43c71f8d936358d264bd732.html