我需要一个 python 脚本来检查椭圆和矩形是否相交。如果它们相交,则以绿色绘制椭圆,否则以红色绘制。
我正在使用 matplotlib 的 path.intersects_bbox 和 path.intersects_path 方法来检查两个图形是否相交。但是这两种方法都不能正常工作。 path.intersects_bbox 方法有时有效,有时无效。有人请帮助我完成这项任务。我附上了以下脚本的一些正确和错误的输出。
我正在使用下面附带的脚本。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.transforms import Bbox
from matplotlib.patches import Ellipse
# Generate random triangle
def generateRect():
left = np.random.randint(-10,10)
bottom = np.random.randint(-10, 10)
width = np.random.randint(-10, 10)
height = np.random.randint(-10, 10)
return left,bottom,width,height
# generating 20 random triangles and intersecting them
for i in range (0, 20):
left, bottom, width, height = generateRect()
rect = plt.Rectangle((left, bottom), width, height, color="blue",fill = False)
fig, ax = plt.subplots()
ax.add_patch(rect)
bbox = Bbox.from_bounds(left, bottom, width, height)
rectPath = rect.get_path()
ellipse = Ellipse((0, 0), 20, 3, 3)
path = ellipse.get_path()
path = path.interpolated(10)
vertices = path.vertices.copy()
vertices = ellipse.get_patch_transform().transform(vertices)
# path.intersects_path is not working
# if path.intersects_path(rectPath):
# color = 'g'
# else:
# color = 'r'
# path.intersects_bbox sometimes works and sometime doesn't
if path.intersects_bbox(bbox,filled= False):
color = 'g'
else:
color = 'r'
for i in vertices:
plt.plot(i[0],i[1], marker="o", markersize=3, markeredgecolor=color, markerfacecolor=color)
ellipse = Ellipse((0, 0), 20, 3, 3,color=color, fill=False)
ax.add_patch(ellipse)
ax.plot()
plt.show()