天天看点

OpenCV平面物体检测

平面物体检测

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

测试数据: 数据图像文件,比如 “box.png”或者“box_in_scene.png”等。

  1. 创建新的控制台(console)项目。读入两个输入图像。

    Mat img1 = imread(argv[1], CV_LOAD_IMAGE_GRAYSCALE);

    Mat img2 = imread(argv[2], CV_LOAD_IMAGE_GRAYSCALE);

  2. 检测两个图像的关键点(尺度旋转都不发生变化的关键点)。

    // 对第一幅图像进行关键点检测

    FastFeatureDetector detector(15);

    vector<KeyPoint> keypoints1;

    detector.detect(img1, keypoints1);

    ... // 对第二幅图像进行关键点检测

  3. 计算每个关键点的描述向量(Descriptor)。

    // 计算描述向量

    SurfDescriptorExtractor extractor;

    Mat descriptors1;

    extractor.compute(img1, keypoints1, descriptors1);

    ... // 计算第二幅图像中的关键点对应的描述向量

  4. 计算两幅图像中的关键点对应的描述向量距离,寻找两图像中距离最近的描述向量对应的关键点,即为两图像中匹配上的关键点:

    // 关键点描述向量匹配

    BruteForceMatcher<L2<float> > matcher;

    vector<DMatch> matches;

    matcher.match(descriptors1, descriptors2, matches);

  5. 可视化结果:

    // 绘制出结果

    namedWindow("matches", 1);

    Mat img_matches;

    drawMatches(img1, keypoints1, img2, keypoints2, matches, img_matches);

    imshow("matches", img_matches);

    waitKey(0);

  6. 寻找两个点集合中的单映射变换(homography transformation):

    vector<Point2f> points1, points2;

    // 用点填充形成矩阵(array)

    ....

    Mat H = findHomography(Mat(points1), Mat(points2), CV_RANSAC, ransacReprojThreshold);

  7. 创建内匹配点集合同时绘制出匹配上的点。用perspectiveTransform函数来通过单映射来映射点:
  1. 用 drawMatches 来绘制内匹配点.