我有一张“视觉上”形成闭合圆的点的图像。然而,这些点沿着这个“轮廓”分布不均匀,导致质心偏斜。我尝试使用 findContours
但没有找到闭合线。
有没有简单的解决办法?
编辑:
这些点存储在 x 和相应的 y 坐标的 vector 中,我使用 cv::circle
绘制它们。
图像:白色 + 红色 = 整个 vector (720 点),红色 = vector 的前半部分(360 点)
原图:
最佳答案
您可以使用 minEnclosingCircle找到包含所有点的最小圆。
你得到 center
作为函数的输出值:
void minEnclosingCircle(InputArray points, Point2f& center, float& radius)
更新
我尝试了一些不同的东西。 我假设你知道你的最终形状是一个圆。
minEnclosingCircle
boundingRect
拟合椭圆
最好的结果(在这张图片中)似乎是 fitEllipse
。
结果
最小封闭圈:
边界矩形:
拟合椭圆:
代码:
#include <opencv2\opencv.hpp>
#include <vector>
using namespace std;
using namespace cv;
int main()
{
Mat1b img = imread("path_to_image", IMREAD_GRAYSCALE);
vector<Point> points;
findNonZero(img, points);
Mat3b res;
cvtColor(img, res, CV_GRAY2BGR);
//////////////////////////////////
// Method 1: minEnclosingCircle
//////////////////////////////////
/*Point2f center;
float radius;
minEnclosingCircle(points, center, radius);
circle(res, center, radius, Scalar(255,0,0), 1);
circle(res, center, 5, Scalar(0,255,0), 1);*/
//////////////////////////////////
// Method 2: boundingRect
//////////////////////////////////
/*Rect bbox = boundingRect(points);
rectangle(res, bbox, Scalar(0,255,255));
circle(res, Point(bbox.x + bbox.width/2, bbox.y + bbox.height/2), 5, Scalar(0,0,255));*/
//////////////////////////////////
// Method 3: fit ellipse
//////////////////////////////////
RotatedRect ell = fitEllipse(points);
ellipse(res, ell, Scalar(255,255,0));
circle(res, ell.center, 5, Scalar(255,0,255));
return 0;
}
关于c++ - 不规则点分布的质心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32048917/