Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Python, how do I tell if a rectangle and a shape overlap?

I'm writing a program in Python. I have a series of shapes (polygons, defined as a sequence of coordinate pairs) and I need to tell if they overlap a particular rectangle.

Is there an easy algorithm for handling this? Or, better, is there a pure Python library that can handle these calculations for me?

like image 510
Chris B. Avatar asked Feb 23 '11 15:02

Chris B.


People also ask

How do you check if a rectangle is overlapped in Python?

Practical Data Science using PythonTwo rectangles overlap when the area of their intersection is positive. So, two rectangles that only touch at the corner or edges do not overlap. So, if the input is like R1 = [0,0,2,2], R2 = [1,1,3,3], then the output will be True.

How do you know if a rectangle is overlapping?

Its top and bottom edges are perpendicular to the X-axis, while its left and right edges are perpendicular to the Y-axis. If the area of their intersection is positive, two rectangles overlap. Two rectangles that touch at the corners or edges do not overlap.

How do you know if two shapes are overlapping?

One option would be to enclose each shape in an imaginary circle. If those circles overlap, you can then imagine smaller tighter circles in the vicinity of the original intersection. Repeat the calculations with smaller and smaller circles as often as desired.


1 Answers

Presuming your "arbitrary shapes" are indeed polygons (given that they're described as coordinate pairs), determining if they overlap (in any language) is a relatively trivial calculation. You merely need to compute if any side of polygon A intersects any other side of polygon B.

If you need an example, there's a rather thorough walkthrough at the Drexel Math Forum.

There are a number of Python modules which can assist you in this pursuit, such as Sympy, Numpy, PyGame, etc., but all of them are rather heavy if this is the only geometric calculation you need to make.

like image 69
Nick Bastin Avatar answered Nov 14 '22 22:11

Nick Bastin