求平面两直线的交点,两直线段的交点
//////////////////////////////////////////////////////////////////////////////////////////////////////// //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; }
int crossPointsOfTwoLines(const Eigen::Vector2f &p0, const Eigen::Vector2f &p1, const Eigen::Vector2f &p2, const Eigen::Vector2f &p3, Eigen::Vector2f &cross_pt) { auto A1 = p1.y() - p0.y(); auto B1 = p0.x() - p1.x(); auto C1 = A1 * p0.x() + B1 * p0.y(); auto A2 = p3.y() - p2.y(); auto B2 = p2.x() - p3.x(); auto C2 = A2 * p2.x() + B2 * p2.y(); auto denominator = A1 * B2 - A2 * B1; // 如果分母为0 则平行或共线, 不相交 if (denominator == 0) { return -1; } cross_pt.x() = (B2 * C1 - B1 * C2) / denominator; cross_pt.y() = (A1 * C2 - A2 * C1) / denominator; // // 2 判断交点是否在两条线段上 // auto rx0 = (cross_pt.x() - p0.x()) / (p1.x() - p0.x()); // auto ry0 = (cross_pt.y() - p0.y()) / (p1.y() - p0.y()); // auto rx1 = (cross_pt.x() - p2.x()) / (p3.x() - p2.x()); // auto ry1 = (cross_pt.y() - p2.y()) / (p3.y() - p2.y()); // if ( // // 交点在线段1上 // ((rx0 >= 0 && rx0 <= 1) || (ry0 >= 0 && ry0 <= 1)) && // // 且交点也在线段2上 // ((rx1 >= 0 && rx1 <= 1) || (ry1 >= 0 && ry1 <= 1))) // { // return 1; // } // else // { // return 0; // } return 0; }