c++ - 不规则点分布的质心

标签 c++ opencv

我有一张“视觉上”形成闭合圆的点的图像。然而,这些点沿着这个“轮廓”分布不均匀,导致质心偏斜。我尝试使用 findContours 但没有找到闭合线。

有没有简单的解决办法?

编辑: 这些点存储在 x 和相应的 y 坐标的 vector 中,我使用 cv::circle 绘制它们。

图像:白色 + 红色 = 整个 vector (720 点),红色 = vector 的前半部分(360 点)

enter image description here

原图:

enter image description here

最佳答案

您可以使用 minEnclosingCircle找到包含所有点的最小圆。

你得到 center 作为函数的输出值:

void minEnclosingCircle(InputArray points, Point2f& center, float& radius)

更新

我尝试了一些不同的东西。 我假设你知道你的最终形状是一个圆

  • minEnclosingCircle
  • boundingRect
  • 拟合椭圆

最好的结果(在这张图片中)似乎是 fitEllipse

结果

最小封闭圈:

enter image description here

边界矩形:

enter image description here

拟合椭圆:

enter image description here

代码:

#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/

相关文章:

c++ - 命名空间参数的理想架构设计

c++ - 逐行复制文件

c++ - "SSE 4.2 insanity"提案文件中的 "if consteval"是什么意思?

visual-c++ - OpenCV 2.3.1 和 OpenNI Kinect

c++ - 对图像应用透视 - 单应性

c++ - 静态断言添加操作是否可用

c++ - UTF-8 字符串的大小(以字节为单位)

c++ - 取消引用 "cv::Mat* "指向 cv::Mat 的指针以接收 Gstreamer 视频并在 OpenCV 中使用

python - 在 opencv 3.x 中设置 FPS

c++ - OpenGL 显示图像的速度是否比 OpenCV 快?