利用opencv4.8和c++求得区域质心并标记代码
时间: 2024-09-09 22:00:44 浏览: 32
以下是利用OpenCV4.8和C++求得区域质心并标记的代码:
```cpp
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
Mat src = imread("test.jpg", 1); //读取图像
Mat gray;
cvtColor(src, gray, COLOR_BGR2GRAY); //将图像转换为灰度图像
threshold(gray, gray, 100, 255, THRESH_BINARY); //二值化处理
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
findContours(gray, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE); //寻找轮廓
for (int i = 0; i < contours.size(); i++)
{
Moments mu = moments(contours[i], false); //计算轮廓的矩
Point2f center(mu.m10 / mu.m00, mu.m01 / mu.m00); //计算轮廓的质心
circle(src, center, 5, Scalar(0, 0, 255), -1); //在图像上标记质心
}
imshow("src", src);
waitKey(0);
return 0;
}
```
阅读全文