如何使用OPENCV获得最小包围圈? [英] How can I get the minimum enclosing circle with OPENCV?

查看:184
本文介绍了如何使用OPENCV获得最小包围圈?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用cv::minEnclosingCircle(...)来获得恰好使我的轮廓逐渐发展的最小圆,但是我得到的圆要大一些.

I'm using cv::minEnclosingCircle(...) in order to get the minimum circle that exactly evolves my contour, but I'm getting a circle a little big bigger.

换句话说,我正在尝试得到这样的东西:

In other words, I'm trying to get something like this:

https://upload.wikimedia.org/wikipedia/commons/thumb/3/35/Simple_concave_polygon_Min_Enclosing_Circle.svg/441px-Simple_concave_polygon_Min_Enclosing_Circle.svg.png

但是我得到了这个(圆圈):

But I'm getting this (the circle):

请注意,圆圈比要围封的项目要大一点.

Note how the circle is a little bigger than the item to enclose.

我需要将对象围成一个圆圈,而不是一个椭圆形.

I need to enclose my object into a circle, not an ellipse.

谢谢.

这是我的代码:

cv::vector<cv::Point> allPixels;
    int columnas = img.cols, filas = img.rows;
    cv::Point pt;
    for(int col = 0; col < columnas; col++){
        for(int row = 0; row < filas; row++){

            int val = img.at<uchar>(row,col);

            if(val == 255){
                pt.x = col;
                pt.y = row;

                allPixels.push_back(pt);
            }
        }
    }

    cv::Mat dispImage = img.clone();
    cv::Point2f center;
    float radius;

    cv::minEnclosingCircle(allPixels,center,radius);

    cv::circle(dispImage,center,radius,cv::Scalar(128),1);
    cv::circle(dispImage,center,1,cv::Scalar(128),1);

    cv::imwrite("Enclosing_Result.png",dispImage);

带有'img'的cv :: Mat大小为(760,760),格式为CV_8UC1.最终结果("Enclosing_Result.png")是下一个:

With 'img' a cv::Mat with size (760,760) and format CV_8UC1. The final result ("Enclosing_Result.png") is next:

我的目标是(绘制)如下:

And my target is which follows (drawn):

推荐答案

我的结果很好.

## only one region
cnts = cv2.findContours(threshed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]

(x,y), r = cv2.minEnclosingCircle(cnts[0])

## more than one region
mask = threshed.copy()

## find centers 
for cnt in cnts:
    (x,y), r = cv2.minEnclosingCircle(cnt)
    pt = (int(x), int(y))
    centers.append(pt)

## connect the `centers`
for i in range(1, len(centers)):
    cv2.line(mask, centers[i-1], centers[i], 255, 2)

## find the center 
cnts = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
(x,y), r = cv2.minEnclosingCircle(cnts[0])

这篇关于如何使用OPENCV获得最小包围圈?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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