代码实现:
import numpy as np
import cv2
class Check_line():
def __init__(self):
pass
def step_one(self, p1, p2, q1, q2):
"""
1、执行第一步,进行快速排斥实验-----直线AB与直线CD
:param p1: A点坐标
:param p2: B点坐标
:param q1: C点坐标
:param q2: D点坐标
"""
reslut_1 = min(p1[0], p2[0]) <= max(q1[0], q2[0])
reslut_2 = min(q1[0], q2[0]) <= max(p1[0], p2[0])
reslut_3 = min(p1[1], p2[1]) <= max(q1[1], q2[1])
reslut_4 = min(q1[1], q2[1]) <= max(p1[1], p2[1])
if reslut_1 and reslut_2 and reslut_3 and reslut_4:
return True
else:
return False
def step_two(self, p1, p2, q2, q1):
"""
2.执行第二步:跨立实验
:param p1: A点坐标
:param p2: B点坐标
:param q2: C点坐标
:param q1: D点坐标
:return:
"""
# [(P1x-Q1x)*(Q2y-Q1y)-(P1y-Q1y)*( Q2x-Q1x)] * [(Q2x-Q1x)*(P2y-Q1y)-(Q2y-Q1y)*(P2x-Q1x)] > 0
result_1 = (p1[0] - q1[0]) * (q2[1] - q1[1]) - (p1[1] - q1[1]) * (q2[0] - q1[0])
result_2 = (q2[0] - q1[0]) * (p2[1] - q1[1]) - (q2[1] - q1[1]) * (p2[0] - q1[0])
# [(Q1x-P1x)*(P1y-P2y)-(Q1y-P1y)*( P2x-P1x)] * [(P2x-P1x)*(Q2y-P1y)-(P2y-P1y)*(Q2x-P1x)] > 0
result_3 = (q1[0] - p1[0]) * (p1[1] - p2[1]) - (q1[1] - p1[1]) * (p2[0] - p1[0])
result_4 = (p2[0] - p1[0]) * (q2[1] - p1[1]) - (p2[1] - p1[1]) * (q2[0] - p1[0])
return (result_1 * result_2 > 0) and (result_3 * result_4 > 0)
def __call__(self, *args, **kwargs):
pass
if __name__ == '__main__':
img = np.zeros((401, 401, 3), np.uint8)
a = (199, 199)
b = (220, 220)
c = (400, 0)
d = (0, 400)
cv2.line(img, a, b, (255, 255, 255), 1)
cv2.line(img, c, d, (255, 255, 255), 1)
line = Check_line()
# 进行快速排斥实验
temp = line.step_one(a, b, c, d)
print(temp)
temp_two = line.step_two(a, b, c, d)
print(temp_two)
cv2.imshow("temp", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
显示效果如下: