Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to judge if a polygon is inside another polygon in Python?

Tags:

python

I need to define a Python function which can dectect if a convex polygon (polygon a) is inside another polygon(polygon b).

The vertex of each polygon are given.

(only use basic lib as well as numpy)

It’s easy for a human to make a judgement with their eyes. But I have no idea how to describe the method in Python. I have tried to check some source code of lib (like shapely) but can't understand how it works. '''

def isinside(polya, polyb):
     #Polya: [(x1,y1), (x2,y2), (x3,y3),...]
     #Polyb: [(x1,y1), (x2,y2), (x3,y3),...]
    #if polya inside polyb
     return True
     # else 
     return False

''' Could someone please give some advice or show some codes? Thanks!

like image 570
user8400129 Avatar asked Apr 25 '19 02:04

user8400129


Video Answer


1 Answers

You could use the shapely lib for that. It'd go like

from shapely.geometry import Polygon

polya = Polygon([(0, 0), (0, 1), (1, 1), (1, 0)]) 
polyb = Polygon([(0.5, 0.5), (0.5, 0.8), (0.8, 0.8), (0.8, 0.5)]) 

polya.contains(polyb)
# True

This module has got a lot more on most geometry related operations, so refer to their User Manual for further examples and thorough explanations.

like image 50
Julio Cezar Silva Avatar answered Oct 22 '22 20:10

Julio Cezar Silva