python3 ray method to judge whether a point is in a polygon

  • 2021-07-03 00:42:38
  • OfStack

In this paper, we share the specific code of python3 ray method to judge whether a point is in a polygon for your reference. The specific contents are as follows


#!/usr/bin/python3.4
# -*- coding:utf-8 -*-
 
 
def isPointinPolygon(point, rangelist): #[[0,0],[1,1],[0,1],[0,0]] [1,0.8]
  #  Determine whether it is in the outer rectangle, and if not, return directly false
  lnglist = []
  latlist = []
  for i in range(len(rangelist)-1):
    lnglist.append(rangelist[i][0])
    latlist.append(rangelist[i][1])
  print(lnglist, latlist)
  maxlng = max(lnglist)
  minlng = min(lnglist)
  maxlat = max(latlist)
  minlat = min(latlist)
  print(maxlng, minlng, maxlat, minlat)
  if (point[0] > maxlng or point[0] < minlng or
    point[1] > maxlat or point[1] < minlat):
    return False
  count = 0
  point1 = rangelist[0]
  for i in range(1, len(rangelist)):
    point2 = rangelist[i]
    #  Points coincide with vertices of polygons 
    if (point[0] == point1[0] and point[1] == point1[1]) or (point[0] == point2[0] and point[1] == point2[1]):
      print(" At the vertex ")
      return False
    #  Judge whether the two ends of the line segment are on both sides of the ray   No, definitely no intersection   Ray ( - ∞, lat ) ( lng,lat ) 
    if (point1[1] < point[1] and point2[1] >= point[1]) or (point1[1] >= point[1] and point2[1] < point[1]):
      #  Find the intersection point between line segment and ray   Again with lat Comparison 
      point12lng = point2[0] - (point2[1] - point[1]) * (point2[0] - point1[0])/(point2[1] - point1[1])
      print(point12lng)
      #  Point on the edge of polygon 
      if (point12lng == point[0]):
        print(" Point on the edge of polygon ")
        return False
      if (point12lng < point[0]):
        count +=1
    point1 = point2
  print(count)
  if count%2 == 0:
    return False
  else:
    return True
 
 
if __name__ == '__main__':
  print(isPointinPolygon([0.8,0.8], [[0,0],[1,1],[0,1],[0,0]]))

Related articles: