如果您的直线有起点和终点[x1, y1] 和[x2, y2],那么直线方程为:
y - y1 = m * (x - x1),其中m = (y2 - y1)/(x2-x1)
然后您可以检查一个点是否属于线,替换x或y,并检查另一个是否与线方程匹配。
在 Pyhton 中:
# the two points that define the line
p1 = [1, 6]
p2 = [3, 2]
# extract x's and y's, just for an easy code reading
x1, y1 = p1
x2, y2 = p2
m = (y2-y1)/(x2-x1)
# your centroid
centroid = [2,4]
x3, y3 = centroid
# check if centroid belongs to the line
if (m * (x3-x1) + y1) == y3:
print("Centroid belongs to line")
但可能...
...计算红点与直线 (distance from a point to a line) 之间的距离,然后检查它是否足够近(即距离小于某个值),您将获得更好的结果。
在 Python 中:
# points that define the line
p1 = [1, 6]
p2 = [3, 2]
x1, y1 = p1
x2, y2 = p2
centroid = [2,4]
x3, y3 = centroid
# distance from centroid to line
import math # to calculate square root
dist = abs((y2-y1)*x3 - (x2-x1)*y3 + x2*y1 - y2*x1)/math.sqrt((y2-y1)**2 + (x2-x1)**2)
if dist < some_value:
print("Near enough")