Opencv學習筆記-----求取兩條直線的交點座標

求取二直線交點(基於OpenCv)

理解了兩條直線的叉乘之後用opencv學習了一個能求取兩條直線交點的代碼,而且發現很多人都遇到求直線交點的問題,然後就把我學習到的代碼貼出來,希望能對你有所幫助

代碼如下:

#include <opencv2\highgui\highgui.hpp>
#include <opencv2\opencv.hpp>
using namespace std;
using namespace cv;

//****************************************************************************************
//  求二條直線的交點的公式
//  有如下方程    a1*x+b1*y=c1
//                a2*x+b2*y=c2
//                x= | c1 b1|  / | a1 b1 |      y= | a1 c1| / | a1 b1 |
//                   | c2 b2|  / | a2 b2 |         | a2 c2| / | a2 b2 |
//
//   a1= (L1.pEnd.y-L1.pStart.y)   
//   b1= (L1.pEnd.x-L1.pStart.x)
//   c1= L1.pStart.x*(L1.pEnd.y-L1.pStart.y)-(L1.pEnd.x-L1.pStart.x)*L1.pStart.y
//   a2= (L2.pEnd.y-L2.pStart.y)   
//   b2= (L2.pEnd.x-L2.pStart.x)
//   c2= L2.pStart.x*(L2.pEnd.y-L2.pStart.y)-(L2.pEnd.x-L2.pStart.x)*L2.pStart.y  
//定義兩個結構體方便理解
struct PT
{
	int x;
	int y;
};
struct LINE
{
	PT pStart;
	PT pEnd;
};
Point CrossPoint(const LINE *line1, const LINE *line2)
{
	//    if(!SegmentIntersect(line1->pStart, line1->pEnd, line2->pStart, line2->pEnd))
	//    {// segments not cross   
	//        return 0;
	//    }
	Point pt;
	// line1's cpmponent
	double X1 = line1->pEnd.x - line1->pStart.x;//b1
	double Y1 = line1->pEnd.y - line1->pStart.y;//a1
	// line2's cpmponent
	double X2 = line2->pEnd.x - line2->pStart.x;//b2
	double Y2 = line2->pEnd.y - line2->pStart.y;//a2
	// distance of 1,2
	double X21 = line2->pStart.x - line1->pStart.x;
	double Y21 = line2->pStart.y - line1->pStart.y;
	// determinant
	double D = Y1*X2 - Y2*X1;// a1b2-a2b1
	// 
	if (D == 0) return 0;
	// cross point
	pt.x = (X1*X2*Y21 + Y1*X2*line1->pStart.x - Y2*X1*line2->pStart.x) / D;
	// on screen y is down increased ! 
	pt.y = -(Y1*Y2*X21 + X1*Y2*line1->pStart.y - X2*Y1*line2->pStart.y) / D;
	// segments intersect.
	if ((abs(pt.x - line1->pStart.x - X1 / 2) <= abs(X1 / 2)) &&
		(abs(pt.y - line1->pStart.y - Y1 / 2) <= abs(Y1 / 2)) &&
		(abs(pt.x - line2->pStart.x - X2 / 2) <= abs(X2 / 2)) &&
		(abs(pt.y - line2->pStart.y - Y2 / 2) <= abs(Y2 / 2)))
	{
		return pt;
	}
	return 0;
}
int main()
{
	LINE line1, line2;
	line1.pStart.x = 0;
	line1.pStart.y = 0;
	line1.pEnd.x = 2;
	line1.pEnd.y = 2;

	line2.pStart.x = 0;
	line2.pStart.y = 2;
	line2.pEnd.x = 2;
	line2.pEnd.y = 0;

	Point cross = CrossPoint(&line1, &line2);
	cout << "CrossPoint: " << "(" << cross.x << "," << cross.y << ")" << endl;
	system("pause");
	return 0;
}
Line1、Line2和交點如圖:

代碼運行結果:


求出來預期的(1,1)交點。



鄙人剛入門Opencv才疏學淺,尚有不足還望不惜賜教。




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章