//////////////////////////////////////////////////////////////////////////////////////////////////////// //aa, bb为一条线段两端点 cc, dd为另一条线段的两端点 相交返回true, 不相交返回false bool LinesProject::getCrossPoint(const PointType& aa, const PointType& bb, const PointType& cc, const PointType& dd, PointType& crossPoint) { if (max(aa.x, bb.x)<min(cc.x, dd.x)) { return false; } if (max(aa.y, bb.y)<min(cc.y, dd.y)) { return false; } if (max(cc.x, dd.x)<min(aa.x, bb.x)) { return false; } if (max(cc.y, dd.y)<min(aa.y, bb.y)) { return false; } if (mult(cc, bb, aa)*mult(bb, dd, aa)<0) { return false; } if (mult(aa, dd, cc)*mult(dd, bb, cc)<0) { return false; } float a1 = bb.y - aa.y; float b1 = aa.x - bb.x; float c1 = aa.x*bb.y - bb.x*aa.y; float a2 = dd.y - cc.y; float b2 = cc.x - dd.x; float c2 = cc.x*dd.y - dd.x*cc.y; float det = a1*b2 - a2*b1; if (det == 0) return false; //说明两线段平行 crossPoint.x = (c1*b2 - c2*b1) / det; crossPoint.y = (a1*c2 - a2*c1) / det; return true; }
//getCrossPoint 计算两直线交点 int getCrossPoint(cv::Point& A, cv::Point& B, cv::Point& C, cv::Point& D, cv::Point& crosspoint) { double m = (B.y - A.y)*(C.x - D.x) - (D.y - C.y)*(A.x- B.x); if (m == 0) { //平行不相交 crosspoint.x = 0; crosspoint.y = 0; return -1; } else { crosspoint.x = ((D.x * C.y - C.x * D.y)*(A.x - B.x) - (B.x * A.y - A.x * B.y)*(C.x - D.x)) / m; crosspoint.y = ((B.x * A.y - A.x * B.y)*(D.y - C.y) - (D.x * C.y - C.x * D.y)*(B.y - A.y)) / m; } return 0; }