I would like you to refer to this point on Math StackExchange: https://math.stackexchange.com/questions/274712/calculate-on-which-side-of-a-straight-line-is-a-given-point-located. Simply put, given that you have three points: A point that denotes the beginning of the line, a point that denotes the end of the line and a query point, you can calculate the cross product between these three points and check the sign of the result. In fact, this answer on Stack Overflow uses this to determine if a point is on the left of a line: How to tell whether a point is to the right or left side of a line.
We can use this behaviour to help define if a point is to the left or right and can adjust based on the fact that you're using Python and DLib. Therefore, if the sign of the cross product is positive, the point is to the left of the line. If the sign is negative the point is to the right of the line. If the cross product is 0, then the point is collinear on the line. Because of numerical imprecision, comparing exactly with 0 is very dangerous as in most circumstances, getting exactly 0 is rare so comparing with exactly 0 may give you the wrong results. Therefore you'll want to see if the value is less than a small threshold, say 1e-9
for the collinear check.
With your example line, take note that it's essentially y = x
so we can definitely define well-known points that should appear to the left and right of the line.
Therefore:
def where_it_is(line, point):
aX = line.p1.x
aY = line.p1.y
bX = line.p2.x
bY = line.p2.y
cX = point.x
cY = point.y
val = ((bX - aX)*(cY - aY) - (bY - aY)*(cX - aX))
thresh = 1e-9
if val >= thresh:
return "left"
elif val <= -thresh:
return "right"
else:
return "point is on the line"
To test this out:
import dlib
a = dlib.point(0, 0)
b = dlib.point(20, 20)
line = dlib.line(a, b)
pt1 = dlib.point(2, -2) # Should appear on the right
pt2 = dlib.point(5, 10) # Should appear on the left
pt3 = dlib.point(2, 2) # Point should be collinear
print(where_it_is(line, pt1))
print(where_it_is(line, pt2))
print(where_it_is(line, pt3))
I've defined points to be on the left, right and collinear on the line. We get:
In [40]: %paste
print(where_it_is(line, pt1))
print(where_it_is(line, pt2))
print(where_it_is(line, pt3))
## -- End pasted text --
right
left
point is on the line