向量叉乘判断点在多边形内
Python代码:
import numpy as np
import matplotlib.pyplot as plt
import random
from matplotlib.patches import FancyArrowPatch
import matplotlib.path as mpath
def circle_points(n, center, radius):
points = {}
angle_step = 2 * np.pi / n
for i in range(n):
angle = i * angle_step
x = center[0] + radius * np.cos(angle)
y = center[1] + radius * np.sin(angle)
points[i] = (x, y)
return points
n = 32
radius = 15
center = (radius, radius)
points = circle_points(n, center, radius)
plt.figure()
plt.grid(True)
ax = plt.gca()
plt.xlim(right=2.5*radius)
plt.ylim(top=2.5*radius)
ax.set_aspect('equal')
circle = plt.Circle(center, radius, fill=False)
ax.add_artist(circle)
m = 10
selected_keys = random.sample(list(points.keys()), m)
sorted_selected_keys = sorted(selected_keys)
sorted_selected_points = [points[key] for key in sorted_selected_keys]
for i in range(len(sorted_selected_keys)):
k = sorted_selected_keys[i]
x = sorted_selected_points[i][0]
y = sorted_selected_points[i][1]
plt.plot(x, y, 'ro')
plt.text(x, y, str(k), ha='center', va='center', fontsize=9)
sorted_selected_points.append(sorted_selected_points[0])
polygon = plt.Polygon(sorted_selected_points, closed=True, fill=False, edgecolor='b')
ax.add_patch(polygon)
test_point = center
cross = []
for i in range(0, len(sorted_selected_points)-1, 1):
posA1 = sorted_selected_points[i]
posB1 = sorted_selected_points[i+1]
arrow1 = FancyArrowPatch(posA1, posB1, arrowstyle='->', mutation_scale=20, lw=2, edgecolor='r')
ax.add_patch(arrow1)
arrow2 = FancyArrowPatch(posA1, center, arrowstyle='->', mutation_scale=20, lw=2, edgecolor='g')
ax.add_patch(arrow2)
plt.draw()
plt.pause(2)
cross.append(np.cross(np.array(posB1) - np.array(posA1), np.array(center) - np.array(posA1)))
cross = [1 if i > 0 else -1 for i in cross]
if len(set(cross)) == 1:
print('点在多边形内')
else:
print('点不在多边形内')
plt.show()