我正在尋找一個幫助函數來計算OpenCV中的兩條線的交點。我搜索了API文檔,但找不到有用的資源。OpenCV二維線相交幫助函數
OpenCV中是否有基本的幾何輔助函數用於線/線段上的相交/距離計算?
我正在尋找一個幫助函數來計算OpenCV中的兩條線的交點。我搜索了API文檔,但找不到有用的資源。OpenCV二維線相交幫助函數
OpenCV中是否有基本的幾何輔助函數用於線/線段上的相交/距離計算?
有在OpenCV的API沒有函數來計算線的交點,但距離是:
cv::Point2f start, end;
double length = cv::norm(end - start);
如果您需要一段代碼,然後在這裏計算的直線相交處是:
// Finds the intersection of two lines, or returns false.
// The lines are defined by (o1, p1) and (o2, p2).
bool intersection(Point2f o1, Point2f p1, Point2f o2, Point2f p2,
Point2f &r)
{
Point2f x = o2 - o1;
Point2f d1 = p1 - o1;
Point2f d2 = p2 - o2;
float cross = d1.x*d2.y - d1.y*d2.x;
if (abs(cross) < /*EPS*/1e-8)
return false;
double t1 = (x.x * d2.y - x.y * d2.x)/cross;
r = o1 + d1 * t1;
return true;
}
這是我對EmguCV(C#)的實現。
static PointF GetIntersection(LineSegment2D line1, LineSegment2D line2)
{
double a1 = (line1.P1.Y - line1.P2.Y)/(double)(line1.P1.X - line1.P2.X);
double b1 = line1.P1.Y - a1 * line1.P1.X;
double a2 = (line2.P1.Y - line2.P2.Y)/(double)(line2.P1.X - line2.P2.X);
double b2 = line2.P1.Y - a2 * line2.P1.X;
if (Math.Abs(a1 - a2) < double.Epsilon)
throw new InvalidOperationException();
double x = (b2 - b1)/(a1 - a2);
double y = a1 * x + b1;
return new PointF((float)x, (float)y);
}
我在Python實現(使用numpy的陣列) 與第1行= [[X1,Y1],[X2,Y2]] & LINE2 = [[X1,Y1],[X2,Y2]]
def getIntersection(line1, line2):
s1 = numpy.array(line1[0])
e1 = numpy.array(line1[1])
s2 = numpy.array(line2[0])
e2 = numpy.array(line2[1])
a1 = (s1[1] - e1[1])/(s1[0] - e1[0])
b1 = s1[1] - (a1 * s1[0])
a2 = (s2[1] - e2[1])/(s2[0] - e2[0])
b2 = s2[1] - (a2 * s2[0])
if abs(a1 - a2) < sys.float_info.epsilon:
return False
x = (b2 - b1)/(a1 - a2)
y = a1 * x + b1
return (x, y)
x1,y1&x2,y2必須像float(0.0,1.0)和(2.0,1.0)一樣浮動 – afiah
由於(si [0] - ei [0]) –
使用齊次座標,使您的生活更輕鬆:
cv::Mat intersectionPoint(const cv::Mat& line1, const cv::Mat& line2)
{
// Assume we receive lines as l=(a,b,c)^T
assert(line1.rows == 3 && line1.cols = 1
&& line2.rows == 3 && line2.cols == 1);
// Point is p=(x,y,w)^T
cv::Mat point = line1.cross(line2);
// Normalize so it is p'=(x',y',1)^T
if(point.at<double>(2,0) != 0)
point = point * (1.0/point.at<double>(2,0));
}
注意,如果第三個座標爲0的線是平行的,沒有解決方案,R 2,但P中^ 2,然後POIN t表示2D中的方向。
「點」的形狀是什麼?這個函數沒有返回任何東西。 – Geoff
查找線相交的算法在後How do you detect where two line segments intersect?
以下是我的OpenCV C++實現被描述得非常好。它使用相同的符號,如上面的帖子
bool getIntersectionPoint(Point a1, Point a2, Point b1, Point b2, Point & intPnt){
Point p = a1;
Point q = b1;
Point r(a2-a1);
Point s(b2-b1);
if(cross(r,s) == 0) {return false;}
double t = cross(q-p,s)/cross(r,s);
intPnt = p + t*r;
return true;
}
double cross(Point v1,Point v2){
return v1.x*v2.y - v1.y*v2.x;
}
只是爲了澄清。您的示例中的線條是由兩個點定義的,還是作爲點和方向矢量定義的? – tisch
它們由兩點來定義。函數內計算的d1和d2是方向向量。 –
感謝幫手功能! – tisch