opencv求解两条直线的交点

本文探讨了如何使用OpenCV找到点集拟合的直线交点,包括通过点斜式、通用直线表达法和矩阵求解三种思路。在处理垂直直线时,文章提到了避免斜率无穷大问题的策略,并提供了相关参考文献。
摘要由CSDN通过智能技术生成

假设现在有一个点集,需要拟合出最能够表达点集轮廓的几条直线,并求直线之间的交点。
从点集中拟合直线可以采用的方法:随机抽样一致性(RANSAC),霍夫变换(though transform)

思路1

利用点斜式表达直线,然后求解两条直线组成的方程组。
{ y = k 1 ∗ x + b 1 y = k 2 ∗ x + b 2 \begin{cases} y = k1 * x + b1 \\ y = k2 * x + b2 \end{cases} { y=k1x+b1y=k2x+b2

  • 缺点
    通过比较两条直线的斜率来判断两条直线是否平行,但是直线垂直时,斜率无穷大,无法比较两条直线。
	/** @brief 计算直线的交点
	@param lines 直线:Vec4d=(vx, vy, x0, y0), where (vx, vy) is a normalized vector collinear to the line and (x0, y0) is a point on the line.
	@param crossPoints 保存直线的交点
	@param mask 掩膜
	*/
	void crossPointsOfLines(std::vector<cv::Vec4d>& lines, std::vector<cv::Point2f> &crossPoints, int nPoints, cv::Mat& mask)
	{
   
	crossPoints.clear();
	for (int i = 0; i < lines.size() && crossPoints.size() < nPoints; i++)
	{
   
		for (int j = i + 1; j < lines.size() && crossPoints.size() < nPoints; j++)
		{
   

			float ka = (float)lines.at(i)[1] / float(lines.at(i)[0] + 0.000001f);//slope of LineA 
			float kb = (float)lines.at(j)[1] / float(lines.at(j)[0] + 0.000001f);//slope of LineB
			//if (std::abs(std::abs(ka) - std::abs(kb)) > 1.0) //two lines are not probably parallel
			if ((std::abs(ka) > 1) && (std::abs(kb) < 1) || (std::abs(ka) < 1) && (std::abs(kb) > 1))//two lines are not probably parallel
			{
   
				cv::Point2d ptA(lines.at(i)[2], lines.at(i)[3]);
				cv::Point2d ptB(lines.at(j)[2], lines.at(j)[3]);
				cv::Point2f crossPoint;
				crossPoint.x = float(ka*ptA.x - ptA.y - kb*ptB.x + ptB.y) / float(ka - kb);
				crossPoint.y = float(ka*kb*(ptA.x - ptB.x) - kb*ptA.y + ka*ptB.y) / float(ka - kb);
				crossPoints.push_back(crossPoint);
#ifdef _DEBUG
				cv::circle(mask, crossPoint, 2, cv::Scalar(0, 0, 255), -1, cv::FILLED);
#endif
			}

		}
	}

	if (crossPoints.size() < nPoints){
   
		LOG(ERROR) << type
  • 4
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值