在人工智能中有个入侵检测:当检测到的目标位于指定区域内才算是入侵,思路很简单,判断相关坐标即可:
from matplotlib import pyplot as plt, patches
from shapely.geometry import Polygon, Point
def is_intrusion(target_box, intrusion_area):
# 判断目标框的多个个角是否在入侵区域内
for point in [(target_box[0], target_box[1]), (target_box[2], target_box[3]),
(target_box[0], target_box[3]), (target_box[2], target_box[1])]:
if point_in_polygon(point, intrusion_area):
return True
# 判断入侵区域是否与目标框相交
intrusion_polygon = Polygon(intrusion_area)
target_polygon = Polygon([(target_box[0], target_box[1]), (target_box[2], target_box[1]),
(target_box[2], target_box[3]), (target_box[0], target_box[3])])
return intrusion_polygon.intersects(target_polygon)
def point_in_polygon(point, polygon):
# 使用 shapely 库检查点是否在多边形内
point = Point(point)
polygon = Polygon(polygon)
return point.within(polygon)
# 示例用法
target_box = (100, 100, 200, 200) # 目标框坐标 (x_min, y_min, x_max, y_max)
intrusion_area_hexagon = [(150, 150), (200, 190), (250, 150), (250, 200), (200, 220), (150, 1000), (100, 220), (150, 190)] # 六边形区域坐标
result = is_intrusion(target_box, intrusion_area_hexagon)
print("是否入侵:", result)
# 创建一个新的图
fig, ax = plt.subplots()
# 绘制目标框
target_rect = patches.Rectangle((target_box[0], target_box[1]), target_box[2] - target_box[0],
target_box[3] - target_box[1], linewidth=1, edgecolor='r', facecolor='none')
ax.add_patch(target_rect)
# 绘制六边形区域
intrusion_area_polygon = patches.Polygon(intrusion_area_hexagon, closed=True, linewidth=1, edgecolor='b',
facecolor='none')
ax.add_patch(intrusion_area_polygon)
# 设置图的坐标轴范围
ax.set_xlim(0, 1920)
ax.set_ylim(0, 1080)
# 显示图
plt.show()
效果如下: