The even–odd algorithm for the point-in-polygon test

该代码实现了一个用于检测点是否在多边形内的算法,基于GraphicsGemsIV中Haines的C程序。它通过计算半直线与多边形边界的交点数来判断。算法遍历多边形的顶点,比较点的y坐标并计算交点,最终确定点的位置(在内或在外)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The even–odd algorithm for the point-in-polygon test

import math
from Points import *


def pip_cross(point, pgon):
    # Determines whether a point is in a polygon. Code adopted
    # from the C program in Graphics Gems IV by Haines (1994).
    # Input
    #   pgon: a list of points as the vertices for a polygon
    #   point: the point
    # Output
    #   Returns a boolean value of True or False and the number
    #   of times the half-line crosses the polygon boundary

    numvert = len(pgon)
    tx=point.x
    ty=point.y
    p1 = pgon[numvert-1]
    p2 = pgon[0]
    yflag1 = (p1.y >= ty)
    crossing = 0
    inside_flag = 0
    for j in range(numvert-1):
        yflag2 = (p2.y >= ty)
        if yflag1 != yflag2:
            xflag1 = (p1.x >= tx)
            xflag2 = (p2.x >= tx)
            if xflag1 == xflag2:
                if xflag1:
                    crossing += 1
                    inside_flag = not inside_flag
            else:
                m = p2.x - float((p2.y-ty))*\
                    (p1.x-p2.x)/(p1.y-p2.y)
                if m >= tx:
                    crossing += 1
                    inside_flag = not inside_flag
        yflag1 = yflag2
        p1 = p2
        p2 = pgon[j+1]
    return inside_flag, crossing


if __name__ == "__main__":
    points = [ [0,10], [5,0], [10,10], [15,0], [20,10],
                 [25,0], [30,20], [40,20], [45,0], [50,50],
                 [40,40], [30,50], [25,20], [20,50], [15,10],
                 [10,50], [8, 8], [4,50], [0,10] ]
    ppgon = [Point(p[0], p[1]) for p in points ]
    inout = lambda pip: "IN" if pip is True else "OUT"
    point = Point(10, 30)
    print("Point %s is %s" % (point, inout(pip_cross(point, ppgon)[0])))
    point = Point(10, 20)
    print("Point %s is %s" % (point, inout(pip_cross(point, ppgon)[0])))
    point = Point(20, 40)
    print("Point %s is %s" % (point, inout(pip_cross(point, ppgon)[0])))
    point = Point(5, 40)
    print("Point %s is %s" % (point, inout(pip_cross(point, ppgon)[0])))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值