1. 程式人生 > >圓檢測(續)- RANSAC

圓檢測(續)- RANSAC

繼之前提到的兩種方法之後,這裡再列出基於RANSAC的圓檢測,RANSAC(Random Sample Consensus)隨機抽樣一致性,略不同於霍夫圓變換那種基於投票的策略,這是一種對觀測資料進行最大化模型檢驗的方法。下面來簡單介紹一下它的原理:
1、原理
最小二乘法通常用線上性擬合引數中,但一旦最小二乘法輸入的觀測資料中包含有大量分散的干擾點時,它擬合出來的效果可能並不好,如可能會出現這樣的情況:
least-squares-fit
可以看到,擬合出來的直線與期望有效點之間的重合率不高,也就代表著它的代價函式Cost(m,b)=ni=1|yi(mxi+b)|雖然已經是最小的了,期望(不是概率論裡面的期望)函式的值卻不是最大的。
Ransac的思路是隨機通過幾個點用最小二乘法給出一個假設的直線,然後計算在直線內的inliers和在直線範圍外的outliers。對所有可能的直線中找出inliers數目最多的那個,也就能找到最好的直線。
演算法步驟:


(1) 隨機地抽取出所需要數目的點去擬合模型:
#2points
綠色的點代表取樣的點
(2)用樣本求出模型引數:
fitting
(3)在設定好直線的閾值範圍中區分出inliers和outliers,並求內點佔觀測資料的比:
percentage
重複步驟1-3直到找出置信度最高的模型
RANSAC幾點要注意的:
① 只有outliers%<50%時,得到的模型才是有保證的。
②inliers的閾值δ跟我們期望的模型抗噪能力相關,閾值越大,抗噪能力越弱,通常我們選取3個畫素偏差的高斯模型作為噪聲模型。
③ 重複1-3步驟的次數跟模型的outliers佔比和我們所需要多高的置信度有關,可以用下面公式表示:

S=
log(1P)log(1pk)

其中,S是所需最小試驗的次數,P是置信度,p是inliers佔的百分比數,k是隨機取樣的數目。

2、實際例子
這裡用網友Micka的程式碼來舉例:

#include <opencv2/opencv.hpp>
#include <ctime>

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; } int main() { clock_t starttime, endtime; starttime = clock(); cv::Mat color = cv::imread("1.jpg"); cv::Mat gray; // convert to grayscale // you could load as grayscale if you want, but I used it for (colored) output too cv::cvtColor(color, gray, CV_BGR2GRAY); cv::Mat mask; float canny1 = 100; float canny2 = 20; cv::Mat canny; cv::Canny(gray, canny, canny1,canny2); //cv::imshow("canny",canny); mask = canny; 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 = 10; // 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 printf("%d\n", maxNrOfIterations); 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; } } std::cout << "bestCirclePerc: " << bestCirclePercentage << std::endl; std::cout << "bestCircleRadius: " << bestCircleRadius << std::endl; // draw if good circle was found if(bestCirclePercentage >= minCirclePercentage) if(bestCircleRadius >= minRadius); cv::circle(color, bestCircleCenter,bestCircleRadius, cv::Scalar(255,255,0),1); std::cout << "the used time is: "<<clock()-starttime <<std::endl; cv::imshow("output",color); cv::imshow("mask",mask); //cv::imwrite("../outputData/1_circle_normalized.png", normalized); cv::waitKey(0); return 0; }

他的思路是:
1. 用Canny提取邊緣點, 用distanceTransform得到距離邊緣點的距離圖;
2. 隨機抽取三個不同的點解方程,三個方程三個未知數,有解;
3. 將2得到的圓周上的點與1中對應位置的點進行比較,看是否屬於inliers,隨後輸出百分比;
4. 找出最大百分比對應的圓就是RANSAC得到的圓。

3、比較霍夫變換跟RANSAC:
魯棒性來說,霍夫變換要穩定一點;
速度來說,霍夫變換要快,而且其所需時間變化不大,100ms左右能夠完成;
RANSAC跟HoughTranform的引數調節都很麻煩,相對來說,霍夫變換更加簡單一點;
RANSAC擬合的程度可能會更高,但受到outliers%<50%這個條件限制。
所以綜合來說,HoughTransform的應用更廣,效率更高,某些情況下,它不能很好地找到合理的圓,這時可以將RANSAC加進去進行優化,可能精度會高很多。

參考資料: RANSAC Kavita Bala