点在多边形内吗?方法有问题

Is a point inside a polygon? Problem with method

Whosebug 中的第一个 post。我在 python 中使用 TfPoseEstimator,需要知道人类 body 的某个点是否在我在多边形中划定的区域内。 我的问题是 try 块说:"Not working" 对于 body 的每个部分。 有人可以帮助我吗?

def punto_en_poligono(x, y, poligono):
    i = 0
    j = len(poligono) - 1
    salida = False
    for i in range(len(poligono)):
        if (poligono[i][1] < y and poligono[j][1] >= y) or (poligono[j][1] < y and poligono[i][1] >= y):
            if poligono[i][0] + (y - poligono[i][1]) / (poligono[j][1] - poligono[i][1]) * (poligono[j][0] - poligono[i][0]) < x:
                salida = not salida
        j = i
    return salida 


humans1 = e.inference(recto, resize_to_default=(w > 0 and h > 0), upsample_size=args.resize_out_ratio)
poly1 = geometry.Polygon([[450,350],[478,0],[638,0],[638,350],[450,350]])

for j in humans1:
    for i in j.body_parts:
        try:
             pos_X = int(j.body_parts[i].x*960)                         
             pos_Y = int(j.body_parts[i].y*640) 
             is_Inside = punto_en_poligono(pos_X,pos_Y,poly1)
        except:
             print("Not working")

预期为真或假。 实际结果:"Not working"

这里有一个使用 shapely 的解决方案:

from shapely.geometry import Point
from shapely.geometry.polygon import Polygon

point0 = Point(500, 200)
point1 = Point(500, 0) 
poly1 = Polygon([[450,350],[478,0],[638,0],[638,350],[450,350]])

print(poly1.contains(point0)) #True
print(poly1.contains(point1)) #False

在你的程序中,你只需替换行:然后你就可以删除函数 punto_en_poligono

is_Inside = poly1.contains(Point(pos_X,pos_Y)