اگر پاره خط باشه و شما 2 نقطه داشته باشید از قطعه کد زیر استفاده کنید.
double Dot(cv::Point a, cv::Point b) {
return (a.x*b.x) + (a.y*b.y);
}
double PerpDot(cv::Point a, cv::Point b) {
return (a.y*b.x) - (a.x*b.y);
}
bool BhLineIntersection4( const Point& A1, const Point& A2, const Point& B1, const Point& B2, Point &intersection)
{
Point a;
a.x = A2.x - A1.x;
a.y = A2.y - A1.y;
Point b;
b.x = B2.x - B1.x;
b.y = B2.y - B1.y;
int f = PerpDot(a,b);
if(!f) // lines are parallel
return false;
Point c;
c.x = B2.x - A2.x;
c.y = B2.y - A2.y;
int aa = PerpDot(a,c);
int bb = PerpDot(b,c);
if(f < 0)
{
if(aa > 0) return false;
if(bb > 0) return false;
if(aa < f) return false;
if(bb < f) return false;
}
else
{
if(aa < 0) return false;
if(bb < 0) return false;
if(aa > f) return false;
if(bb > f) return false;
}
float out = 1.0 - ((float)aa / f);
intersection = Point( ((B2.x - B1.x) * out) + B1.x ,((B2.y - B1.y) * out) + B1.y);
return true;
}
و اگر خطوط به صورت یک نقطه و زاویه خط باشه از روش زیر استفاده کنید.
CvPoint linesInterSectionPoint(CvPoint p1,CvPoint p2,float deg1,float deg2)
{
float m1 = tan( deg1);
float m2 = tan( deg2);
double x,y;
x = (m1* p1.x - m2 * p2.x + (p2.y - p1.y)) / (m1-m2) ;
y = m1 * (x - p1.x) + p1.y ;
return cvPoint(cvRound(x),cvRound(y));
}