您可以通过每对点(线AB,BC,AC)找到线,并检查这些线的哪一侧是三角形的内侧。摆在所有线路上的“inside'侧的点是在三角形内:
def insidetriangle((x1,x2,x3),(y1,y2,y3)):
import numpy as np
xs=np.array((x1,x2,x3),dtype=float)
ys=np.array((y1,y2,y3),dtype=float)
# The possible range of coordinates that can be returned
x_range=np.arange(np.min(xs),np.max(xs)+1)
y_range=np.arange(np.min(ys),np.max(ys)+1)
# Set the grid of coordinates on which the triangle lies. The centre of the
# triangle serves as a criterion for what is inside or outside the triangle.
X,Y=np.meshgrid(x_range,y_range)
xc=np.mean(xs)
yc=np.mean(ys)
# From the array 'triangle', points that lie outside the triangle will be
# set to 'False'.
triangle = np.ones(X.shape,dtype=bool)
for i in range(3):
ii=(i+1)%3
if xs[i]==xs[ii]:
include = X *(xc-xs[i])/abs(xc-xs[i]) > xs[i] *(xc-xs[i])/abs(xc-xs[i])
else:
poly=np.poly1d([(ys[ii]-ys[i])/(xs[ii]-xs[i]),ys[i]-xs[i]*(ys[ii]-ys[i])/(xs[ii]-xs[i])])
include = Y *(yc-poly(xc))/abs(yc-poly(xc)) > poly(X) *(yc-poly(xc))/abs(yc-poly(xc))
triangle*=include
# Output: 2 arrays with the x- and y- coordinates of the points inside the
# triangle.
return X[triangle],Y[triangle]
3不等式解决了循环,导致相乘,得到三角形内仅点布尔阵列。
编辑: 回路可以写更多的不言自明的一点是:
for i in range(3):
ii=(i+1)%3
if xs[i]==xs[ii]:
if xc>xs:
include = (X > xs[i])
else:
include = (X < xs[i])
else:
slope=(ys[ii]-ys[i])/(xs[ii]-xs[i])
poly=np.poly1d([slope,ys[i]-xs[i]*slope])
if yc>poly(xc):
include = (Y > poly(X))
else:
include = (Y < poly(X))
triangle*=include
谷歌“测试,如果点在三角”。有很多资源。你不必解决9个不平等。 –
我不确定它是否有效,但我相信你可以计算出三个高度。 这对第1点和第2点没有帮助,但它会将不平等数量最小化为三。因为要位于三角形内,与点A的距离必须小于h_a等等 – Glostas
一些想法'http://stackoverflow.com/questions/2049582/how-to-determine-a-point-in-a-2d -triangle' – Marichyasana