How to calculate line line intersection

I got 2 lines and each line was defined by two points.
I’m trying to compute the intersection of the two lines with code below:

img1Line1P1 = [35.522341272816135, 244.0, -81.8808026069687]
img1Line1P2 = [36.1800944701046, 231.0, -81.31657002936069]
img2Line1P1 = [72.34037273903428, 244.0, -81.8925739257786]
img2Line1P2 = [70.43558942657907, 231.0, -81.32453925781688]

u = vtk.mutable(0)
v = vtk.mutable(0)

intersectType = vtk.vtkLine().Intersection(
img1Line1P1, img1Line1P2, img2Line1P1, img2Line1P2, u, v)
target11 = [img1Line1P1[i]+u*(img1Line1P2[i]-img1Line1P1[i]) for i in range(3)]
target12 = [img2Line1P1[i]+v*(img2Line1P2[i]-img2Line1P1[i]) for i in range(3)]
target1 = [(target11[i]+target12[i])/2 for i in range(3)]

print(intersectType)
print(u,v)
print(target11)
print(target12)
print(target1)

img1Line1P1 = [35.5223, 244, -81.8808]
img1Line1P2 = [36.4701, 231, -81.3736]
img2Line1P1 = [72.3401, 244, -81.8927]
img2Line1P2 = [70.4352, 231, -81.3244]

u = vtk.mutable(0)
v = vtk.mutable(0)

intersectType = vtk.vtkLine().Intersection(
img1Line1P1, img1Line1P2, img2Line1P1, img2Line1P2, u, v)
target11 = [img1Line1P1[i]+u*(img1Line1P2[i]-img1Line1P1[i]) for i in range(3)]
target12 = [img2Line1P1[i]+v*(img2Line1P2[i]-img2Line1P1[i]) for i in range(3)]
target1 = [(target11[i]+target12[i])/2 for i in range(3)]

print(intersectType)
print(u,v)
print(target11)
print(target12)
print(target1)

Output of code above goes like:

0
14.367889142863488 14.367746083471086
[44.972866294820804, 57.217441142774646, -73.7739714811047]
[44.97292976164488, 57.21930091487587, -73.73119604989571]
[44.97289802823284, 57.21837102882526, -73.7525837655002]
0
12.902095599460948 12.899676454379204
[47.7509062091691, 76.27275720700769, -75.33685711195344]
[47.76750632205291, 76.30420609307035, -74.56181387097621]
[47.759206265611006, 76.28848165003902, -74.94933549146482]

As you can see, even with a tiny difference of the points coordinates, the intersection calculated was totally different, especially with the Y-axis.

I was wondering if my code is the correct way to calculate the intersection of two 3D lines? How to get the correct result?

Hi,
Maybe I’m wrong but it seems that if intersectType == 0 it means no intersection.

Intersection type is for finite line(or line segment) intersection and my purpose is to find the intersection of two infinite line.

As you can see the u and v calculated are beyond [0, 1], this is why vtkLine::Intersection() returns 0.

Plus, these two lines are skew lines so there is no intersection in the 3D space. But since vtkLine::Intersection() calculates the intersection of two 3D lines by projecting them to a plane, it does find a point which is closest to both two lines and I call it intersection

The question was also asked and answered on the Slicer forum: