python ray method is used to judge whether the detection point is located in the rectangle outside the area
- 2021-07-06 11:06:21
- OfStack
In this paper, we share the specific code of python ray method to judge whether the point is located in the area for your reference. The specific contents are as follows
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2018-10-07 15:49:37
# @Author : Sheldon (thisisscret@qq.com)
# @Blog : Sheldon's Parson Notes
# @Link : https://www.cnblogs.com/shld/
# @Version : 0.0.1
def isinpolygon(point,vertex_lst:list, contain_boundary=True):
# Whether the detection point is located in the rectangle outside the area
lngaxis, lataxis = zip(*vertex_lst)
minlng, maxlng = min(lngaxis),max(lngaxis)
minlat, maxlat = min(lataxis),max(lataxis)
lng, lat = point
if contain_boundary:
isin = (minlng<=lng<=maxlng) & (minlat<=lat<=maxlat)
else:
isin = (minlng<lng<maxlng) & (minlat<lat<maxlat)
return isin
def isintersect(poi,spoi,epoi):
# Input: Judgment point, edge starting point and edge ending point are all [lng,lat] Format array
# The ray is a latitude line to the east
# Possible existence bug When the region straddles the prime meridian or 180 There may be problems when measuring longitude
lng, lat = poi
slng, slat = spoi
elng, elat = epoi
if poi == spoi:
#print(" At the vertex ")
return None
if slat==elat: # Exclude the parallelism and coincidence with rays and the coincidence of the first and last endpoints of line segments
return False
if slat>lat and elat>lat: # The line segment is on the top of the ray
return False
if slat<lat and elat<lat: # The line segment is below the ray
return False
if slat==lat and elat>lat: # The intersection point is the lower endpoint, corresponding to spoint
return False
if elat==lat and slat>lat: # The intersection point is the lower endpoint, corresponding to epoint
return False
if slng<lng and elat<lat: # The line segment is on the left side of the ray
return False
# Find the intersection point
xseg=elng-(elng-slng)*(elat-lat)/(elat-slat)
if xseg == lng:
#print(" Point on the edge of polygon ")
return None
if xseg<lng: # The intersection point is to the left of the starting point of the ray
return False
return True # After excluding the above situation,
def isin_multipolygon(poi,vertex_lst, contain_boundary=True):
# Determine whether it is in the outer rectangle, and if not, return directly false
if not isinpolygon(poi, vertex_lst, contain_boundary):
return False
sinsc = 0
for spoi, epoi in zip(vertex_lst[:-1],vertex_lst[1::]):
intersect = isintersect(poi, spoi, epoi)
if intersect is None:
return (False, True)[contain_boundary]
elif intersect:
sinsc+=1
return sinsc%2==1
if __name__ == '__main__':
vertex_lst = [[0,0],[1,1],[1,2],[0,2],[0,0]]
poi = [0.82,0.75]
print(isin_multipolygon(poi,vertex_lst, contain_boundary=True))