求输入n个点求这个n个点构造的三角网,之后随机输入一个点,求解点落在那个三角形中
求输入n个点求这个n个点构造的三角网,之后随机输入一个点,求解点落在那个三角形中
该算法实现了通过输入n个点,构造一个三角网,然后,输入一个点,可以判断落在三角网的那个区域,对代码感兴趣的,可以找我
实现代码如下:
import os
x= 637184.652096
y=4658089.958579
path="C:/Users/gaoxi/Desktop/data/data/data.txt"
target_point=[x,y]
def extra_data(path):
list_co=[]
with open(path,encoding='utf-8') as file:
line = file.readline()
line = file.readline()
while line:
data= line.split()
if len(data)<5:
line = file.readline()
continue
line = file.readline()
# print(data)
dataz=[float(i) for i in data[1:5]]
list_co.append(dataz)
# print(data[1:5])
# print(list_co)
return list_co
list_re=extra_data(path)
#print(list_re)
#print(len(list_re))
points=[]
import matplotlib.pyplot as plt
for i in list_re:
points.append(i[0:2])
plt.scatter(i[0],i[1],c='b')
def isInsideTriangle(P,p1,p2,p3): #is P inside triangle made by p1,p2,p3?
x,x1,x2,x3 = P[0],p1[0],p2[0],p3[0]
y,y1,y2,y3 = P[1],p1[1],p2[1],p3[1]
full = abs (x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2))
first = abs (x1 * (y2 - y) + x2 * (y - y1) + x * (y1 - y2))
second = abs (x1 * (y - y3) + x * (y3 - y1) + x3 * (y1 - y))
third = abs (x * (y2 - y3) + x2 * (y3 - y) + x3 * (y - y2))
return abs(first + second + third - full) < .00001
from scipy.spatial import Delaunay
import numpy as np
tri = Delaunay(points)
#print(tri.simplices)
for i in tri.simplices:
# print(i)
if isInsideTriangle(target_point,points[i[0]],points[i[1]],points[i[2]]):
print(list_re[i[0]])
print(list_re[i[1]])
print(list_re[i[2]])
break
plt.scatter(x,y,c='r')
plt.show()
os.system("pause")
运行结果如下:
最后三个点事输出的三角形坐标。