使用OpenCV检测带噪声的部分圆形

7
我尝试使用OpenCV HoughCircles和findContours来检测圆形,但是这些算法要么不能找到足够完整的圆形,要么图像中有太多噪点。或者我们对OpenCV还不够熟悉。这是我需要找到圆形的图像。您应该能够用肉眼清楚地看到它,但是没有一个圆形检测算法似乎起作用。我发现应用中值滤波器可以清除大部分噪音,但即使经过中值滤波,算法仍然无法检测到圆形。
注意:我甚至查看并尝试了此处的解决方案,因此不是那个问题的重复: Detect semicircle in OpenCV 有什么想法吗?这是我需要使用的原始图像。
此外,我想检测圆形的原因是我想在仅使用属于圆形一部分的点进行计算。
原始图像: http://www.collegemobile.com/IMG_2021.JPG 中值滤波后的图像: http://www.collegemobile.com/IMG_2022.JPG

你能假设图像中总是恰好有一个圆吗? - Micka
图片链接已失效。 - user513951
3个回答

17

给您:

我使用了来自Detect semi-circle in opencv的第二个答案,并进行了一些修改。这个版本现在能够检测到最佳的半圆(就完整度而言)。

但是首先,我想告诉您为什么链接到Detect semi-circle in opencv stack overflow question的被接受的答案在这里不起作用(除了噪音):你只有圆的边缘!正如那个问题所述,HoughCircle函数在内部计算梯度,这对于棱角分明的图像效果不好。

但现在我是怎么做的:

使用这个作为输入(您自己的中值滤波图像(我只是裁剪了一下):

enter image description here

首先我“规范化”了图像。我只是拉伸了值,使最小值为0,最大值为255,导致了这个结果:(也许一些真正的对比度增强更好)

enter image description here

之后,我使用一些固定阈值计算该图像的阈值(您可能需要编辑它并找到一种动态选择阈值的方法!更好的对比度增强可能有所帮助)

enter image description here

从这个图像中,我使用了一些简单的RANSAC圆检测(与链接的半圆检测问题中我的答案非常相似),给出了这个结果作为最佳半圆:

enter image description here

这是代码:

int main()
{
    //cv::Mat color = cv::imread("../inputData/semi_circle_contrast.png");
    cv::Mat color = cv::imread("../inputData/semi_circle_median.png");
    cv::Mat gray;

    // convert to grayscale
    cv::cvtColor(color, gray, CV_BGR2GRAY);

    // now map brightest pixel to 255 and smalles pixel val to 0. this is for easier finding of threshold
    double min, max;
    cv::minMaxLoc(gray,&min,&max);
    float sub = min;
    float mult = 255.0f/(float)(max-sub);
    cv::Mat normalized = gray - sub;
    normalized = mult * normalized;
    cv::imshow("normalized" , normalized);
    //--------------------------------


    // now compute threshold
    // TODO: this might ne a tricky task if noise differs...
    cv::Mat mask;
    //cv::threshold(input, mask, 0, 255, CV_THRESH_BINARY | CV_THRESH_OTSU);
    cv::threshold(normalized, mask, 100, 255, CV_THRESH_BINARY);



    std::vector<cv::Point2f> edgePositions;
    edgePositions = getPointPositions(mask);

    // create distance transform to efficiently evaluate distance to nearest edge
    cv::Mat dt;
    cv::distanceTransform(255-mask, dt,CV_DIST_L1, 3);

    //TODO: maybe seed random variable for real random numbers.

    unsigned int nIterations = 0;

    cv::Point2f bestCircleCenter;
    float bestCircleRadius;
    float bestCirclePercentage = 0;
    float minRadius = 50;   // TODO: ADJUST THIS PARAMETER TO YOUR NEEDS, otherwise smaller circles wont be detected or "small noise circles" will have a high percentage of completion

    //float minCirclePercentage = 0.2f;
    float minCirclePercentage = 0.05f;  // at least 5% of a circle must be present? maybe more...

    int maxNrOfIterations = edgePositions.size();   // TODO: adjust this parameter or include some real ransac criteria with inlier/outlier percentages to decide when to stop

    for(unsigned int its=0; its< maxNrOfIterations; ++its)
    {
        //RANSAC: randomly choose 3 point and create a circle:
        //TODO: choose randomly but more intelligent, 
        //so that it is more likely to choose three points of a circle. 
        //For example if there are many small circles, it is unlikely to randomly choose 3 points of the same circle.
        unsigned int idx1 = rand()%edgePositions.size();
        unsigned int idx2 = rand()%edgePositions.size();
        unsigned int idx3 = rand()%edgePositions.size();

        // we need 3 different samples:
        if(idx1 == idx2) continue;
        if(idx1 == idx3) continue;
        if(idx3 == idx2) continue;

        // create circle from 3 points:
        cv::Point2f center; float radius;
        getCircle(edgePositions[idx1],edgePositions[idx2],edgePositions[idx3],center,radius);

        // inlier set unused at the moment but could be used to approximate a (more robust) circle from alle inlier
        std::vector<cv::Point2f> inlierSet;

        //verify or falsify the circle by inlier counting:
        float cPerc = verifyCircle(dt,center,radius, inlierSet);

        // update best circle information if necessary
        if(cPerc >= bestCirclePercentage)
            if(radius >= minRadius)
        {
            bestCirclePercentage = cPerc;
            bestCircleRadius = radius;
            bestCircleCenter = center;
        }

    }

    // draw if good circle was found
    if(bestCirclePercentage >= minCirclePercentage)
        if(bestCircleRadius >= minRadius);
        cv::circle(color, bestCircleCenter,bestCircleRadius, cv::Scalar(255,255,0),1);


        cv::imshow("output",color);
        cv::imshow("mask",mask);
        cv::waitKey(0);

        return 0;
    }

利用这些帮助函数:

float verifyCircle(cv::Mat dt, cv::Point2f center, float radius, std::vector<cv::Point2f> & inlierSet)
{
 unsigned int counter = 0;
 unsigned int inlier = 0;
 float minInlierDist = 2.0f;
 float maxInlierDistMax = 100.0f;
 float maxInlierDist = radius/25.0f;
 if(maxInlierDist<minInlierDist) maxInlierDist = minInlierDist;
 if(maxInlierDist>maxInlierDistMax) maxInlierDist = maxInlierDistMax;

 // choose samples along the circle and count inlier percentage
 for(float t =0; t<2*3.14159265359f; t+= 0.05f)
 {
     counter++;
     float cX = radius*cos(t) + center.x;
     float cY = radius*sin(t) + center.y;

     if(cX < dt.cols)
     if(cX >= 0)
     if(cY < dt.rows)
     if(cY >= 0)
     if(dt.at<float>(cY,cX) < maxInlierDist)
     {
        inlier++;
        inlierSet.push_back(cv::Point2f(cX,cY));
     }
 }

 return (float)inlier/float(counter);
}


inline void getCircle(cv::Point2f& p1,cv::Point2f& p2,cv::Point2f& p3, cv::Point2f& center, float& radius)
{
  float x1 = p1.x;
  float x2 = p2.x;
  float x3 = p3.x;

  float y1 = p1.y;
  float y2 = p2.y;
  float y3 = p3.y;

  // PLEASE CHECK FOR TYPOS IN THE FORMULA :)
  center.x = (x1*x1+y1*y1)*(y2-y3) + (x2*x2+y2*y2)*(y3-y1) + (x3*x3+y3*y3)*(y1-y2);
  center.x /= ( 2*(x1*(y2-y3) - y1*(x2-x3) + x2*y3 - x3*y2) );

  center.y = (x1*x1 + y1*y1)*(x3-x2) + (x2*x2+y2*y2)*(x1-x3) + (x3*x3 + y3*y3)*(x2-x1);
  center.y /= ( 2*(x1*(y2-y3) - y1*(x2-x3) + x2*y3 - x3*y2) );

  radius = sqrt((center.x-x1)*(center.x-x1) + (center.y-y1)*(center.y-y1));
}



std::vector<cv::Point2f> getPointPositions(cv::Mat binaryImage)
{
 std::vector<cv::Point2f> pointPositions;

 for(unsigned int y=0; y<binaryImage.rows; ++y)
 {
     //unsigned char* rowPtr = binaryImage.ptr<unsigned char>(y);
     for(unsigned int x=0; x<binaryImage.cols; ++x)
     {
         //if(rowPtr[x] > 0) pointPositions.push_back(cv::Point2i(x,y));
         if(binaryImage.at<unsigned char>(y,x) > 0) pointPositions.push_back(cv::Point2f(x,y));
     }
 }

 return pointPositions;
}

编辑:还有一件事:速度表现高度取决于maxNrOfIterations。如果这很重要,你真的应该了解何时停止RANSAC。因此,您可能能够早期确定找到的圆是正确的,并且不需要测试其他任何一个;)


基于直方图分析的技术最终会更快,也许更容易检测到圆形? - LandonZeKepitelOfGreytBritn
@trilolil:可能是的,你有什么特别的想法吗? - Micka
1
嗯,我只知道基于直方图、排序、中位数和方差等方面有一些可能性...据我所听,使用这种技术的人并没有真正想出什么新东西,他们只是凭借多年的经验来假装自己懂得统计学和“专业知识”。除此之外,最近我还发现了这个链接:http://paper.ijcsns.org/07_book/201208/20120807.pdf(不确定这是否相关)。 - LandonZeKepitelOfGreytBritn

1
我使用最小二乘算法来拟合2D点上的圆。我将该算法应用于Micka的阈值图像,但先使用形态学开运算方法去除离群值。
Mat img;
img = imread("iokqh.png");

if (img.empty())
{
    cout << "Could not open image..." << endl;
    return -1;
}

cvtColor(img, img, COLOR_BGR2GRAY);

int dilation_type = 0;
int dilation_elem = 0;

if (dilation_elem == 0) { dilation_type = MORPH_RECT; }
else if (dilation_elem == 1) { dilation_type = MORPH_CROSS; }
else if (dilation_elem == 2) { dilation_type = MORPH_ELLIPSE; }

int size = 1;

Mat element = getStructuringElement(dilation_type, Size(2 * size + 1, 2 * size + 1), Point(size, size));
morphologyEx(img, img, MORPH_OPEN, element);

vector<Point2f> points;
for (int x = 0; x < img.cols; x++)
{
    for (int y = 0; y < img.rows; y++)
    {
        if (img.at<uchar>(y, x) > 0)
        {
            points.push_back(cv::Point2f(x, y));
        }
    }
}

//// Least Square Algorithm 

float xn = 0, xsum = 0;
float yn = 0, ysum = 0;
float n = points.size();

for (int i = 0; i < n; i++)
{
    xsum = xsum + points[i].x;
    ysum = ysum + points[i].y;
}

xn = xsum / n;
yn = ysum / n;

float ui = 0;
float vi = 0;
float suu = 0, suuu = 0;
float svv = 0, svvv = 0;
float suv = 0;
float suvv = 0, svuu = 0;

for (int i = 0; i < n; i++)
{
    ui = points[i].x - xn;
    vi = points[i].y - yn;

    suu = suu + (ui * ui);
    suuu = suuu + (ui * ui * ui);

    svv = svv + (vi * vi);
    svvv = svvv + (vi * vi * vi);

    suv = suv + (ui * vi);

    suvv = suvv + (ui * vi * vi);
    svuu = svuu + (vi * ui * ui);
}

cv::Mat A = (cv::Mat_<float>(2, 2) <<
    suu, suv,
    suv, svv);

cv::Mat B = (cv::Mat_<float>(2, 1) <<
    0.5*(suuu + suvv),
    0.5*(svvv + svuu));

cv::Mat abc;
cv::solve(A, B, abc);

float u = abc.at<float>(0);
float v = abc.at<float>(1);

float x = u + xn;
float y = v + yn;

float alpha = u * u + v * v + ((suu + svv) / n);
float r = sqrt(alpha);

////

cvtColor(img, img, COLOR_GRAY2BGR);

// Draw circle
circle(img, Point(x, y), r, Scalar(255, 0, 0), 1, 8, 0);
imshow("window", img);
waitKey(0);

以下是结果: 在此输入图像描述


0

嗯......如果你稍微增强一下图像的对比度,就会得到这个结果

enter image description here

我认为大多数算法都会遇到困难。由于实际圆形相对于其他(可能是)不需要的东西非常明亮,因此可以考虑在值约为200的某处进行阈值处理。


只需要圆圈,不需要其他噪音。听起来噪音是问题的原因,我早就猜到了。 - Chad Jones
它实际上被称为“阈值”,这里有一个例子 http://www.tutorialspoint.com/java_dip/basic_thresholding.htm - Mark Setchell

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接