#include <opencv2/opencv.hpp>
#include <opencv2/features2d.hpp>
#include <opencv2/xfeatures2d.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main() {
    // 加载图像并将其转换为灰度图像
    Mat img = imread('circle.jpg', IMREAD_COLOR);
    Mat gray;
    cvtColor(img, gray, COLOR_BGR2GRAY);

    // 使用SURF算法检测图像中的关键点和描述符
    Ptr<SURF> surf = SURF::create();
    vector<KeyPoint> keypoints;
    Mat descriptors;
    surf->detectAndCompute(gray, noArray(), keypoints, descriptors);

    // 找到尺子的匹配
    BFMatcher matcher(NORM_L2);
    vector<vector<DMatch>> matches;
    matcher.knnMatch(descriptors, descriptors, matches, 2);
    vector<Point2f> src_points;
    vector<Point2f> dst_points;
    for (int i = 0; i < matches.size(); i++) {
        DMatch &m1 = matches[i][0];
        DMatch &m2 = matches[i][1];
        if (m1.distance < 0.7 * m2.distance) {
            KeyPoint &kp1 = keypoints[m1.queryIdx];
            KeyPoint &kp2 = keypoints[m1.trainIdx];
            src_points.push_back(kp1.pt);
            dst_points.push_back(kp2.pt);
        }
    }

    // 计算尺子的长度
    Mat H = findHomography(src_points, dst_points);
    double ruler_length = norm(Point2f(0, 0), Point2f(H.at<double>(0, 2), H.at<double>(1, 2)));

    // 应用Hough圆变换算法,以检测图像中的圆形
    Mat blur;
    GaussianBlur(gray, blur, Size(5, 5), 0);
    Mat edges;
    Canny(blur, edges, 50, 150);
    vector<Vec3f> circles;
    HoughCircles(edges, circles, HOUGH_GRADIENT, 1, 20, 50, 30, 20, 100);

    // 计算检测到的圆的数量和尺寸
    int num_circles = circles.size();
    cout << 'Number of circles detected: ' << num_circles << endl;
    vector<Scalar> colors;
    colors.push_back(Scalar(255, 0, 0));  // 蓝色
    colors.push_back(Scalar(0, 255, 0));  // 绿色
    colors.push_back(Scalar(0, 0, 255));  // 红色
    colors.push_back(Scalar(255, 255, 0)); // 青色
    colors.push_back(Scalar(255, 0, 255)); // 品红色
    for (int i = 0; i < num_circles; i++) {
        Vec3f c = circles[i];
        Point center(c[0], c[1]);
        int radius = c[2];
        double diameter = radius * 2.0;
        double area = CV_PI * radius * radius;
        double size_cm = diameter * ruler_length / img.cols;
        cout << 'Circle ' << i << ':' << endl;
        cout << ' Diameter: ' << diameter << ' pixels' << endl;
        cout << ' Area: ' << area << ' pixels' << endl;
        cout << ' Size: ' << size_cm << ' cm' << endl;
        circle(img, center, radius, colors[i % 5], 2);
    }

    // 显示结果
    imshow('Circle detection', img);
    waitKey(0);
    destroyAllWindows();

    return 0;
}
使用 OpenCV 和 SURF 进行圆形检测与测量

原文地址: https://www.cveoy.top/t/topic/jsBJ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录