#include <opencv2/opencv.hpp>#include <iostream>using namespace std;using namespace cv;int main(){ // 读取图像并进行预处理 Mat src = imread("test.jpg"); Mat gray, binary; cvtColor(src, gray, COLOR_BGR2GRAY); threshold(gray, binary, 0, 255, THRESH_BINARY | THRESH_OTSU); imshow("binary", binary); // 计算轮廓 vector<vector<Point> > contours; vector<Vec4i> hierarchy; findContours(binary, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point()); // 计算中心、质心、重心、外接圆圆心 Point2f center, centroid, gravity, minEnclosingCircleCenter; Moments mu = moments(contours[0], false); center = Point2f(mu.m10 / mu.m00, mu.m01 / mu.m00); minEnclosingCircle(contours[0], minEnclosingCircleCenter, radius); centroid = Point2f(mu.m10 / mu.m00, mu.m01 / mu.m00); gravity = Point2f(mu.m10 / mu.m00, mu.m01 / mu.m00 + 50); // 绘制结果 Mat drawing = Mat::zeros(binary.size(), CV_8UC3); circle(drawing, center, 5, Scalar(0, 0, 255), -1); circle(drawing, centroid, 5, Scalar(0, 255, 0), -1); circle(drawing, gravity, 5, Scalar(255, 0, 0), -1); circle(drawing, minEnclosingCircleCenter, 5, Scalar(0, 255, 255), -1); imshow("result", drawing); waitKey(0); return 0;}添加更详细的注释
时间: 2024-03-01 12:52:36 浏览: 112
好的,下面是更详细的注释:
```c++
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main()
{
// 读取图像并进行预处理
Mat src = imread("test.jpg"); // 读取图像
Mat gray, binary; // 定义灰度图像和二值图像
cvtColor(src, gray, COLOR_BGR2GRAY); // 将图像转换为灰度图像
threshold(gray, binary, 0, 255, THRESH_BINARY | THRESH_OTSU); // 对灰度图像进行二值化
imshow("binary", binary); // 显示二值图像
// 计算轮廓
vector<vector<Point> > contours; // 定义轮廓
vector<Vec4i> hierarchy; // 定义轮廓的层次结构
findContours(binary, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point()); // 提取轮廓
// 计算中心、质心、重心、外接圆圆心
Point2f center, centroid, gravity, minEnclosingCircleCenter; // 定义中心、质心、重心、外接圆圆心
Moments mu = moments(contours[0], false); // 计算轮廓的矩
center = Point2f(mu.m10 / mu.m00, mu.m01 / mu.m00); // 计算中心
float radius;
minEnclosingCircle(contours[0], minEnclosingCircleCenter, radius); // 计算外接圆
centroid = Point2f(mu.m10 / mu.m00, mu.m01 / mu.m00); // 计算质心
gravity = Point2f(mu.m10 / mu.m00, mu.m01 / mu.m00 + 50); // 计算重心
// 绘制结果
Mat drawing = Mat::zeros(binary.size(), CV_8UC3); // 创建一个空的彩色图像
circle(drawing, center, 5, Scalar(0, 0, 255), -1); // 绘制中心
circle(drawing, centroid, 5, Scalar(0, 255, 0), -1); // 绘制质心
circle(drawing, gravity, 5, Scalar(255, 0, 0), -1); // 绘制重心
circle(drawing, minEnclosingCircleCenter, 5, Scalar(0, 255, 255), -1); // 绘制外接圆圆心
imshow("result", drawing); // 显示绘制结果
waitKey(0); // 等待按键
return 0;
}
```
注释中对代码的各个部分进行了说明,使得代码更容易理解。
阅读全文