opencv:在二进制图像中拟合最小的包围椭圆

时间:2015-05-12 15:00:22

标签: c++ opencv image-processing

我已经使用OpenCV和grabcut实现来生成前景的二进制掩码。这表示为CV_8UC1的opencv矩阵,其中属于前景的像素具有值255并且背景为零(即,它是二进制掩码)。因此,像附加的图像:enter image description here

我想找到这个蒙版图像的最小包围椭圆。我在网上找到的例子似乎有点复杂,我无法将其转化为我的需求。我试过简单地使用

// result is my OpenCV array of 
cv::RotatedRect e = cv::fitEllipse(result);

OpenCV Error: Assertion failed (points.checkVector(2) >= 0 && 
(points.depth() == CV_32F || points.depth() == CV_32S)) in fitEllipse, 
file /home/luca/Downloads/opencv-2.4.10/modules/imgproc
/src/contours.cpp, line 2019

terminate called after throwing an instance of 'cv::Exception'
what():  /home/luca/Downloads/opencv-2.4.10/modules/imgproc
/src/contours.cpp:2019: error: (-215) points.checkVector(2) >= 0 && 
(points.depth() == CV_32F || points.depth() == CV_32S) in function 
fitEllipse

即使我使用以下命令将其转换为32位signed int,错误仍然存​​在:

cv::Mat r;
result.convertTo(r, CV_32S);
cv::RotatedRect e = cv::fitEllipse(r);

3 个答案:

答案 0 :(得分:3)

函数fitEllipse采用cv :: Point s数组,而不是图像。因此,您希望首先通过findContours运行您的图片。请注意,findContours会修改图片,因此您可能需要先制作副本。

std::vector< std::vector<cv::Point> > contours;
cv::Mat tmp = result.clone();
cv::findContours(tmp, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE); // edited to change from CV_CHAIN_APPROX_SIMPLE
cv::RotatedRect e = cv::fitEllipse(contours[0]);

以上假设您的图像中只有一个轮廓。您可能想要在contours搜索最大轮廓(使用大小或区域)以防有任何噪音(并确认您至少获得一个轮廓)。

答案 1 :(得分:2)

如果您不确定图像中是否有椭圆,可以通过调用cv::minAreaRect来使用其他方法。

我已经用3种不同的方式编写了示例代码:

1. call cv::fitEllipse
2. call cv::minAreaRect
3. call cv::fitEllipse on contour only

代码有点乱,但反正可能会有所帮助

int main()
{
    cv::Mat input = cv::imread("../inputData/fitEllipseMask.jpg");

    cv::Mat gray;
    cv::cvtColor(input,gray,CV_BGR2GRAY);
    cv::Mat mask = gray > 200; // remove jpeg artifacts

    std::vector<cv::Point> pts;

    for(int j=0; j<mask.rows; ++j)
        for(int i=0; i<mask.cols; ++i)
        {
            if(mask.at<unsigned char>(j,i))
            {
                pts.push_back(cv::Point(i,j));
            }
        }

    cv::RotatedRect result1 = cv::fitEllipse(pts);
    cv::ellipse(input, result1, cv::Scalar(0,255,0) ,3  );

    cv::RotatedRect result2 = cv::minAreaRect(pts);
    cv::ellipse(input, result2, cv::Scalar(0,0,255) ,3 );


    // now a third method to fit an ellipse but only the contour of the mask object

    // edges could be extracted with findContours instead which might or might not be better, depending on input images
    cv::Mat magX, absmagx;
    cv::Sobel(mask, magX, CV_32FC1, 1, 0);
    cv::convertScaleAbs( magX, absmagx );

    cv::Mat magY, absmagy;
    cv::Sobel(mask, magY, CV_32FC1, 0, 1);
    cv::convertScaleAbs( magY, absmagy );

    cv::Mat mag = absmagx+absmagy;

    cv::Mat edgeMask = mag > 0;

    cv::imshow("edges",edgeMask);


    std::vector<cv::Point> ptsEdges;

    for(int j=0; j<edgeMask.rows; ++j)
        for(int i=0; i<edgeMask.cols; ++i)
        {
            if(edgeMask.at<unsigned char>(j,i))
            {
                ptsEdges.push_back(cv::Point(i,j));
            }
        }

    cv::RotatedRect result3 = cv::fitEllipse(ptsEdges);
    cv::ellipse(input, result3, cv::Scalar(255,0,0) , 3  );


    cv::namedWindow("input");
    cv::imshow("input", input);
    //cv::imwrite("../outputData/MainBase.png", input);
    cv::waitKey(0);
    return 0;
}

enter image description here

1. green: since we try to fit the ellipse to the whole white region, the best found ellipse is something like the mean ellipse within the region
2. red: not as good as 3 but will give better results if there is no ellipse in the image but another object
3. blue: fitting an ellipse to a real ellipse with some outliers/noise is just the best result ;)

答案 2 :(得分:1)

好的,我明白了。我需要将它转换为轮廓集。代码来自在线示例。

cv::vector<cv::vector<cv::Point> > contours;
cv::findContours(result, contours, cv::RETR_LIST, cv::CHAIN_APPROX_NONE);
// Assuming always returns one contour as the input is binary
cv::RotatedRect box = cv::fitEllipse(contours[0]);
// Draw the ellipse
cv::ellipse(image, box, cv::Scalar(255,0,0));