【问题标题】:Best fit a circle from a binary image using contours or any other technique使用轮廓或任何其他技术从二值图像中最佳拟合圆
【发布时间】:2018-02-22 16:36:24
【问题描述】:

我有一个通过一些算法计算得到的二值图像。图像中有一个洞,我想在这个洞中最适合一个圆圈。我尝试使用bestminEnclosingCircle 函数,但效果不佳。

这是二值图像

这是我从这个函数中得到的结果

这是预期的

我想排除这部分

这是我寻找轮廓的代码

    vector<Vec4i> hierarchy;
    vector<vector<Point> > contours;


    findContours(src, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));

【问题讨论】:

  • 你的结果看起来很奇怪只做findcontours......使用该功能你应该能够完全获得黑色斑点......你可以尝试fitellipse。 here 是一些opencv函数的教程,可能对你有帮助(它在python中,但这些函数也存在于c++中)

标签: c++ opencv opencv-contour best-fit


【解决方案1】:

检查下面的代码

#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include <iostream>

using namespace cv;
using namespace std;


int main(int, char** argv)
{
    Mat src, src_gray;

    /// Load source image and convert it to gray
    src = imread("e:/test/ifFz9.png");
    resize(src, src, Size(), 0.25, 0.25);

    /// Convert image to gray and blur it
    cvtColor(src, src_gray, COLOR_BGR2GRAY);
    blur(src_gray, src_gray, Size(3, 3));

    imshow("Source", src);

    Mat threshold_output;
    vector<vector<Point> > contours;

    /// Detect edges using Threshold
    threshold(src_gray, threshold_output, 127, 255, THRESH_BINARY);
    /// Find contours
    findContours(threshold_output, contours, RETR_TREE, CHAIN_APPROX_SIMPLE);

    for (size_t i = 0; i < contours.size(); i++)
    {
        if (contours[i].size() > 50)
        {
            RotatedRect minEllipse = fitEllipse(contours[i]);

            int size = min(minEllipse.size.width, minEllipse.size.height) / 2;
            // ellipse
            if (size < src.rows / 2)
                ellipse(src, minEllipse.center, Size(size, size), 0, 360, 0, Scalar(0, 0, 0255), 2, 8);
        }
    }

    imshow("Contours", src);
    waitKey(0);

    return 0;
}

【讨论】:

  • 谢谢。让我试试。另外,你能解释一下第二个循环吗?
  • 这不是为这种图像提供正确的结果binaryrgb result
  • 如果孔的内部比外部更白,它也不会给出正确的结果。即对于这种示例,我们必须找到旋转矩形的高度和宽度的最大值,而不是高度和宽度的最小值。
猜你喜欢
  • 1970-01-01
  • 2020-03-29
  • 2015-04-01
  • 1970-01-01
  • 2015-12-12
  • 1970-01-01
  • 2019-07-08
  • 2015-10-03
  • 2020-03-01
相关资源
最近更新 更多