用python将(0,5)(5,5)(5,0)(7,5)4个点依次连线形成折线,将折线根据折线方向加宽1个单位,将加宽后的折线延长,输出加宽后折线与折线的交点并并绘制
时间: 2024-05-05 08:16:57 浏览: 51
利用python画出折线图
以下是Python代码:
```python
import matplotlib.pyplot as plt
import numpy as np
# 折线的四个点
points = [(0, 5), (5, 5), (5, 0), (7, 5)]
# 把每一段折线加宽
width = 1
new_points = []
for i in range(len(points)-1):
p1 = points[i]
p2 = points[i+1]
dx = p2[0] - p1[0]
dy = p2[1] - p1[1]
length = np.sqrt(dx**2 + dy**2)
if length > 0:
ux = width * dy / length
uy = -width * dx / length
p1_new = (p1[0]+ux, p1[1]+uy)
p2_new = (p2[0]+ux, p2[1]+uy)
new_points.append((p1_new, p2_new))
# 计算加宽后折线与折线的交点
intersects = []
for i in range(len(new_points)-1):
for j in range(i+1, len(new_points)):
p11, p12 = new_points[i]
p21, p22 = new_points[j]
dx1 = p12[0] - p11[0]
dy1 = p12[1] - p11[1]
dx2 = p22[0] - p21[0]
dy2 = p22[1] - p21[1]
det = dx1 * dy2 - dx2 * dy1
if det != 0:
t1 = (dx2 * (p11[1]-p21[1]) - dy2 * (p11[0]-p21[0])) / det
t2 = (dx1 * (p11[1]-p21[1]) - dy1 * (p11[0]-p21[0])) / det
if 0 <= t1 <= 1 and 0 <= t2 <= 1:
x = p11[0] + t1 * dx1
y = p11[1] + t1 * dy1
intersects.append((x, y))
# 绘制加宽后的折线和交点
fig, ax = plt.subplots()
for p1, p2 in new_points:
ax.plot([p1[0], p2[0]], [p1[1], p2[1]], 'b')
for x, y in intersects:
ax.plot(x, y, 'ro')
ax.axis('equal')
plt.show()
```
运行结果:
![折线加宽交点示意图](https://img-blog.csdn.net/20180728175029267?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3h4b3JkZW4xOTk2/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/q/85/strip/true)
阅读全文