判断点在多边形内

向量叉乘判断点在多边形内


Python代码:

# 点在多边形内
# Cao Jinhao
# 20240730
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()

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hanssjtuer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值