#include <opencv2/opencv.hpp> #include

using namespace cv; using namespace std;

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

// 使用SIFT算法检测图像中的关键点和描述符
Ptr <SIFT> sift = SIFT::create();
vector <KeyPoint> keypoints;
Mat descriptors;
sift->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;

}

// 修改这个代码的语法错误内容:这个代码没有语法错误,但可能需要进行一些改进以提高性能和准确性。例如,可以尝试使用ORB或SURF算法替代SIFT算法,或者使用适当的参数来优化Hough圆变换算法的性能。


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

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