opencv检测相交点_opencv求解两条直线的交点

假设现在有一个点集,需要拟合出最能够表达点集轮廓的几条直线,并求直线之间的交点。

从点集中拟合直线可以采用的方法:随机抽样一致性(RANSAC),霍夫变换(though transform)

c++ 程序代码

/** @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<:vec4d>& lines, std::vector<: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() << "::crossPointsOfLines: " << "cross points is less than parameter nPoints.";

}

}

参考文献

OpenCV找任意两条直线的交点

OpenCV找直线及直线的交点

随机抽样一致性算法(ransac)

你可能感兴趣的:(opencv检测相交点)