最适合使用轮廓或任何其他技术从二进制图像中拟合圆圈

时间:2017-09-13 20:39:30

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

我有一些从某些算法算出的二进制图像。图像上有一个洞,我想在这个洞中最合适的圆圈。我尝试使用bestminEnclosingCircle功能,但它没有给出最佳效果。

这是二进制图像

enter image description here

以下是我从这个功能中获得的内容

enter image description here

这是预期的

enter image description here

我想排除这部分

enter image description here

这是我查找轮廓的代码

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


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

1 个答案:

答案 0 :(得分:0)

检查下面的代码

enter image description here

#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;
}