Opencv中SIFT特征检测代码详细解释

    xiaoxiao2025-06-07  65

    Opencv中SIFT特征检测代码详细解释

    #include <opencv2/opencv.hpp> #include <opencv2/xfeatures2d.hpp> #include <iostream> using namespace cv; using namespace std; using namespace cv::xfeatures2d; int main(int agrc, char** agrv) { Mat src = imread("D:/image2/41.jpg",IMREAD_GRAYSCALE);//加载进来就是一张灰度图像 if (!src.data) { printf("加载图片失败。。。\n"); return -1; } namedWindow("原图", CV_WINDOW_AUTOSIZE); imshow("原图", src); int numFeatures = 400; Ptr<SIFT> dector = SIFT::create(numFeatures); vector<KeyPoint> keyPoints; dector->detect(src, keyPoints, Mat()); printf("所有的关键点个数:%d", keyPoints.size()); Mat keypoint_img; drawKeypoints(src, keyPoints, keypoint_img, Scalar::all(-1), DrawMatchesFlags::DEFAULT); namedWindow("SIFT 关键点", CV_WINDOW_AUTOSIZE); imshow("SIFT 关键点", keypoint_img); waitKey(0); return 0; }

    Ptr detector = SIFT::create(numFeatures);

    numFeatures:要保留的最佳功能的数量。 按住Ctrl单击SIFT查找到SIFT::create( ) 函数的类,这条代码的意思就是类函数的实例化,比如下面的例子:

    class Box { public double length; // 长度 public double breadth; // 宽度 public double height; // 高度 } static void Main(string[] args) { Box Box1 = new Box(); // 声明 Box1,类型为 Box Box1.height = 5.0; }

    vector keypoints;

    KeyPoint是一个类,vector是个容器,合起来就是容器里面很多个类, 其中KeyPoint是SIFT算法里面的关键点,包含了各种特点:坐标、 特征点领域直径、特征点的方向、关键点的强度、特征点所在的图像金字塔的组、用于聚类的id

    class KeyPoint { Point2f pt; // 坐标 float size; // 特征点领域直径 float angle; // 特征点的方向 float response; int octave; // 特征点所在的图像金字塔的组 int class_id; // 用于聚类的id }

    detector->detect(src, keypoints, Mat());

    指针的赋值。这里的detect是类detector一个成员函数,但我没找到证据。这里的意思是调用了里面的一个函数检测src中的SIFT特征点,存储到keypoints中。 detect检测关键点函数:

    /** @brief Detects keypoints in an image (first variant) or image set (second variant). @param image Image. @param keypoints The detected keypoints. In the second variant of the method keypoints[i] is a set of keypoints detected in images[i] . @param mask Mask specifying where to look for keypoints (optional). It must be a 8-bit integer matrix with non-zero values in the region of interest. */ CV_WRAP virtual void detect( InputArray image, CV_OUT std::vector<KeyPoint>& keypoints, InputArray mask=noArray() );

    代码演示结果:

    最新回复(0)