检查点是否在多边形内 [英] Checking if a point is inside a polygon

查看:128
本文介绍了检查点是否在多边形内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个描述一个点的类(具有2个坐标x和y),一个类描述了一个多边形,该多边形具有与角相对应的点列表(self.corners) 我需要检查一个点是否在多边形中

I have a class describing a Point (has 2 coordinates x and y) and a class describing a Polygon which has a list of Points which correspond to corners (self.corners) I need to check if a Point is in a Polygon

这是应该检查点是否在多边形中的功能.我正在使用射线投射法

Here is the function that is supposed to check if the Point is in the Polygon. I am using the Ray Casting Method

def in_me(self, point):
        result = False
        n = len(self.corners)
        p1x = int(self.corners[0].x)
        p1y = int(self.corners[0].y)
        for i in range(n+1):
            p2x = int(self.corners[i % n].x)
            p2y = int(self.corners[i % n].y)
            if point.y > min(p1y,p2y):
                if point.x <= max(p1x,p2x):
                    if p1y != p2y:
                        xinters = (point.y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
                        print xinters
                    if p1x == p2x or point.x <= xinters:
                        result = not result
            p1x,p1y = p2x,p2y
         return result

我用以下形状和点进行了测试:

I run a test with following shape and point:

PG1 = (0,0), (0,2), (2,2), (2,0)
point = (1,1)

即使脚本在行中指向该点,它也会很高兴地返回False.我找不到错误

The script happily returns False even though the point it within the line. I am unable to find the mistake

推荐答案

我建议使用matplotlib

import matplotlib.path as mplPath
import numpy as np

poly = [190, 50, 500, 310]
bbPath = mplPath.Path(np.array([[poly[0], poly[1]],
                     [poly[1], poly[2]],
                     [poly[2], poly[3]],
                     [poly[3], poly[0]]]))

bbPath.contains_point((200, 100))

(如果要测试多个点,则还有一个contains_points函数)

(There is also a contains_points function if you want to test for multiple points)

这篇关于检查点是否在多边形内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆