我们可以使用斜率来解决这个问题。我们知道一条线的斜率是arctanys 和xs 之比的xs
slope_as_angle = atan((y1 - y2) / (x1 - x2))
最好使用atan2 而不是atan。为简单起见,让我们使用度数而不是弧度:
slope_as_angle = math.degrees(math.atan2((y1 - y2), (x1 - x2)))
现在让我们看看不同倾斜角度下线条的外观:
for i in range(0, 360, 20):
x = 10 * math.cos(math.radians(i))
y = 10 * math.sin(math.radians(i))
spl = math.degrees(math.atan2(y - 0, x - 0)) % 360
plt.plot([0, x], [0, y], label=str(i))
plt.legend()
plt.show()
请注意,对于每个 20 degrees,我们正在获取 (0, 0) 和 (cos, sin) 之间的所有线的倾斜角(请参阅:Cartesian to Polar)。
现在我们需要一个逻辑来理解一条线在给定的倾斜角度下是垂直还是水平:
水平
我会说每条斜角在 [160, 200] 或大于 340 或小于 20 之间的线是水平的。
if 160 < angle < 200 or 340 < angle or angle < 20
更好的方法:
if 160 < angle < 200 or not 20 < angle < 340
垂直
我会说斜角在 [60, 120] 或 [240, 300] 之间的每条线都是垂直的。
if 60< angle < 120 or 240 < angle < 300.
让我们指定一个限制变量作为阈值,以便我们可以随意更改它:
对于水平线:
if (not limit < spl <= 360 - limit) or (180 - limit <= spl < 180 + limit):
垂直线:
if (90 - limit < spl < 90 + limit) or (270 - limit < spl < 270 + limit):
要检查的代码是:
def check_the_line(slope, limit=10):
if (not limit < spl <= 360 - limit) or (180 - limit <= spl < 180 + limit):
return "h"
elif (90 - limit < spl < 90 + limit) or (270 - limit < spl < 270 + limit):
return "v"
return "o"
让我们验证一下:
import math
from matplotlib import pyplot as plt
fig, (ax1, ax2, ax3) = plt.subplots(3, 1)
limit = 10
def check_the_line(slope, limit=10):
if (not limit < spl <= 360 - limit) or (180 - limit <= spl < 180 + limit):
return "h"
elif (90 - limit < spl < 90 + limit) or (270 - limit < spl < 270 + limit):
return "v"
return "o"
for i in range(0, 360, 1):
x = 10 * math.cos(math.radians(i))
y = 10 * math.sin(math.radians(i))
spl = math.degrees(math.atan2(y, x)) % 360
ax1.plot([0, x], [0, y])
if check_the_line(spl, limit=limit) == "h":
ax2.plot([0, x], [0, y])
elif check_the_line(spl, limit=limit) == "v":
ax3.plot([0, x], [0, y])
ax1.set_title("All lines")
ax1.set_xlim([-10, 10])
ax1.set_ylim([-10, 10])
ax2.set_title("Horizontal Lines")
ax2.set_xlim([-10, 10])
ax2.set_ylim([-10, 10])
ax3.set_title("Vertical Lines")
ax3.set_xlim([-10, 10])
ax3.set_ylim([-10, 10])
plt.show()