c++opencvsift

Using SIFT in opencv using c++ without special libraries


Based on sources such as this it seems the only way people are using SIFT is with the library

#include <opencv2/nonfree/features2d.hpp>

which I am not able to use. Im not finding any sources saying there are other options in c++ opencv

Does anyone know of a way to do SIFT extraction without this library?

I have tried using this library included with opencv

#include <opencv2/features2d.hpp>

which according to https://docs.opencv.org/4.x/d7/d60/classcv_1_1SIFT.html should contain the SIFT functions needed

const cv::Mat input = cv::imread("my/file/path", 0); //Load as grayscale

        cv::SiftFeatureDetector detector;
        std::vector<cv::KeyPoint> keypoints;
        detector.detect(input, keypoints);

        // Add results to image and save.
        cv::Mat output;
        cv::drawKeypoints(input, keypoints, output);
        for (int i = 0; i < 100; i++) {
            imshow(window_name, output);
            waitKey(50);
        }

but when I run this i get an exception that likely means nothing is being stored in the output matrix to begin with

Unhandled exception at 0x00007FFFF808FE7C in CS4391_Project1.exe: Microsoft C++ exception: cv::Exception at memory location 0x00000008C15CF5C0.

Solution

  • As far as I know, OpenCV expects you to create the feature detector dynamically. For example, you can do something like this:

    #include <opencv2/features2d.hpp>
    #include <opencv2/imgcodecs.hpp>
    #include <opencv2/highgui.hpp>
    #include <iostream>
    
    int main(int argc, char **argv) { 
    
        if (argc != 2) {
            std::cerr << "Usage; sift <imagefile>\n";
            return EXIT_FAILURE;
        }
       
        const int feature_count = 10; // number of features to find
    
        const cv::Mat input = cv::imread(argv[1], 0);
    
        cv::Ptr<cv::SiftFeatureDetector> detector =
            cv::SiftFeatureDetector::create(feature_count);
        std::vector<cv::KeyPoint> keypoints;
        detector->detect(input, keypoints);
    
        std::string window_name = "main";
    
        cv::namedWindow(window_name);
    
        cv::Mat output;
        cv::drawKeypoints(input, keypoints, output);
        cv::imshow(window_name, output);
        cv::waitKey(0);
    }
    

    [Tested on Ubuntu, with OpenCV 4.5.4]

    Note that although the features it detects will be outlined in color on a gray-scale image, they're sometimes pretty small so you need to look carefully to find them.