Karthik
Karthik

Reputation: 1

Python script to check if ellipse and rectangle intersect

I need a python script to check if ellipse and rectangle intersect. If they intersect plot the ellipse in green color else plot in red color.

I am using matplotlib's path.intersects_bbox and path.intersects_path methods to check if two figures intersect. But both the methods doesn't work properly. path.intersects_bbox methods sometimes work and sometimes doesn't. Somebody please help me in achieving this task. I am attaching some correct and wrong outputs of the below script.Correct Output Correct Output Wrong Output

I am using the script attached below.

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()

Upvotes: 0

Views: 87

Answers (0)

Related Questions