opencv实现任意形状的内切圆

参考任意多边形的最大内切圆算法_海风吹来的石头的博客-CSDN博客_c++ 最大内切圆


前言

利用opencv的distanceTransform函数实现内切圆,对于稍微大一点的图像,耗时很严重,所以我参考上面提到的博客的思想(将轮廓区域进行分割),主要利用opencv的pointPolygonTest函数来求解内切圆,耗时较少。所以在这里记录一下。

一、源码

代码如下(示例):

//可牺牲精度加快速度
Point GeometryFindPIA(const vector<Point> &polygon, float bounds[]) {
    int N_CELLS = 1;
    int M_CELLS = 5;
    cv::Point pia;
    pia.x = (bounds[0] + bounds[1]) / 2;
    pia.y = (bounds[2] + bounds[3]) / 2;
    cv::Point tmp;
    float increment_x = (bounds[1] - bounds[0]) / N_CELLS;
    float increment_y = (bounds[3] - bounds[2]) / M_CELLS;
    float max_distance = 0;
    int i, j;
    float tmp_distance = FLT_MAX;
    for (i = 0; i <= N_CELLS; i++)
    {
        tmp.x = bounds[0] + i * increment_x;
        for (j = 0; j <= M_CELLS; j++)
        {
            tmp.y = bounds[2] + j * increment_y;
            tmp_distance = pointPolygonTest(polygon, tmp, true);
            if (tmp_distance > max_distance)
            {
                max_distance = tmp_distance;
                pia.x = tmp.x;
                pia.y = tmp.y;
            }
        }
    }
    return pia;
}

//求解最大内切圆函数,传入多个轮廓
bool MaxInnerCircle(const vector<vector<Point>> &cons, vector< Point> &center, vector<double> &radius) {
    if (cons.size() == 0) {
        return false;
    }
    for (int m = 0; m < cons.size(); ++m) {
        Rect rect = boundingRect(cons[m]);//获得轮廓的矩形区域
        double radiusTemp = 0;
        float bounds[4];
        //初始化区域
        bounds[0] = rect.x;
        bounds[1] = rect.x + rect.width;
        bounds[2] = rect.y;
        bounds[3] = rect.y + rect.height;
        cv::Point point_pia;
        float flt_tmp = FLT_MAX;
        int count = 1;
        cv::Point point_tmp;// 
        //先划分区域,找到合适的一个区域后,再次划分这个区域,按此迭代,直到找到心点和半径
        while (count++)
        {
            // 对区域划分,找到最合适的区域
            point_tmp = GeometryFindPIA(cons[m], bounds);
            // 更新中心点
            point_pia.x = point_tmp.x;
            point_pia.y = point_tmp.y;
            // 更新区域
            flt_tmp = (bounds[1] - bounds[0]) / (sqrtf(2) * 2);
            bounds[0] = point_pia.x - flt_tmp;
            bounds[1] = point_pia.x + flt_tmp;
            flt_tmp = (bounds[3] - bounds[2]) / (sqrtf(2) * 2);
            bounds[2] = point_pia.y - flt_tmp;
            bounds[3] = point_pia.y + flt_tmp;
            //可牺牲精度加快速度
            if (bounds[1] - bounds[0] < 1 || bounds[3] - bounds[2] < 1) break;
        }
        radiusTemp = pointPolygonTest(cons[m], point_pia, true);
        if (radiusTemp>0) {
            center.push_back(point_tmp);
            radius.push_back(radiusTemp);
        }
        
    }
}


//最大内接圆重载,传入单个轮廓
bool MaxInnerCircle(const vector<Point> &con, Point &center, double &radius) {
    if (con.size() <= 0) {
        return false;
    }
    Rect rect = boundingRect(con);
    float bounds[4];
    bounds[0] = rect.x;
    bounds[1] = rect.x + rect.width;
    bounds[2] = rect.y;
    bounds[3] = rect.y + rect.height;
    cv::Point point_pia;
    float flt_tmp = FLT_MAX;
    int count = 1;
    cv::Point point_tmp;// 
    while (count++)
    {
        // find new candidate 
        point_tmp = GeometryFindPIA(con, bounds);
        // update current 
        point_pia.x = point_tmp.x;
        point_pia.y = point_tmp.y;
        // update the bounds
        flt_tmp = (bounds[1] - bounds[0]) / (sqrtf(2) * 2);
        bounds[0] = point_pia.x - flt_tmp;
        bounds[1] = point_pia.x + flt_tmp;
        flt_tmp = (bounds[3] - bounds[2]) / (sqrtf(2) * 2);
        bounds[2] = point_pia.y - flt_tmp;
        bounds[3] = point_pia.y + flt_tmp;
        //可牺牲精度加快速度
        if (bounds[1] - bounds[0] < 1 || bounds[3] - bounds[2] < 1) break;
    }

    radius = pointPolygonTest(con, point_pia, true);
    center = point_pia;
    if (radius <= 0.1) {
        return false;
    }
    return true;
}

2.测试

代码如下(示例):

//测试最大内接圆
void testInnerCircle(int flag) {
    Mat img = imread("1.png", 1);
    Mat src;
    cvtColor(img, src, COLOR_BGR2GRAY);
    threshold(src, src, 130, 255, THRESH_BINARY);
    vector<vector<Point>> contours, SelectContours;

    findContours(src, contours, RETR_LIST, CHAIN_APPROX_NONE);
    int jpg = 10000000;
    for (int i = 0; i < contours.size(); i = i + 1) {//一条边内外轮廓会检测出四条
        //approxPolyDP(Con, approx, 0.1, true);
        double area1 = contourArea(contours[i]);
        if (area1 > 1000) {
            SelectContours.push_back(contours[i]);
        }
    }

    clock_t begin = clock();
    if (flag == 1) {
        vector<Point> Center;
        vector<double> Radius;
        MaxInnerCircle(SelectContours, Center, Radius);
        for (int i = 0; i < Center.size(); i++) {
            circle(img, Center[i], Radius[i], Scalar(0, 0, 255),6);
        }
    }
    else {
        vector<Point> cons1;
        Point P;
        double R;
        for (int i = 0; i < SelectContours.size(); i++) {
            cons1 = SelectContours[i];
            if (MaxInnerCircle(cons1, P, R)) {
                circle(img, P, R, Scalar(0, 0, 255), 2);
            }            
        }
    }
    clock_t end = clock();
    double programTimes = ((double)end - begin) / CLOCKS_PER_SEC;
    cout << "执行时间: " << programTimes << endl;
    namedWindow("img", WINDOW_NORMAL);
    namedWindow("src", WINDOW_NORMAL);
    imshow("img", img);
    imshow("src", src);
    waitKey(0);
}

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
OpenCV 中提取任意形状轮廓的步骤如下: 1. 读入原始图像,转换为灰度图像。 ``` img = cv2.imread('image.jpg') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ``` 2. 对灰度图像进行二值化处理,使用 `cv2.threshold()` 函数实现。该函数会返回一个阈值和二值化后的图像。 ``` ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY) ``` 3. 对二值化后的图像进行形态学操作,使用 `cv2.morphologyEx()` 函数实现。一般情况下,我们可以先对图像进行腐蚀操作,然后再进行膨胀操作,以去除噪音和填充空洞。 ``` kernel = np.ones((5,5),np.uint8) thresh = cv2.erode(thresh,kernel,iterations = 1) thresh = cv2.dilate(thresh,kernel,iterations = 1) ``` 4. 检测图像中的轮廓,使用 `cv2.findContours()` 函数实现。该函数会返回一个包含所有轮廓的数组,每个轮廓都是一个由点组成的数组。 ``` contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) ``` 5. 对轮廓进行筛选,使用 `cv2.contourArea()` 函数计算轮廓的面积,并根据面积大小进行筛选。例如,我们可以筛选出面积大于某个值的轮廓。 ``` for cnt in contours: area = cv2.contourArea(cnt) if area > 100: cv2.drawContours(img, [cnt], 0, (0, 255, 0), 3) ``` 在上述代码中,我们使用 `cv2.drawContours()` 函数将轮廓绘制到原始图像上。该函数需要传入原始图像、轮廓数组、轮廓的索引、绘制的颜色和线条宽度等参数。 需要注意的是,轮廓提取的具体实现方式可能因应用场景而异,需要根据实际情况进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值