如何在c ++中使用opencv 3检测图像中的圆圈 [英] How to detect the circles in the image using opencv 3 in c++

查看:66
本文介绍了如何在c ++中使用opencv 3检测图像中的圆圈的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何检测圆圈并计算此图像中的数字.我是打开 cv 和 c++ 的新手.任何人都可以帮助解决这个问题.我试过 hough circle .但没有用.

How Can I detect the circles and count the number in this image. I'm new to open cv and c++.Can any one help with this issue. I tried with hough circle . But didn't work .

骨架化的二值图像如下.

The skeletonized binary image is as follows.

推荐答案

从这张图开始(我去掉了边框):

Starting from this image (I removed the border):

您可以采用这种方法:

1) 使用 findContour 获取轮廓.

1) Use findContour to get the contours.

2) 只保留内部轮廓.您可以检查 contourArea(..., true) 返回的区域的符号.您将获得 2 个内部轮廓:

2) Keep only internal contours. You can do that checking the sign of the area returned by contourArea(..., true). You'll get the 2 internal contours:

3) 现在你有了两个轮廓,你可以用 minEnclosureCircle(蓝色)找到一个圆,或者用 fitEllipse(红色)拟合一个椭圆:

3) Now that you have the two contours, you can find a circle with minEnclosingCircle (in blue), or fit an ellipse with fitEllipse (in red):

这里有完整的代码供参考:

Here the full code for reference:

#include <opencv2/opencv.hpp>
#include <vector>

using namespace std;
using namespace cv;

int main() 
{
    Mat1b img = imread("path_to_image", IMREAD_GRAYSCALE);

    // Get contours
    vector<vector<Point>> contours;
    findContours(img, contours, RETR_TREE, CHAIN_APPROX_NONE);

    // Create output image
    Mat3b out;
    cvtColor(img, out, COLOR_GRAY2BGR);

    Mat3b outContours = out.clone();

    // Get internal contours
    vector<vector<Point>> internalContours;
    for (size_t i = 0; i < contours.size(); ++i) {
        // Find orientation: CW or CCW
        double area = contourArea(contours[i], true);
        if (area >= 0) {
            // Internal contour
            internalContours.push_back(contours[i]);

            // Draw with different color
            drawContours(outContours, contours, i, Scalar(rand() & 255, rand() & 255, rand() & 255));
        }
    }

    // Get circles 
    for (const auto& cnt : internalContours) {
        Point2f center;
        float radius;
        minEnclosingCircle(cnt, center, radius);

        // Draw circle in blue
        circle(out, center, radius, Scalar(255, 0, 0));
    }

    // Get ellipses
    for (const auto& cnt : internalContours) {
        RotatedRect rect = fitEllipse(cnt);

        // Draw ellipse in red
        ellipse(out, rect, Scalar(0, 0, 255), 2);
    }

    imshow("Out", out);
    waitKey();

    return 0;
}

这篇关于如何在c ++中使用opencv 3检测图像中的圆圈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆