工業相機拍攝的圖像中,因爲攝像質量的限制,圖像中的直線通過處理後,會表現出比較嚴重的鋸齒。在這種狀況下求取直線的傾角(其實就是直線的斜率),若是是直接選取直線的開始點和結束點來計算,或是用opencv自帶的哈夫曼直線方法,都會引發較大的角度誤差,通常會達到好幾度。偏差這麼大,顯然達不到工控要求。後來嘗試採起直線點集作最小二乘擬合,偏差縮小到0.5如下。如下是算法的代碼:算法
//最小二乘擬合計算直線的傾角 int pointCount = pointVect.size(); if (pointCount > 0) { int xCount = 0; int yCount = 0; int xyCount = 0; int xxCount = 0; for (int i = 0; i< pointCount; i++) { xCount += pointVect.at(i).x; yCount += pointVect.at(i).y; xyCount += (pointVect.at(i).x * pointVect.at(i).y); xxCount += (pointVect.at(i).x * pointVect.at(i).x); } double k = (double)(pointCount * xyCount - xCount * yCount) / (double)(pointCount * xxCount - xCount * xCount); double sinValue = - k / (sqrt(1 + k * k)); double radian = asin(sinValue); double pi = 3.1415926535; double angle = radian * 180.0 / pi; }