如何将轮廓转换为实心圆圈?

时间:2015-07-28 06:23:44

标签: python opencv tracking opencv-contour

是否有机会将框架中找到的所有轮廓转换为实心圆圈?

让我解释一下,我的视频有许多小物件,使用Mosse跟踪很难检测到,因为我的物体改变了它的形状。所以我有了一个想法,将所有找到的轮廓更改为实心圆圈,这意味着,转换此图像上找到的所有这些对象:

enter image description here

这样的事情:

enter image description here

我正在使用python和Opencv。

1 个答案:

答案 0 :(得分:0)

要在实心圆中转换轮廓,一种简单的方法就像:

  1. 获取每个轮廓
  2. 找到轮廓的边界框
  3. 找到边界框的中心,将是圆圈的中心
  4. 找到边界框的对角线,将是圆圈的半径
  5. 画一个给定中心和半径的圆圈。
  6. 下面是一个示例(它的C ++,但你可以很容易地移植到python)关于如何编写上述步骤的代码:

    #include "opencv2/opencv.hpp"
    using namespace cv;
    
    int main(int, char**)
    {
        Mat1b img = imread("path_to_image", IMREAD_GRAYSCALE);
    
        // This will enlarge the circles by a "factor"
        float factor = 2;
    
        // Find blobs and extract contours
        vector<vector<Point>> contours;
        findContours(img.clone(), contours, CV_RETR_LIST, CV_CHAIN_APPROX_NONE);
    
        Mat1b res(img.size(), uchar(0));
    
        for (int i = 0; i < contours.size(); ++i)
        {
            // Get the bounding box of the contours
            Rect bb = boundingRect(contours[i]);
    
            // Get the center of the bounding box
            // Will be the center of the circle
            Point center(bb.x + bb.width/2, bb.y + bb.height/2);
    
            // Get the length of the diagonal of the bounding box.
            // Will be the radius of the circle (eventually multiplied by a factor)
            int radius = sqrt(bb.width*bb.width + bb.height*bb.height) / 2;
    
            // Draw the circle
            circle(res, center, radius*factor, Scalar(255), CV_FILLED);
        }
    
        return 0;
    }
    

    原始图片

    enter image description here

    圈子结果

    enter image description here