简体   繁体   中英

Shapely package - returning values of multiple intersections

courtesy of the following answer, I am trying to extend this script to work for multiple curves...

Intersection of two graphs in Python, find the x value

在此处输入图像描述

It only plots intersections on the last straigh line. Not sure how to get it for all straight lines.

import numpy as np
import matplotlib.pyplot as plt
from shapely.geometry import LineString

x = np.arange(0, 1000)
f1 = np.arange(0, 500, .5)
f2 = np.arange(0, 1000)
f3 = np.arange(0, 2000, 2)
f4 = np.arange(0, 2000, 2)
f =np.stack((f1, f2, f3, f4))

g1 = np.sin(np.arange(0, 10, 0.01) * 2) * 500
g2 = np.sin(np.arange(0, 10, 0.01) * 2) * 600
g3 = np.sin(np.arange(0, 10, 0.01) * 2) * 800
g4 = np.sin(np.arange(0, 10, 0.01) * 2) * 1000
g =np.stack((g1, g2, g3, g4))
for i in range(len(f)):
    plt.plot(x, f[i])
for i in range(len(g)):
    plt.plot(x, g[i])

a = []
for i in range(len(g)):
    a.append(LineString(np.column_stack((x, g[i]))))
b = []
for i in range(len(f)):
    b.append(LineString(np.column_stack((x, f[i]))))
    
inter = []
for i in range(len(a)):
     inter.append(a[i].intersection(b[i]))

for i in range(len(inter)):
    if inter[i].geom_type == 'MultiPoint':
        plt.plot(*LineString(inter[i]).xy, 'o')
    elif inter[i].geom_type == 'Point':
        plt.plot(*inter[i].xy, 'o')

Solution:

import numpy as np
import matplotlib.pyplot as plt
from shapely.geometry import LineString

x = np.arange(0, 1000)
f1 = np.arange(0, 500, .5)
f2 = np.arange(0, 1000)
f3 = np.arange(0, 2000, 2)
f4 = np.arange(0, 2000, 2)
f =np.stack((f1, f2, f3, f4))

g1 = np.sin(np.arange(0, 10, 0.01) * 2) * 500
g2 = np.sin(np.arange(0, 10, 0.01) * 2) * 600
g3 = np.sin(np.arange(0, 10, 0.01) * 2) * 800
g4 = np.sin(np.arange(0, 10, 0.01) * 2) * 1000
g =np.stack((g1, g2, g3, g4))
for i in range(len(f)):
    plt.plot(x, f[i])
for i in range(len(g)):
    plt.plot(x, g[i])

a = []
for i in range(len(g)):
    a.append(LineString(np.column_stack((x, g[i]))))
b = []
for i in range(len(f)):
    b.append(LineString(np.column_stack((x, f[i]))))
    
inter = []
for i in range(len(a)):
    for j in range(len(b)):
     inter.append(a[i].intersection(b[j]))

for i in range(len(inter)):
    if inter[i].geom_type == 'MultiPoint':
        plt.plot(*LineString(inter[i]).xy, 'o')
    elif inter[i].geom_type == 'Point':
        plt.plot(*inter[i].xy, 'o')

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM