c++opencvsift

How do I use SIFT in OpenCV 4.2.0 with C++?


I am using visual studio 2017. Opencv and opencv verison of 4.2.0 is installed and files are generated using cmake. xfeatured2d420.lib is linked with compiler. And also #include "opencv2/xfeatures2d.hpp" #include "opencv2/xfeatures2d/nonfree.hpp" included. Extracting features using xfeatures2d::Sift giving me memory error. I need to compute sift keypoints from two images.


Solution

  • Mat img_1 = imread("C:/Users/Dan/Desktop/0.jpg", 1);   
    Mat img_2 = imread("C:/Users/Dan/Desktop/0.jpg", 1);
    cv::Ptr<Feature2D> f2d = xfeatures2d::SIFT::create(); 
    std::vector<KeyPoint> keypoints_1, keypoints_2; 
    f2d->detect(img_1, keypoints_1); 
    f2d->detect(img_2, keypoints_2); 
    Mat descriptors_1, descriptors_2; 
    f2d->compute(img_1, keypoints_1, descriptors_1); 
    f2d->compute(img_2, keypoints_2, descriptors_2); 
    BFMatcher matcher; 
    std::vector< DMatch > matches; matcher.match(descriptors_1, 
    descriptors_2, matches); 
    vector<cv::DMatch> good_matches;
    for (int i = 0; i < matches.size(); ++i)
    {
        const float ratio = 0.8; 
        if (matches[i][0].distance < ratio * matches[i] 
     [1].distance)
                    {
                    good_matches.push_back(matches[i][0]);
                    }
        }
    
    vector<Point2f> points1, points2;
    for (int i = 0; i < good_matches.size(); i++)
        {
                //-- Get the keypoints from the good matches
                 
            points1.push_back(keypoints_1[good_matches[i].queryIdx].pt);
                 
            points2.push_back(keypoints_2[good_matches[i].trainIdx].pt);
        }
    
            /* Find Homography */
    Mat H = findHomography(Mat(points2), Mat(points1), RANSAC);