Skip to content

平面物体检测

本教程的目标是学习如何使用 features2d 与 calib3d 模块来检测场景中已知的平面物体。

测试数据:使用你数据文件夹中的图像,例如 box.png 和 box_in_scene.png。

  • 创建一个新的控制台项目。读取两幅输入图像:
Mat img1 = imread(argv[1], IMREAD_GRAYSCALE);
Mat img2 = imread(argv[2], IMREAD_GRAYSCALE);
  • 在两幅图像中检测关键点,并为每个关键点计算描述子:
// detecting keypoints
Ptr<Feature2D> surf = SURF::create();
vector<KeyPoint> keypoints1;
Mat descriptors1;
surf->detectAndCompute(img1, Mat(), keypoints1, descriptors1);
... // do the same for the second image
  • 现在,在第一幅图像与第二幅图像的描述子之间寻找最近匹配:
// matching descriptors
BruteForceMatcher<L2<float> > matcher;
vector<DMatch> matches;
matcher.match(descriptors1, descriptors2, matches);
  • 可视化结果:
// drawing the results
namedWindow("matches", 1);
Mat img_matches;
drawMatches(img1, keypoints1, img2, keypoints2, matches, img_matches);
imshow("matches", img_matches);
waitKey(0);
  • 在两组点之间寻找单应性变换:
vector<Point2f> points1, points2;
// fill the arrays with the points
....
Mat H = findHomography(Mat(points1), Mat(points2), RANSAC, ransacReprojThreshold);
  • 创建一组内点匹配并绘制它们。使用 perspectiveTransform 函数通过单应性矩阵映射点:

    Mat points1Projected; perspectiveTransform(Mat(points1), points1Projected, H);

  • 使用 drawMatches 绘制内点。