Skip to main content
 首页 » 编程设计

Python点查找(坐标装箱)

2025年05月04日10artech

问候,

我正在尝试将一组点 (x, y) 放入一组框 [(x0, y0), (x1, y0), (x0, y1) , (x1, y1)] (元组是角点)

到目前为止,我有以下例程:

def isInside(self, point, x0, x1, y0, y1): 
    pr1 = getProduct(point, (x0, y0), (x1, y0)) 
    if pr1 >= 0: 
        pr2 = getProduct(point, (x1, y0), (x1, y1)) 
        if pr2 >= 0: 
            pr3 = getProduct(point, (x1, y1), (x0, y1)) 
            if pr3 >= 0: 
                pr4 = getProduct(point, (x0, y1), (x0, y0)) 
                if pr4 >= 0: 
                    return True 
    return False 
 
def getProduct(origin, pointA, pointB): 
    product = (pointA[0] - origin[0])*(pointB[1] - origin[1]) - (pointB[0] - origin[0])*(pointA[1] - origin[1]) 
    return product 

有没有比逐点查找更好的方法?也许是一些不明显的 numpy 例程?

谢谢!

请您参考如下方法:

如果我正确理解您的问题,那么假设您的点也是二元组,则以下内容应该有效。

def in_bin(point, lower_corner, upper_corner): 
    """ 
    lower_corner is a 2-tuple - the coords of the lower left hand corner of the 
    bin. 
    upper_corner is a 2-tuple - the coords of the upper right hand corner of the 
    bin. 
    """ 
    return lower_corner <= point <= upper_corner 
 
if __name__ == '__main__': 
    p_min = (1, 1) # lower left corner of bin 
    p_max = (5, 5) # upper right corner of bin 
 
    p1 = (3, 3) # inside 
    p2 = (1, 0) # outside 
    p3 = (5, 6) # outside 
    p4 = (1, 5) # inside 
 
    points = [p1, p2, p3, p4] 
 
    for p in points: 
        print '%s in bin: %s' % (p, in_bin(p, x_min, x_max)) 

此代码表明您可以直接比较元组 - 文档中有一些关于此的信息:http://docs.python.org/tutorial/datastructures.html#comparing-sequences-and-other-types