Skip to content Skip to sidebar Skip to footer

Opencv - Ellipse Contour Not Fitting Correctly

I want to draw contours around the concentric ellipses shown in the image appended below. I am not getting the expected result. I have tried the following steps: Read the Image

Solution 1:

Algorithm can be simple:

  1. Convert RGB to HSV, split and working with a V channel.

  2. Threshold for delete all color lines.

  3. HoughLinesP for delete non color lines.

  4. dilate + erosion for close holes in ellipses.

  5. findContours + fitEllipse.

Result:

Result image

With new image (added black curve) my approach do not works. It seems that you need to use Hough ellipse detection instead "findContours + fitEllipse". OpenCV don't have implementation but you can find it here or here.

If you don't afraid C++ code (for OpenCV library C++ is more expressive) then:

cv::Mat rgbImg = cv::imread("sqOOE.jpg", cv::IMREAD_COLOR);

cv::Mat hsvImg;
cv::cvtColor(rgbImg, hsvImg, cv::COLOR_BGR2HSV);

std::vector<cv::Mat> chans;
cv::split(hsvImg, chans);
cv::threshold(255 - chans[2], chans[2], 200, 255, cv::THRESH_BINARY);

std::vector<cv::Vec4i> linesP;
cv::HoughLinesP(chans[2], linesP, 1, CV_PI/180, 50, chans[2].rows / 4, 10);
for (auto l : linesP)
{
    cv::line(chans[2], cv::Point(l[0], l[1]), cv::Point(l[2], l[3]), cv::Scalar::all(0), 3, cv::LINE_AA);
}
cv::dilate(chans[2], chans[2], cv::getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3)), cv::Point(-1, -1), 4);
cv::erode(chans[2], chans[2], cv::getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3)), cv::Point(-1, -1), 3);

std::vector<std::vector<cv::Point> > contours;
std::vector<cv::Vec4i> hierarchy;
cv::findContours(chans[2], contours, hierarchy, cv::RETR_TREE, cv::CHAIN_APPROX_SIMPLE);

for (size_t i = 0; i < contours.size(); i++)
{
    if (contours[i].size() > 4)
    {
        cv::ellipse(rgbImg, cv::fitEllipse(contours[i]), cv::Scalar(255, 0, 255), 2);
    }
}

cv::imshow("rgbImg", rgbImg);
cv::waitKey(0);

Post a Comment for "Opencv - Ellipse Contour Not Fitting Correctly"