Features2D + Homography物体识别

void FeaHom(){
    Mat img_object = imread("hours.jpg");
    Mat img_scene = imread("findhours.jpg");

    int minHessian = 800;
    SurfFeatureDetector detector(minHessian);
    vector<KeyPoint>keypoints_object, keypoints_scene;
    detector.detect(img_object, keypoints_object);
    detector.detect(img_scene, keypoints_scene);

    SurfDescriptorExtractor extractor;
    Mat descriptors_object, descriptors_scene;
    extractor.compute(img_object, keypoints_object, descriptors_object);
    extractor.compute(img_scene, keypoints_scene, descriptors_scene);

    FlannBasedMatcher matcher;

    vector<DMatch>matches;
    matcher.match(descriptors_object, descriptors_scene, matches);
    double max_dist = 0; double min_dist = 100;
    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;
    }

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

    vector<Point2f>obj;
    vector<Point2f>scene;
    for (int i = 0; i < good_matches.size(); ++i){
        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, CV_RANSAC);
    vector<Point2f>obj_corners(4);
    obj_corners[0] = cvPoint(0, 0); 
    obj_corners[1] = cvPoint(img_object.cols,0);
    obj_corners[2] = cvPoint(img_object.cols, img_object.rows); 
    obj_corners[3] = cvPoint(0, img_object.rows);
    vector<Point2f>scene_corners(4);
    perspectiveTransform(obj_corners, scene_corners, H);


    line(img_matches, scene_corners[0] + Point2f(img_object.cols, 0), scene_corners[1] + Point2f(img_object.cols, 0), Scalar(0, 255, 0), 4);
    line(img_matches, scene_corners[1] + Point2f(img_object.cols, 0), scene_corners[2] + Point2f(img_object.cols, 0), Scalar(0, 255, 0), 4);
    line(img_matches, scene_corners[2] + Point2f(img_object.cols, 0), scene_corners[3] + Point2f(img_object.cols, 0), Scalar(0, 255, 0), 4);
    line(img_matches, scene_corners[3] + Point2f(img_object.cols, 0), scene_corners[0] + Point2f(img_object.cols, 0), Scalar(0, 255, 0), 4);


    imshow("Good Matches & Object detection", img_matches);
    waitKey(0);
}

这里写图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值