基于Opencv的卡尺找线

  1. 首先, 边缘点的提取主要学习的是VisionPro的CogCaliperTool工具的原理。
  2. 之后,获得边缘点集之后,用RANSAC算法把异常点筛选出来。RANSAC的算法原理参考RANSAC算法(附RANSAC直线拟合C++与Python版本),有做小小地修改,根据以下公式计算迭代次数: k = l o g ( 1 − p ) l o g ( 1 − w n ) k=\frac{log(1-p)}{log(1-w^n)} k=log(1wn)log(1p)
void CCaliperGraphics::RansacLineFiler(const vector<Point2d>& points,vector<Point2d>&vpdExceptPoints, double sigma)
{
	unsigned int n = points.size();

	if (n < 2)
	{
		return;
	}

	RNG random;
	double bestScore = -1.;
	vector<Point2d>vpdTemp;
	int iterations = log(1 - 0.99) / (log(1 - (1.00 / n)))*10;
	
	for (int k = 0; k < iterations; k++)
	{
		int i1 = 0, i2 = 0;
		while (i1 == i2)
		{
			i1 = random(n);
			i2 = random(n);
		}
		const cv::Point2d& p1 = points[i1];
		const cv::Point2d& p2 = points[i2];
		Point2d vectorP21 = p2 - p1;
		vectorP21 *= 1. / norm(vectorP21);
		double score = 0;
		vpdTemp.clear();
		for (int i = 0; i < n; i++)
		{
			Point2d vectorPi1 = points[i] - p1;
			double d = vectorPi1.y * vectorP21.x - vectorPi1.x * vectorP21.y;//calculate the cos�� of the two vectors.
			if (fabs(d) < sigma)
			{
				score += 1;
			}
			else
			{
				vpdTemp.push_back(points[i]);
			}
		}
		if (score > bestScore)
		{
			bestScore = score;
			vpdExceptPoints = vpdTemp;
		}
	}
}
  1. 最后,用fitLine去做直线拟合。
    最终效果:
    基于Opencv的卡尺找线_第1张图片
    用ImageWatch放大图片,
    基于Opencv的卡尺找线_第2张图片

用opencv的trackbar和mouse事件简易地实现了了卡尺的拖动和编辑:

卡尺的实现比较麻烦的是采样方向,我的定义如下图,根据向量的夹角公式计算线段与X轴的夹角,同样反过来,只要有线段中心,方向以及长度,就能计算出线段的起点和终点。

static double GetAngleVecWithX(Point2d p1,Point2d p2)
{
    if (p1 == p2)
    {
        return -1;
    }
    Point2d vector = p2 - p1;
    if (vector.x == 0)
    {
        if (vector.y > 0)
        {
            return 90;
        }
        else
        {
            return -90;
        }
    }
    double angle = to_degree(acos(pow(vector.x, 2) / (vector.x * sqrt(pow(vector.x, 2) + pow(vector.y, 2)))));
    if (p1.y > p2.y)
    {
        angle = -angle;
    }


    return  angle;
}

基于Opencv的卡尺找线_第3张图片
此外,我觉得自带的drawArrow不是很好用,就利用RotateRect重新写了一个。画十字架也是类似的原理。

static void DrawArrow(Mat& inputMat, Point2d p1, Point2d p2, int dSize, Scalar color, int nThickness = 1)
{
    if (inputMat.empty())
    {
        return;
    }
    double dK = ((double)p2.y - (double)p1.y) / ((double)p2.x - (double)p1.x);
    double dAngle = atan(dK) * 180 / PI;
    line(inputMat, p1, p2, color, nThickness, LINE_AA);
    RotatedRect rotateRect(p2, Size(dSize, dSize * 0.5), dAngle);
    Point2f rectPoints[4];
    rotateRect.points(rectPoints);
    if ((dAngle >= 0 && p1.x <= p2.x) || (dAngle < 0 && p1.x <= p2.x))
    {
        line(inputMat, p2, rectPoints[0], color, nThickness, LINE_AA);
        line(inputMat, p2, rectPoints[1], color, nThickness, LINE_AA);
    }
    else
    {
        line(inputMat, p2, rectPoints[2], color, nThickness, LINE_AA);
        line(inputMat, p2, rectPoints[3], color, nThickness, LINE_AA);
    }
}

基于opencv的卡尺找线 源码

卡尺找圆也是一样的原理,效果在这里基于opencv的卡尺找圆

你可能感兴趣的:(Opencv,opencv)