C++opencv确定轮廓中心center
时间: 2023-07-04 17:27:15 浏览: 196
确定轮廓中心点的一种方法是使用cv::moments函数计算轮廓的矩和中心坐标。下面是使用cv::moments函数确定轮廓中心点的C++代码示例:
```c++
#include <opencv2/opencv.hpp>
using namespace cv;
int main()
{
// 读取图像
Mat img = imread("contour.jpg");
// 转换为灰度图像
Mat gray;
cvtColor(img, gray, COLOR_BGR2GRAY);
// 二值化处理
Mat binary;
threshold(gray, binary, 0, 255, THRESH_BINARY);
// 寻找轮廓
std::vector<std::vector<Point>> contours;
findContours(binary, contours, RETR_EXTERNAL, 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);
// 在图像中绘制轮廓和中心点
drawContours(img, contours, i, Scalar(0, 0, 255), 2);
circle(img, center, 3, Scalar(0, 255, 0), -1);
}
// 显示图像
imshow("contour", img);
waitKey();
return 0;
}
```
在上述代码中,使用cv::moments函数计算了每个轮廓的矩和中心坐标。其中,mu.m00表示轮廓面积,mu.m10和mu.m01分别表示轮廓的x方向和y方向的一阶矩。最后,使用cv::circle函数在图像中绘制轮廓中心点。