python – 如何以有效的方式找到两个轮廓集之间的所有交点

前端之家收集整理的这篇文章主要介绍了python – 如何以有效的方式找到两个轮廓集之间的所有交点前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想知道在两组轮廓线之间找到所有交点(到舍入误差)的最佳方法.这是最好的方法吗?这是一个例子:
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. x = np.linspace(-1,1,500)
  4. X,Y = np.meshgrid(x,x)
  5. Z1 = np.abs(np.sin(2*X**2+Y))
  6. Z2 = np.abs(np.cos(2*Y**2+X**2))
  7. plt.contour(Z1,colors='k')
  8. plt.contour(Z2,colors='r')
  9. plt.show()

我想要一些类似的:

  1. intersection_points = intersect(contour1,contour2)
  2. print intersection_points
  3. [(x1,y1),...,(xn,yn)]

解决方法

  1. import collections
  2. import matplotlib.pyplot as plt
  3. import numpy as np
  4. import scipy.spatial as spatial
  5. import scipy.spatial.distance as dist
  6. import scipy.cluster.hierarchy as hier
  7.  
  8.  
  9. def intersection(points1,points2,eps):
  10. tree = spatial.KDTree(points1)
  11. distances,indices = tree.query(points2,k=1,distance_upper_bound=eps)
  12. intersection_points = tree.data[indices[np.isfinite(distances)]]
  13. return intersection_points
  14.  
  15.  
  16. def cluster(points,cluster_size):
  17. dists = dist.pdist(points,metric='sqeuclidean')
  18. linkage_matrix = hier.linkage(dists,'average')
  19. groups = hier.fcluster(linkage_matrix,cluster_size,criterion='distance')
  20. return np.array([points[cluster].mean(axis=0)
  21. for cluster in clusterlists(groups)])
  22.  
  23.  
  24. def contour_points(contour,steps=1):
  25. return np.row_stack([path.interpolated(steps).vertices
  26. for linecol in contour.collections
  27. for path in linecol.get_paths()])
  28.  
  29.  
  30. def clusterlists(T):
  31. '''
  32. https://stackoverflow.com/a/2913071/190597 (denis)
  33. T = [2,2,1]
  34. Returns [[0,4,5,6,7,8],[1,3,9]]
  35. '''
  36. groups = collections.defaultdict(list)
  37. for i,elt in enumerate(T):
  38. groups[elt].append(i)
  39. return sorted(groups.values(),key=len,reverse=True)
  40.  
  41. # every intersection point must be within eps of a point on the other
  42. # contour path
  43. eps = 1.0
  44.  
  45. # cluster together intersection points so that the original points in each flat
  46. # cluster have a cophenetic_distance < cluster_size
  47. cluster_size = 100
  48.  
  49. x = np.linspace(-1,x)
  50. Z1 = np.abs(np.sin(2 * X ** 2 + Y))
  51. Z2 = np.abs(np.cos(2 * Y ** 2 + X ** 2))
  52. contour1 = plt.contour(Z1,colors='k')
  53. contour2 = plt.contour(Z2,colors='r')
  54.  
  55. points1 = contour_points(contour1)
  56. points2 = contour_points(contour2)
  57.  
  58. intersection_points = intersection(points1,eps)
  59. intersection_points = cluster(intersection_points,cluster_size)
  60. plt.scatter(intersection_points[:,0],intersection_points[:,1],s=20)
  61. plt.show()

产量

猜你在找的Python相关文章