工业相机拍摄的图像中,由于摄像质量的限制,图像中的直线经过处理后,会表现出比较严重的锯齿。在这种情况下求取直线的倾角(其实就是直线的斜率),如果是直接选取直线的开始点和结束点来计算,或是用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;
}