I was looking for a helper function to calculate the intersection of two lines in OpenCV. I have searched the API Documentation, but couldn't find a useful resource.
Are there basic geometric helper functions for intersection/distance calculations on lines/line segments in OpenCV?
There are no function in OpenCV API to calculate lines intersection, but distance is:
cv::Point2f start, end;
double length = cv::norm(end - start);
If you need a piece of code to calculate line intersections then here it is:
// 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;
}
There's one cool trick in 2D geometry which I find to be very useful to calculate lines intersection. In order to use this trick we represent each 2D point and each 2D line in homogeneous 3D coordinates.
At first let's talk about 2D points:
(x, y)
corresponds to a 3D line that passes through points (0, 0, 0)
and (x, y, 1)
.(x, y, 1)
and (α•x, α•y, α)
and (β•x, β•y, β)
correspond to the same point (x, y)
in 2D space.(x, y) -> (x, y, 1)
(x, y, ω) -> (x / ω, y / ω)
. If ω is zero that means "point at infinity". It doesn't correspond to any point in 2D space.convertPointsToHomogeneous()
and convertPointsFromHomogeneous()
Now let's talk about 2D lines:
(a, b, c)
which corresponds to 2D line equation: a•x + b•y + c = 0
(a, b, c)
and (ω•a, ω•b, ω•c)
correspond to the same 2D line.(a, b, c)
corresponds to (nx, ny, d)
where (nx, ny)
is unit length normal vector and d is distance from the line to (0, 0)
(nx, ny, d)
is (cos φ, sin φ, ρ)
where (φ, ρ)
are polar coordinates of the line.There're two interesting formulas that link together points and lines:
(α•x₁, α•y₁, α) ✕ (β•x₂, β•y₂, β) = (a, b, c)
(a₁, b₁, c₁) ✕ (a₂, b₂, c₂) = (x, y, ω)
. If ω is zero that means lines are parallel (have no single intersection point in Euclidean geometry).Mat::cross()
or numpy.cross()
to get cross productIf you're still here, you've got all you need to find lines given two points and intersection point given two lines.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With